authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-06-15 16:10:53-04:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-07-07 22:59:52-04:00
log525f341f33af9b8aad53931fd5511f00a82cb090
treecec3280498c1122858580946ac5e31f8feb807ce
parent8f20e81b8816aadd8ceb1b04bd3727cc1d124464

Zcu: introduce `PerThread` and pass to all the functions


56 files changed, 11266 insertions(+), 9961 deletions(-)

CMakeLists.txt+1
......@@ -525,6 +525,7 @@ set(ZIG_STAGE2_SOURCES
525525 src/Type.zig
526526 src/Value.zig
527527 src/Zcu.zig
528 src/Zcu/PerThread.zig
528529 src/arch/aarch64/CodeGen.zig
529530 src/arch/aarch64/Emit.zig
530531 src/arch/aarch64/Mir.zig
lib/std/Thread/Pool.zig+86-10
......@@ -9,17 +9,19 @@ run_queue: RunQueue = .{},
99is_running: bool = true,
1010allocator: std.mem.Allocator,
1111threads: []std.Thread,
12ids: std.AutoArrayHashMapUnmanaged(std.Thread.Id, void),
1213
1314const RunQueue = std.SinglyLinkedList(Runnable);
1415const Runnable = struct {
1516 runFn: RunProto,
1617};
1718
18const RunProto = *const fn (*Runnable) void;
19const RunProto = *const fn (*Runnable, id: ?usize) void;
1920
2021pub const Options = struct {
2122 allocator: std.mem.Allocator,
2223 n_jobs: ?u32 = null,
24 track_ids: bool = false,
2325};
2426
2527pub fn init(pool: *Pool, options: Options) !void {
......@@ -28,6 +30,7 @@ pub fn init(pool: *Pool, options: Options) !void {
2830 pool.* = .{
2931 .allocator = allocator,
3032 .threads = &[_]std.Thread{},
33 .ids = .{},
3134 };
3235
3336 if (builtin.single_threaded) {
......@@ -35,6 +38,10 @@ pub fn init(pool: *Pool, options: Options) !void {
3538 }
3639
3740 const thread_count = options.n_jobs orelse @max(1, std.Thread.getCpuCount() catch 1);
41 if (options.track_ids) {
42 try pool.ids.ensureTotalCapacity(allocator, 1 + thread_count);
43 pool.ids.putAssumeCapacityNoClobber(std.Thread.getCurrentId(), {});
44 }
3845
3946 // kill and join any threads we spawned and free memory on error.
4047 pool.threads = try allocator.alloc(std.Thread, thread_count);
......@@ -49,6 +56,7 @@ pub fn init(pool: *Pool, options: Options) !void {
4956
5057pub fn deinit(pool: *Pool) void {
5158 pool.join(pool.threads.len); // kill and join all threads.
59 pool.ids.deinit(pool.allocator);
5260 pool.* = undefined;
5361}
5462
......@@ -96,7 +104,7 @@ pub fn spawnWg(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args
96104 run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } },
97105 wait_group: *WaitGroup,
98106
99 fn runFn(runnable: *Runnable) void {
107 fn runFn(runnable: *Runnable, _: ?usize) void {
100108 const run_node: *RunQueue.Node = @fieldParentPtr("data", runnable);
101109 const closure: *@This() = @alignCast(@fieldParentPtr("run_node", run_node));
102110 @call(.auto, func, closure.arguments);
......@@ -134,6 +142,70 @@ pub fn spawnWg(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args
134142 pool.cond.signal();
135143}
136144
145/// Runs `func` in the thread pool, calling `WaitGroup.start` beforehand, and
146/// `WaitGroup.finish` after it returns.
147///
148/// The first argument passed to `func` is a dense `usize` thread id, the rest
149/// of the arguments are passed from `args`. Requires the pool to have been
150/// initialized with `.track_ids = true`.
151///
152/// In the case that queuing the function call fails to allocate memory, or the
153/// target is single-threaded, the function is called directly.
154pub fn spawnWgId(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args: anytype) void {
155 wait_group.start();
156
157 if (builtin.single_threaded) {
158 @call(.auto, func, .{0} ++ args);
159 wait_group.finish();
160 return;
161 }
162
163 const Args = @TypeOf(args);
164 const Closure = struct {
165 arguments: Args,
166 pool: *Pool,
167 run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } },
168 wait_group: *WaitGroup,
169
170 fn runFn(runnable: *Runnable, id: ?usize) void {
171 const run_node: *RunQueue.Node = @fieldParentPtr("data", runnable);
172 const closure: *@This() = @alignCast(@fieldParentPtr("run_node", run_node));
173 @call(.auto, func, .{id.?} ++ closure.arguments);
174 closure.wait_group.finish();
175
176 // The thread pool's allocator is protected by the mutex.
177 const mutex = &closure.pool.mutex;
178 mutex.lock();
179 defer mutex.unlock();
180
181 closure.pool.allocator.destroy(closure);
182 }
183 };
184
185 {
186 pool.mutex.lock();
187
188 const closure = pool.allocator.create(Closure) catch {
189 const id = pool.ids.getIndex(std.Thread.getCurrentId());
190 pool.mutex.unlock();
191 @call(.auto, func, .{id.?} ++ args);
192 wait_group.finish();
193 return;
194 };
195 closure.* = .{
196 .arguments = args,
197 .pool = pool,
198 .wait_group = wait_group,
199 };
200
201 pool.run_queue.prepend(&closure.run_node);
202 pool.mutex.unlock();
203 }
204
205 // Notify waiting threads outside the lock to try and keep the critical section small.
206 pool.cond.signal();
207}
208
137209pub fn spawn(pool: *Pool, comptime func: anytype, args: anytype) !void {
138210 if (builtin.single_threaded) {
139211 @call(.auto, func, args);
......@@ -181,14 +253,16 @@ fn worker(pool: *Pool) void {
181253 pool.mutex.lock();
182254 defer pool.mutex.unlock();
183255
256 const id = if (pool.ids.count() > 0) pool.ids.count() else null;
257 if (id) |_| pool.ids.putAssumeCapacityNoClobber(std.Thread.getCurrentId(), {});
258
184259 while (true) {
185260 while (pool.run_queue.popFirst()) |run_node| {
186261 // Temporarily unlock the mutex in order to execute the run_node
187262 pool.mutex.unlock();
188263 defer pool.mutex.lock();
189264
190 const runFn = run_node.data.runFn;
191 runFn(&run_node.data);
265 run_node.data.runFn(&run_node.data, id);
192266 }
193267
194268 // Stop executing instead of waiting if the thread pool is no longer running.
......@@ -201,16 +275,18 @@ fn worker(pool: *Pool) void {
201275}
202276
203277pub fn waitAndWork(pool: *Pool, wait_group: *WaitGroup) void {
278 var id: ?usize = null;
279
204280 while (!wait_group.isDone()) {
205 if (blk: {
206 pool.mutex.lock();
207 defer pool.mutex.unlock();
208 break :blk pool.run_queue.popFirst();
209 }) |run_node| {
210 run_node.data.runFn(&run_node.data);
281 pool.mutex.lock();
282 if (pool.run_queue.popFirst()) |run_node| {
283 id = id orelse pool.ids.getIndex(std.Thread.getCurrentId());
284 pool.mutex.unlock();
285 run_node.data.runFn(&run_node.data, id);
211286 continue;
212287 }
213288
289 pool.mutex.unlock();
214290 wait_group.wait();
215291 return;
216292 }
src/Air.zig+2-2
......@@ -1563,12 +1563,12 @@ pub fn internedToRef(ip_index: InternPool.Index) Inst.Ref {
15631563}
15641564
15651565/// Returns `null` if runtime-known.
1566pub fn value(air: Air, inst: Inst.Ref, mod: *Module) !?Value {
1566pub fn value(air: Air, inst: Inst.Ref, pt: Zcu.PerThread) !?Value {
15671567 if (inst.toInterned()) |ip_index| {
15681568 return Value.fromInterned(ip_index);
15691569 }
15701570 const index = inst.toIndex().?;
1571 return air.typeOfIndex(index, &mod.intern_pool).onePossibleValue(mod);
1571 return air.typeOfIndex(index, &pt.zcu.intern_pool).onePossibleValue(pt);
15721572}
15731573
15741574pub fn nullTerminatedString(air: Air, index: usize) [:0]const u8 {
src/Compilation.zig+31-29
......@@ -2146,6 +2146,8 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21462146 try comp.performAllTheWork(main_progress_node);
21472147
21482148 if (comp.module) |zcu| {
2149 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = .main };
2150
21492151 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {
21502152 std.debug.print("intern pool stats for '{s}':\n", .{
21512153 comp.root_name,
......@@ -2165,10 +2167,10 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21652167 // The `test_functions` decl has been intentionally postponed until now,
21662168 // at which point we must populate it with the list of test functions that
21672169 // have been discovered and not filtered out.
2168 try zcu.populateTestFunctions(main_progress_node);
2170 try pt.populateTestFunctions(main_progress_node);
21692171 }
21702172
2171 try zcu.processExports();
2173 try pt.processExports();
21722174 }
21732175
21742176 if (comp.totalErrorCount() != 0) {
......@@ -2247,7 +2249,7 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
22472249 }
22482250 }
22492251
2250 try flush(comp, arena, main_progress_node);
2252 try flush(comp, arena, .main, main_progress_node);
22512253 if (comp.totalErrorCount() != 0) return;
22522254
22532255 // Failure here only means an unnecessary cache miss.
......@@ -2264,16 +2266,16 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
22642266 whole.lock = man.toOwnedLock();
22652267 },
22662268 .incremental => {
2267 try flush(comp, arena, main_progress_node);
2269 try flush(comp, arena, .main, main_progress_node);
22682270 if (comp.totalErrorCount() != 0) return;
22692271 },
22702272 }
22712273}
22722274
2273fn flush(comp: *Compilation, arena: Allocator, prog_node: std.Progress.Node) !void {
2275fn flush(comp: *Compilation, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
22742276 if (comp.bin_file) |lf| {
22752277 // This is needed before reading the error flags.
2276 lf.flush(arena, prog_node) catch |err| switch (err) {
2278 lf.flush(arena, tid, prog_node) catch |err| switch (err) {
22772279 error.FlushFailure => {}, // error reported through link_error_flags
22782280 error.LLDReportedFailure => {}, // error reported via lockAndParseLldStderr
22792281 else => |e| return e,
......@@ -3419,7 +3421,7 @@ pub fn performAllTheWork(
34193421
34203422 while (true) {
34213423 if (comp.work_queue.readItem()) |work_item| {
3422 try processOneJob(comp, work_item, main_progress_node);
3424 try processOneJob(0, comp, work_item, main_progress_node);
34233425 continue;
34243426 }
34253427 if (comp.module) |zcu| {
......@@ -3447,11 +3449,11 @@ pub fn performAllTheWork(
34473449 }
34483450}
34493451
3450fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {
3452fn processOneJob(tid: usize, comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {
34513453 switch (job) {
34523454 .codegen_decl => |decl_index| {
3453 const zcu = comp.module.?;
3454 const decl = zcu.declPtr(decl_index);
3455 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3456 const decl = pt.zcu.declPtr(decl_index);
34553457
34563458 switch (decl.analysis) {
34573459 .unreferenced => unreachable,
......@@ -3469,7 +3471,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34693471
34703472 assert(decl.has_tv);
34713473
3472 try zcu.linkerUpdateDecl(decl_index);
3474 try pt.linkerUpdateDecl(decl_index);
34733475 return;
34743476 },
34753477 }
......@@ -3478,16 +3480,16 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34783480 const named_frame = tracy.namedFrame("codegen_func");
34793481 defer named_frame.end();
34803482
3481 const zcu = comp.module.?;
3483 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
34823484 // This call takes ownership of `func.air`.
3483 try zcu.linkerUpdateFunc(func.func, func.air);
3485 try pt.linkerUpdateFunc(func.func, func.air);
34843486 },
34853487 .analyze_func => |func| {
34863488 const named_frame = tracy.namedFrame("analyze_func");
34873489 defer named_frame.end();
34883490
3489 const zcu = comp.module.?;
3490 zcu.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
3491 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3492 pt.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
34913493 error.OutOfMemory => return error.OutOfMemory,
34923494 error.AnalysisFail => return,
34933495 };
......@@ -3496,8 +3498,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34963498 if (true) @panic("regressed compiler feature: emit-h should hook into updateExports, " ++
34973499 "not decl analysis, which is too early to know about @export calls");
34983500
3499 const zcu = comp.module.?;
3500 const decl = zcu.declPtr(decl_index);
3501 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3502 const decl = pt.zcu.declPtr(decl_index);
35013503
35023504 switch (decl.analysis) {
35033505 .unreferenced => unreachable,
......@@ -3515,7 +3517,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35153517 defer named_frame.end();
35163518
35173519 const gpa = comp.gpa;
3518 const emit_h = zcu.emit_h.?;
3520 const emit_h = pt.zcu.emit_h.?;
35193521 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
35203522 const decl_emit_h = emit_h.declPtr(decl_index);
35213523 const fwd_decl = &decl_emit_h.fwd_decl;
......@@ -3523,11 +3525,11 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35233525 var ctypes_arena = std.heap.ArenaAllocator.init(gpa);
35243526 defer ctypes_arena.deinit();
35253527
3526 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
3528 const file_scope = pt.zcu.namespacePtr(decl.src_namespace).fileScope(pt.zcu);
35273529
35283530 var dg: c_codegen.DeclGen = .{
35293531 .gpa = gpa,
3530 .zcu = zcu,
3532 .pt = pt,
35313533 .mod = file_scope.mod,
35323534 .error_msg = null,
35333535 .pass = .{ .decl = decl_index },
......@@ -3557,25 +3559,25 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35573559 }
35583560 },
35593561 .analyze_decl => |decl_index| {
3560 const zcu = comp.module.?;
3561 zcu.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
3562 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3563 pt.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
35623564 error.OutOfMemory => return error.OutOfMemory,
35633565 error.AnalysisFail => return,
35643566 };
3565 const decl = zcu.declPtr(decl_index);
3567 const decl = pt.zcu.declPtr(decl_index);
35663568 if (decl.kind == .@"test" and comp.config.is_test) {
35673569 // Tests are always emitted in test binaries. The decl_refs are created by
35683570 // Zcu.populateTestFunctions, but this will not queue body analysis, so do
35693571 // that now.
3570 try zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
3572 try pt.zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
35713573 }
35723574 },
35733575 .resolve_type_fully => |ty| {
35743576 const named_frame = tracy.namedFrame("resolve_type_fully");
35753577 defer named_frame.end();
35763578
3577 const zcu = comp.module.?;
3578 Type.fromInterned(ty).resolveFully(zcu) catch |err| switch (err) {
3579 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3580 Type.fromInterned(ty).resolveFully(pt) catch |err| switch (err) {
35793581 error.OutOfMemory => return error.OutOfMemory,
35803582 error.AnalysisFail => return,
35813583 };
......@@ -3603,12 +3605,12 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
36033605 try zcu.retryable_failures.append(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
36043606 };
36053607 },
3606 .analyze_mod => |pkg| {
3608 .analyze_mod => |mod| {
36073609 const named_frame = tracy.namedFrame("analyze_mod");
36083610 defer named_frame.end();
36093611
3610 const zcu = comp.module.?;
3611 zcu.semaPkg(pkg) catch |err| switch (err) {
3612 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3613 pt.semaPkg(mod) catch |err| switch (err) {
36123614 error.OutOfMemory => return error.OutOfMemory,
36133615 error.AnalysisFail => return,
36143616 };
src/InternPool.zig+156-86
......@@ -4548,17 +4548,14 @@ pub fn init(ip: *InternPool, gpa: Allocator) !void {
45484548
45494549 // This inserts all the statically-known values into the intern pool in the
45504550 // order expected.
4551 for (static_keys[0..@intFromEnum(Index.empty_struct_type)]) |key| {
4552 _ = ip.get(gpa, key) catch unreachable;
4553 }
4554 _ = ip.getAnonStructType(gpa, .{
4555 .types = &.{},
4556 .names = &.{},
4557 .values = &.{},
4558 }) catch unreachable;
4559 for (static_keys[@intFromEnum(Index.empty_struct_type) + 1 ..]) |key| {
4560 _ = ip.get(gpa, key) catch unreachable;
4561 }
4551 for (&static_keys, 0..) |key, key_index| switch (@as(Index, @enumFromInt(key_index))) {
4552 .empty_struct_type => assert(try ip.getAnonStructType(gpa, .main, .{
4553 .types = &.{},
4554 .names = &.{},
4555 .values = &.{},
4556 }) == .empty_struct_type),
4557 else => |expected_index| assert(try ip.get(gpa, .main, key) == expected_index),
4558 };
45624559
45634560 if (std.debug.runtime_safety) {
45644561 // Sanity check.
......@@ -5242,7 +5239,7 @@ fn indexToKeyBigInt(ip: *const InternPool, limb_index: u32, positive: bool) Key
52425239 } };
52435240}
52445241
5245pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
5242pub fn get(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, key: Key) Allocator.Error!Index {
52465243 const adapter: KeyAdapter = .{ .intern_pool = ip };
52475244 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
52485245 if (gop.found_existing) return @enumFromInt(gop.index);
......@@ -5266,8 +5263,9 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
52665263 _ = ip.map.pop();
52675264 var new_key = key;
52685265 new_key.ptr_type.flags.size = .Many;
5269 const ptr_type_index = try ip.get(gpa, new_key);
5266 const ptr_type_index = try ip.get(gpa, tid, new_key);
52705267 assert(!(try ip.map.getOrPutAdapted(gpa, key, adapter)).found_existing);
5268
52715269 try ip.items.ensureUnusedCapacity(gpa, 1);
52725270 ip.items.appendAssumeCapacity(.{
52735271 .tag = .type_slice,
......@@ -5519,7 +5517,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
55195517 else => unreachable,
55205518 }
55215519 _ = ip.map.pop();
5522 const index_index = try ip.get(gpa, .{ .int = .{
5520 const index_index = try ip.get(gpa, tid, .{ .int = .{
55235521 .ty = .usize_type,
55245522 .storage = .{ .u64 = base_index.index },
55255523 } });
......@@ -5932,7 +5930,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
59325930 const elem = switch (aggregate.storage) {
59335931 .bytes => |bytes| elem: {
59345932 _ = ip.map.pop();
5935 const elem = try ip.get(gpa, .{ .int = .{
5933 const elem = try ip.get(gpa, tid, .{ .int = .{
59365934 .ty = .u8_type,
59375935 .storage = .{ .u64 = bytes.at(0, ip) },
59385936 } });
......@@ -6074,7 +6072,12 @@ pub const UnionTypeInit = struct {
60746072 },
60756073};
60766074
6077pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocator.Error!WipNamespaceType.Result {
6075pub fn getUnionType(
6076 ip: *InternPool,
6077 gpa: Allocator,
6078 _: Zcu.PerThread.Id,
6079 ini: UnionTypeInit,
6080) Allocator.Error!WipNamespaceType.Result {
60786081 const adapter: KeyAdapter = .{ .intern_pool = ip };
60796082 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .union_type = switch (ini.key) {
60806083 .declared => |d| .{ .declared = .{
......@@ -6221,6 +6224,7 @@ pub const StructTypeInit = struct {
62216224pub fn getStructType(
62226225 ip: *InternPool,
62236226 gpa: Allocator,
6227 _: Zcu.PerThread.Id,
62246228 ini: StructTypeInit,
62256229) Allocator.Error!WipNamespaceType.Result {
62266230 const adapter: KeyAdapter = .{ .intern_pool = ip };
......@@ -6396,7 +6400,12 @@ pub const AnonStructTypeInit = struct {
63966400 values: []const Index,
63976401};
63986402
6399pub fn getAnonStructType(ip: *InternPool, gpa: Allocator, ini: AnonStructTypeInit) Allocator.Error!Index {
6403pub fn getAnonStructType(
6404 ip: *InternPool,
6405 gpa: Allocator,
6406 _: Zcu.PerThread.Id,
6407 ini: AnonStructTypeInit,
6408) Allocator.Error!Index {
64006409 assert(ini.types.len == ini.values.len);
64016410 for (ini.types) |elem| assert(elem != .none);
64026411
......@@ -6450,7 +6459,12 @@ pub const GetFuncTypeKey = struct {
64506459 addrspace_is_generic: bool = false,
64516460};
64526461
6453pub fn getFuncType(ip: *InternPool, gpa: Allocator, key: GetFuncTypeKey) Allocator.Error!Index {
6462pub fn getFuncType(
6463 ip: *InternPool,
6464 gpa: Allocator,
6465 _: Zcu.PerThread.Id,
6466 key: GetFuncTypeKey,
6467) Allocator.Error!Index {
64546468 // Validate input parameters.
64556469 assert(key.return_type != .none);
64566470 for (key.param_types) |param_type| assert(param_type != .none);
......@@ -6503,7 +6517,12 @@ pub fn getFuncType(ip: *InternPool, gpa: Allocator, key: GetFuncTypeKey) Allocat
65036517 return @enumFromInt(ip.items.len - 1);
65046518}
65056519
6506pub fn getExternFunc(ip: *InternPool, gpa: Allocator, key: Key.ExternFunc) Allocator.Error!Index {
6520pub fn getExternFunc(
6521 ip: *InternPool,
6522 gpa: Allocator,
6523 _: Zcu.PerThread.Id,
6524 key: Key.ExternFunc,
6525) Allocator.Error!Index {
65076526 const adapter: KeyAdapter = .{ .intern_pool = ip };
65086527 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .extern_func = key }, adapter);
65096528 if (gop.found_existing) return @enumFromInt(gop.index);
......@@ -6531,7 +6550,12 @@ pub const GetFuncDeclKey = struct {
65316550 is_noinline: bool,
65326551};
65336552
6534pub fn getFuncDecl(ip: *InternPool, gpa: Allocator, key: GetFuncDeclKey) Allocator.Error!Index {
6553pub fn getFuncDecl(
6554 ip: *InternPool,
6555 gpa: Allocator,
6556 _: Zcu.PerThread.Id,
6557 key: GetFuncDeclKey,
6558) Allocator.Error!Index {
65356559 // The strategy here is to add the function type unconditionally, then to
65366560 // ask if it already exists, and if so, revert the lengths of the mutated
65376561 // arrays. This is similar to what `getOrPutTrailingString` does.
......@@ -6598,7 +6622,12 @@ pub const GetFuncDeclIesKey = struct {
65986622 rbrace_column: u32,
65996623};
66006624
6601pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) Allocator.Error!Index {
6625pub fn getFuncDeclIes(
6626 ip: *InternPool,
6627 gpa: Allocator,
6628 _: Zcu.PerThread.Id,
6629 key: GetFuncDeclIesKey,
6630) Allocator.Error!Index {
66026631 // Validate input parameters.
66036632 assert(key.bare_return_type != .none);
66046633 for (key.param_types) |param_type| assert(param_type != .none);
......@@ -6707,6 +6736,7 @@ pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) A
67076736pub fn getErrorSetType(
67086737 ip: *InternPool,
67096738 gpa: Allocator,
6739 _: Zcu.PerThread.Id,
67106740 names: []const NullTerminatedString,
67116741) Allocator.Error!Index {
67126742 assert(std.sort.isSorted(NullTerminatedString, names, {}, NullTerminatedString.indexLessThan));
......@@ -6770,11 +6800,16 @@ pub const GetFuncInstanceKey = struct {
67706800 inferred_error_set: bool,
67716801};
67726802
6773pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey) Allocator.Error!Index {
6803pub fn getFuncInstance(
6804 ip: *InternPool,
6805 gpa: Allocator,
6806 tid: Zcu.PerThread.Id,
6807 arg: GetFuncInstanceKey,
6808) Allocator.Error!Index {
67746809 if (arg.inferred_error_set)
6775 return getFuncInstanceIes(ip, gpa, arg);
6810 return getFuncInstanceIes(ip, gpa, tid, arg);
67766811
6777 const func_ty = try ip.getFuncType(gpa, .{
6812 const func_ty = try ip.getFuncType(gpa, tid, .{
67786813 .param_types = arg.param_types,
67796814 .return_type = arg.bare_return_type,
67806815 .noalias_bits = arg.noalias_bits,
......@@ -6844,6 +6879,7 @@ pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey)
68446879pub fn getFuncInstanceIes(
68456880 ip: *InternPool,
68466881 gpa: Allocator,
6882 _: Zcu.PerThread.Id,
68476883 arg: GetFuncInstanceKey,
68486884) Allocator.Error!Index {
68496885 // Validate input parameters.
......@@ -6955,7 +6991,6 @@ pub fn getFuncInstanceIes(
69556991 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
69566992 .func_type = extraFuncType(ip, func_type_extra_index),
69576993 }, adapter).found_existing);
6958
69596994 return finishFuncInstance(
69606995 ip,
69616996 gpa,
......@@ -7096,6 +7131,7 @@ pub const WipEnumType = struct {
70967131pub fn getEnumType(
70977132 ip: *InternPool,
70987133 gpa: Allocator,
7134 _: Zcu.PerThread.Id,
70997135 ini: EnumTypeInit,
71007136) Allocator.Error!WipEnumType.Result {
71017137 const adapter: KeyAdapter = .{ .intern_pool = ip };
......@@ -7172,7 +7208,7 @@ pub fn getEnumType(
71727208 break :m values_map.toOptional();
71737209 };
71747210 errdefer if (ini.has_values) {
7175 _ = ip.map.pop();
7211 _ = ip.maps.pop();
71767212 };
71777213
71787214 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(EnumExplicit).Struct.fields.len +
......@@ -7245,7 +7281,12 @@ const GeneratedTagEnumTypeInit = struct {
72457281/// Creates an enum type which was automatically-generated as the tag type of a
72467282/// `union` with no explicit tag type. Since this is only called once per union
72477283/// type, it asserts that no matching type yet exists.
7248pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTagEnumTypeInit) Allocator.Error!Index {
7284pub fn getGeneratedTagEnumType(
7285 ip: *InternPool,
7286 gpa: Allocator,
7287 _: Zcu.PerThread.Id,
7288 ini: GeneratedTagEnumTypeInit,
7289) Allocator.Error!Index {
72497290 assert(ip.isUnion(ini.owner_union_ty));
72507291 assert(ip.isIntegerType(ini.tag_ty));
72517292 for (ini.values) |val| assert(ip.typeOf(val) == ini.tag_ty);
......@@ -7342,7 +7383,12 @@ pub const OpaqueTypeInit = struct {
73427383 },
73437384};
73447385
7345pub fn getOpaqueType(ip: *InternPool, gpa: Allocator, ini: OpaqueTypeInit) Allocator.Error!WipNamespaceType.Result {
7386pub fn getOpaqueType(
7387 ip: *InternPool,
7388 gpa: Allocator,
7389 _: Zcu.PerThread.Id,
7390 ini: OpaqueTypeInit,
7391) Allocator.Error!WipNamespaceType.Result {
73467392 const adapter: KeyAdapter = .{ .intern_pool = ip };
73477393 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .opaque_type = switch (ini.key) {
73487394 .declared => |d| .{ .declared = .{
......@@ -7680,23 +7726,23 @@ test "basic usage" {
76807726 var ip: InternPool = .{};
76817727 defer ip.deinit(gpa);
76827728
7683 const i32_type = try ip.get(gpa, .{ .int_type = .{
7729 const i32_type = try ip.get(gpa, .main, .{ .int_type = .{
76847730 .signedness = .signed,
76857731 .bits = 32,
76867732 } });
7687 const array_i32 = try ip.get(gpa, .{ .array_type = .{
7733 const array_i32 = try ip.get(gpa, .main, .{ .array_type = .{
76887734 .len = 10,
76897735 .child = i32_type,
76907736 .sentinel = .none,
76917737 } });
76927738
7693 const another_i32_type = try ip.get(gpa, .{ .int_type = .{
7739 const another_i32_type = try ip.get(gpa, .main, .{ .int_type = .{
76947740 .signedness = .signed,
76957741 .bits = 32,
76967742 } });
76977743 try std.testing.expect(another_i32_type == i32_type);
76987744
7699 const another_array_i32 = try ip.get(gpa, .{ .array_type = .{
7745 const another_array_i32 = try ip.get(gpa, .main, .{ .array_type = .{
77007746 .len = 10,
77017747 .child = i32_type,
77027748 .sentinel = .none,
......@@ -7766,48 +7812,54 @@ pub fn sliceLen(ip: *const InternPool, i: Index) Index {
77667812/// * payload => error union
77677813/// * fn <=> fn
77687814/// * aggregate <=> aggregate (where children can also be coerced)
7769pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
7815pub fn getCoerced(
7816 ip: *InternPool,
7817 gpa: Allocator,
7818 tid: Zcu.PerThread.Id,
7819 val: Index,
7820 new_ty: Index,
7821) Allocator.Error!Index {
77707822 const old_ty = ip.typeOf(val);
77717823 if (old_ty == new_ty) return val;
77727824
77737825 const tags = ip.items.items(.tag);
77747826
77757827 switch (val) {
7776 .undef => return ip.get(gpa, .{ .undef = new_ty }),
7828 .undef => return ip.get(gpa, tid, .{ .undef = new_ty }),
77777829 .null_value => {
7778 if (ip.isOptionalType(new_ty)) return ip.get(gpa, .{ .opt = .{
7830 if (ip.isOptionalType(new_ty)) return ip.get(gpa, tid, .{ .opt = .{
77797831 .ty = new_ty,
77807832 .val = .none,
77817833 } });
77827834
77837835 if (ip.isPointerType(new_ty)) switch (ip.indexToKey(new_ty).ptr_type.flags.size) {
7784 .One, .Many, .C => return ip.get(gpa, .{ .ptr = .{
7836 .One, .Many, .C => return ip.get(gpa, tid, .{ .ptr = .{
77857837 .ty = new_ty,
77867838 .base_addr = .int,
77877839 .byte_offset = 0,
77887840 } }),
7789 .Slice => return ip.get(gpa, .{ .slice = .{
7841 .Slice => return ip.get(gpa, tid, .{ .slice = .{
77907842 .ty = new_ty,
7791 .ptr = try ip.get(gpa, .{ .ptr = .{
7843 .ptr = try ip.get(gpa, tid, .{ .ptr = .{
77927844 .ty = ip.slicePtrType(new_ty),
77937845 .base_addr = .int,
77947846 .byte_offset = 0,
77957847 } }),
7796 .len = try ip.get(gpa, .{ .undef = .usize_type }),
7848 .len = try ip.get(gpa, tid, .{ .undef = .usize_type }),
77977849 } }),
77987850 };
77997851 },
78007852 else => switch (tags[@intFromEnum(val)]) {
7801 .func_decl => return getCoercedFuncDecl(ip, gpa, val, new_ty),
7802 .func_instance => return getCoercedFuncInstance(ip, gpa, val, new_ty),
7853 .func_decl => return getCoercedFuncDecl(ip, gpa, tid, val, new_ty),
7854 .func_instance => return getCoercedFuncInstance(ip, gpa, tid, val, new_ty),
78037855 .func_coerced => {
78047856 const extra_index = ip.items.items(.data)[@intFromEnum(val)];
78057857 const func: Index = @enumFromInt(
78067858 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncCoerced, "func").?],
78077859 );
78087860 switch (tags[@intFromEnum(func)]) {
7809 .func_decl => return getCoercedFuncDecl(ip, gpa, val, new_ty),
7810 .func_instance => return getCoercedFuncInstance(ip, gpa, val, new_ty),
7861 .func_decl => return getCoercedFuncDecl(ip, gpa, tid, val, new_ty),
7862 .func_instance => return getCoercedFuncInstance(ip, gpa, tid, val, new_ty),
78117863 else => unreachable,
78127864 }
78137865 },
......@@ -7816,9 +7868,9 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78167868 }
78177869
78187870 switch (ip.indexToKey(val)) {
7819 .undef => return ip.get(gpa, .{ .undef = new_ty }),
7871 .undef => return ip.get(gpa, tid, .{ .undef = new_ty }),
78207872 .extern_func => |extern_func| if (ip.isFunctionType(new_ty))
7821 return ip.get(gpa, .{ .extern_func = .{
7873 return ip.get(gpa, tid, .{ .extern_func = .{
78227874 .ty = new_ty,
78237875 .decl = extern_func.decl,
78247876 .lib_name = extern_func.lib_name,
......@@ -7827,12 +7879,12 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78277879 .func => unreachable,
78287880
78297881 .int => |int| switch (ip.indexToKey(new_ty)) {
7830 .enum_type => return ip.get(gpa, .{ .enum_tag = .{
7882 .enum_type => return ip.get(gpa, tid, .{ .enum_tag = .{
78317883 .ty = new_ty,
7832 .int = try ip.getCoerced(gpa, val, ip.loadEnumType(new_ty).tag_ty),
7884 .int = try ip.getCoerced(gpa, tid, val, ip.loadEnumType(new_ty).tag_ty),
78337885 } }),
78347886 .ptr_type => switch (int.storage) {
7835 inline .u64, .i64 => |int_val| return ip.get(gpa, .{ .ptr = .{
7887 inline .u64, .i64 => |int_val| return ip.get(gpa, tid, .{ .ptr = .{
78367888 .ty = new_ty,
78377889 .base_addr = .int,
78387890 .byte_offset = @intCast(int_val),
......@@ -7841,7 +7893,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78417893 .lazy_align, .lazy_size => {},
78427894 },
78437895 else => if (ip.isIntegerType(new_ty))
7844 return getCoercedInts(ip, gpa, int, new_ty),
7896 return ip.getCoercedInts(gpa, tid, int, new_ty),
78457897 },
78467898 .float => |float| switch (ip.indexToKey(new_ty)) {
78477899 .simple_type => |simple| switch (simple) {
......@@ -7852,7 +7904,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78527904 .f128,
78537905 .c_longdouble,
78547906 .comptime_float,
7855 => return ip.get(gpa, .{ .float = .{
7907 => return ip.get(gpa, tid, .{ .float = .{
78567908 .ty = new_ty,
78577909 .storage = float.storage,
78587910 } }),
......@@ -7861,17 +7913,17 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78617913 else => {},
78627914 },
78637915 .enum_tag => |enum_tag| if (ip.isIntegerType(new_ty))
7864 return getCoercedInts(ip, gpa, ip.indexToKey(enum_tag.int).int, new_ty),
7916 return ip.getCoercedInts(gpa, tid, ip.indexToKey(enum_tag.int).int, new_ty),
78657917 .enum_literal => |enum_literal| switch (ip.indexToKey(new_ty)) {
78667918 .enum_type => {
78677919 const enum_type = ip.loadEnumType(new_ty);
78687920 const index = enum_type.nameIndex(ip, enum_literal).?;
7869 return ip.get(gpa, .{ .enum_tag = .{
7921 return ip.get(gpa, tid, .{ .enum_tag = .{
78707922 .ty = new_ty,
78717923 .int = if (enum_type.values.len != 0)
78727924 enum_type.values.get(ip)[index]
78737925 else
7874 try ip.get(gpa, .{ .int = .{
7926 try ip.get(gpa, tid, .{ .int = .{
78757927 .ty = enum_type.tag_ty,
78767928 .storage = .{ .u64 = index },
78777929 } }),
......@@ -7880,22 +7932,22 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78807932 else => {},
78817933 },
78827934 .slice => |slice| if (ip.isPointerType(new_ty) and ip.indexToKey(new_ty).ptr_type.flags.size == .Slice)
7883 return ip.get(gpa, .{ .slice = .{
7935 return ip.get(gpa, tid, .{ .slice = .{
78847936 .ty = new_ty,
7885 .ptr = try ip.getCoerced(gpa, slice.ptr, ip.slicePtrType(new_ty)),
7937 .ptr = try ip.getCoerced(gpa, tid, slice.ptr, ip.slicePtrType(new_ty)),
78867938 .len = slice.len,
78877939 } })
78887940 else if (ip.isIntegerType(new_ty))
7889 return ip.getCoerced(gpa, slice.ptr, new_ty),
7941 return ip.getCoerced(gpa, tid, slice.ptr, new_ty),
78907942 .ptr => |ptr| if (ip.isPointerType(new_ty) and ip.indexToKey(new_ty).ptr_type.flags.size != .Slice)
7891 return ip.get(gpa, .{ .ptr = .{
7943 return ip.get(gpa, tid, .{ .ptr = .{
78927944 .ty = new_ty,
78937945 .base_addr = ptr.base_addr,
78947946 .byte_offset = ptr.byte_offset,
78957947 } })
78967948 else if (ip.isIntegerType(new_ty))
78977949 switch (ptr.base_addr) {
7898 .int => return ip.get(gpa, .{ .int = .{
7950 .int => return ip.get(gpa, tid, .{ .int = .{
78997951 .ty = .usize_type,
79007952 .storage = .{ .u64 = @intCast(ptr.byte_offset) },
79017953 } }),
......@@ -7904,44 +7956,44 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79047956 .opt => |opt| switch (ip.indexToKey(new_ty)) {
79057957 .ptr_type => |ptr_type| return switch (opt.val) {
79067958 .none => switch (ptr_type.flags.size) {
7907 .One, .Many, .C => try ip.get(gpa, .{ .ptr = .{
7959 .One, .Many, .C => try ip.get(gpa, tid, .{ .ptr = .{
79087960 .ty = new_ty,
79097961 .base_addr = .int,
79107962 .byte_offset = 0,
79117963 } }),
7912 .Slice => try ip.get(gpa, .{ .slice = .{
7964 .Slice => try ip.get(gpa, tid, .{ .slice = .{
79137965 .ty = new_ty,
7914 .ptr = try ip.get(gpa, .{ .ptr = .{
7966 .ptr = try ip.get(gpa, tid, .{ .ptr = .{
79157967 .ty = ip.slicePtrType(new_ty),
79167968 .base_addr = .int,
79177969 .byte_offset = 0,
79187970 } }),
7919 .len = try ip.get(gpa, .{ .undef = .usize_type }),
7971 .len = try ip.get(gpa, tid, .{ .undef = .usize_type }),
79207972 } }),
79217973 },
7922 else => |payload| try ip.getCoerced(gpa, payload, new_ty),
7974 else => |payload| try ip.getCoerced(gpa, tid, payload, new_ty),
79237975 },
7924 .opt_type => |child_type| return try ip.get(gpa, .{ .opt = .{
7976 .opt_type => |child_type| return try ip.get(gpa, tid, .{ .opt = .{
79257977 .ty = new_ty,
79267978 .val = switch (opt.val) {
79277979 .none => .none,
7928 else => try ip.getCoerced(gpa, opt.val, child_type),
7980 else => try ip.getCoerced(gpa, tid, opt.val, child_type),
79297981 },
79307982 } }),
79317983 else => {},
79327984 },
79337985 .err => |err| if (ip.isErrorSetType(new_ty))
7934 return ip.get(gpa, .{ .err = .{
7986 return ip.get(gpa, tid, .{ .err = .{
79357987 .ty = new_ty,
79367988 .name = err.name,
79377989 } })
79387990 else if (ip.isErrorUnionType(new_ty))
7939 return ip.get(gpa, .{ .error_union = .{
7991 return ip.get(gpa, tid, .{ .error_union = .{
79407992 .ty = new_ty,
79417993 .val = .{ .err_name = err.name },
79427994 } }),
79437995 .error_union => |error_union| if (ip.isErrorUnionType(new_ty))
7944 return ip.get(gpa, .{ .error_union = .{
7996 return ip.get(gpa, tid, .{ .error_union = .{
79457997 .ty = new_ty,
79467998 .val = error_union.val,
79477999 } }),
......@@ -7960,20 +8012,20 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79608012 };
79618013 if (old_ty_child != new_ty_child) break :direct;
79628014 switch (aggregate.storage) {
7963 .bytes => |bytes| return ip.get(gpa, .{ .aggregate = .{
8015 .bytes => |bytes| return ip.get(gpa, tid, .{ .aggregate = .{
79648016 .ty = new_ty,
79658017 .storage = .{ .bytes = bytes },
79668018 } }),
79678019 .elems => |elems| {
79688020 const elems_copy = try gpa.dupe(Index, elems[0..new_len]);
79698021 defer gpa.free(elems_copy);
7970 return ip.get(gpa, .{ .aggregate = .{
8022 return ip.get(gpa, tid, .{ .aggregate = .{
79718023 .ty = new_ty,
79728024 .storage = .{ .elems = elems_copy },
79738025 } });
79748026 },
79758027 .repeated_elem => |elem| {
7976 return ip.get(gpa, .{ .aggregate = .{
8028 return ip.get(gpa, tid, .{ .aggregate = .{
79778029 .ty = new_ty,
79788030 .storage = .{ .repeated_elem = elem },
79798031 } });
......@@ -7991,7 +8043,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79918043 // We have to intern each value here, so unfortunately we can't easily avoid
79928044 // the repeated indexToKey calls.
79938045 for (agg_elems, 0..) |*elem, index| {
7994 elem.* = try ip.get(gpa, .{ .int = .{
8046 elem.* = try ip.get(gpa, tid, .{ .int = .{
79958047 .ty = .u8_type,
79968048 .storage = .{ .u64 = bytes.at(index, ip) },
79978049 } });
......@@ -8008,27 +8060,27 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
80088060 .struct_type => ip.loadStructType(new_ty).field_types.get(ip)[i],
80098061 else => unreachable,
80108062 };
8011 elem.* = try ip.getCoerced(gpa, elem.*, new_elem_ty);
8063 elem.* = try ip.getCoerced(gpa, tid, elem.*, new_elem_ty);
80128064 }
8013 return ip.get(gpa, .{ .aggregate = .{ .ty = new_ty, .storage = .{ .elems = agg_elems } } });
8065 return ip.get(gpa, tid, .{ .aggregate = .{ .ty = new_ty, .storage = .{ .elems = agg_elems } } });
80148066 },
80158067 else => {},
80168068 }
80178069
80188070 switch (ip.indexToKey(new_ty)) {
80198071 .opt_type => |child_type| switch (val) {
8020 .null_value => return ip.get(gpa, .{ .opt = .{
8072 .null_value => return ip.get(gpa, tid, .{ .opt = .{
80218073 .ty = new_ty,
80228074 .val = .none,
80238075 } }),
8024 else => return ip.get(gpa, .{ .opt = .{
8076 else => return ip.get(gpa, tid, .{ .opt = .{
80258077 .ty = new_ty,
8026 .val = try ip.getCoerced(gpa, val, child_type),
8078 .val = try ip.getCoerced(gpa, tid, val, child_type),
80278079 } }),
80288080 },
8029 .error_union_type => |error_union_type| return ip.get(gpa, .{ .error_union = .{
8081 .error_union_type => |error_union_type| return ip.get(gpa, tid, .{ .error_union = .{
80308082 .ty = new_ty,
8031 .val = .{ .payload = try ip.getCoerced(gpa, val, error_union_type.payload_type) },
8083 .val = .{ .payload = try ip.getCoerced(gpa, tid, val, error_union_type.payload_type) },
80328084 } }),
80338085 else => {},
80348086 }
......@@ -8042,27 +8094,45 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
80428094 unreachable;
80438095}
80448096
8045fn getCoercedFuncDecl(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
8097fn getCoercedFuncDecl(
8098 ip: *InternPool,
8099 gpa: Allocator,
8100 tid: Zcu.PerThread.Id,
8101 val: Index,
8102 new_ty: Index,
8103) Allocator.Error!Index {
80468104 const datas = ip.items.items(.data);
80478105 const extra_index = datas[@intFromEnum(val)];
80488106 const prev_ty: Index = @enumFromInt(
80498107 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncDecl, "ty").?],
80508108 );
80518109 if (new_ty == prev_ty) return val;
8052 return getCoercedFunc(ip, gpa, val, new_ty);
8110 return getCoercedFunc(ip, gpa, tid, val, new_ty);
80538111}
80548112
8055fn getCoercedFuncInstance(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
8113fn getCoercedFuncInstance(
8114 ip: *InternPool,
8115 gpa: Allocator,
8116 tid: Zcu.PerThread.Id,
8117 val: Index,
8118 new_ty: Index,
8119) Allocator.Error!Index {
80568120 const datas = ip.items.items(.data);
80578121 const extra_index = datas[@intFromEnum(val)];
80588122 const prev_ty: Index = @enumFromInt(
80598123 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncInstance, "ty").?],
80608124 );
80618125 if (new_ty == prev_ty) return val;
8062 return getCoercedFunc(ip, gpa, val, new_ty);
8126 return getCoercedFunc(ip, gpa, tid, val, new_ty);
80638127}
80648128
8065fn getCoercedFunc(ip: *InternPool, gpa: Allocator, func: Index, ty: Index) Allocator.Error!Index {
8129fn getCoercedFunc(
8130 ip: *InternPool,
8131 gpa: Allocator,
8132 _: Zcu.PerThread.Id,
8133 func: Index,
8134 ty: Index,
8135) Allocator.Error!Index {
80668136 const prev_extra_len = ip.extra.items.len;
80678137 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncCoerced).Struct.fields.len);
80688138 try ip.items.ensureUnusedCapacity(gpa, 1);
......@@ -8092,7 +8162,7 @@ fn getCoercedFunc(ip: *InternPool, gpa: Allocator, func: Index, ty: Index) Alloc
80928162
80938163/// Asserts `val` has an integer type.
80948164/// Assumes `new_ty` is an integer type.
8095pub fn getCoercedInts(ip: *InternPool, gpa: Allocator, int: Key.Int, new_ty: Index) Allocator.Error!Index {
8165pub fn getCoercedInts(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, int: Key.Int, new_ty: Index) Allocator.Error!Index {
80968166 // The key cannot be passed directly to `get`, otherwise in the case of
80978167 // big_int storage, the limbs would be invalidated before they are read.
80988168 // Here we pre-reserve the limbs to ensure that the logic in `addInt` will
......@@ -8111,7 +8181,7 @@ pub fn getCoercedInts(ip: *InternPool, gpa: Allocator, int: Key.Int, new_ty: Ind
81118181 } };
81128182 },
81138183 };
8114 return ip.get(gpa, .{ .int = .{
8184 return ip.get(gpa, tid, .{ .int = .{
81158185 .ty = new_ty,
81168186 .storage = new_storage,
81178187 } });
src/RangeSet.zig+15-17
......@@ -6,13 +6,11 @@ const InternPool = @import("InternPool.zig");
66const Type = @import("Type.zig");
77const Value = @import("Value.zig");
88const Zcu = @import("Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
119const RangeSet = @This();
1210const LazySrcLoc = Zcu.LazySrcLoc;
1311
12pt: Zcu.PerThread,
1413ranges: std.ArrayList(Range),
15module: *Module,
1614
1715pub const Range = struct {
1816 first: InternPool.Index,
......@@ -20,10 +18,10 @@ pub const Range = struct {
2018 src: LazySrcLoc,
2119};
2220
23pub fn init(allocator: std.mem.Allocator, module: *Module) RangeSet {
21pub fn init(allocator: std.mem.Allocator, pt: Zcu.PerThread) RangeSet {
2422 return .{
23 .pt = pt,
2524 .ranges = std.ArrayList(Range).init(allocator),
26 .module = module,
2725 };
2826}
2927
......@@ -37,8 +35,8 @@ pub fn add(
3735 last: InternPool.Index,
3836 src: LazySrcLoc,
3937) !?LazySrcLoc {
40 const mod = self.module;
41 const ip = &mod.intern_pool;
38 const pt = self.pt;
39 const ip = &pt.zcu.intern_pool;
4240
4341 const ty = ip.typeOf(first);
4442 assert(ty == ip.typeOf(last));
......@@ -47,8 +45,8 @@ pub fn add(
4745 assert(ty == ip.typeOf(range.first));
4846 assert(ty == ip.typeOf(range.last));
4947
50 if (Value.fromInterned(last).compareScalar(.gte, Value.fromInterned(range.first), Type.fromInterned(ty), mod) and
51 Value.fromInterned(first).compareScalar(.lte, Value.fromInterned(range.last), Type.fromInterned(ty), mod))
48 if (Value.fromInterned(last).compareScalar(.gte, Value.fromInterned(range.first), Type.fromInterned(ty), pt) and
49 Value.fromInterned(first).compareScalar(.lte, Value.fromInterned(range.last), Type.fromInterned(ty), pt))
5250 {
5351 return range.src; // They overlap.
5452 }
......@@ -63,20 +61,20 @@ pub fn add(
6361}
6462
6563/// Assumes a and b do not overlap
66fn lessThan(mod: *Module, a: Range, b: Range) bool {
67 const ty = Type.fromInterned(mod.intern_pool.typeOf(a.first));
68 return Value.fromInterned(a.first).compareScalar(.lt, Value.fromInterned(b.first), ty, mod);
64fn lessThan(pt: Zcu.PerThread, a: Range, b: Range) bool {
65 const ty = Type.fromInterned(pt.zcu.intern_pool.typeOf(a.first));
66 return Value.fromInterned(a.first).compareScalar(.lt, Value.fromInterned(b.first), ty, pt);
6967}
7068
7169pub fn spans(self: *RangeSet, first: InternPool.Index, last: InternPool.Index) !bool {
72 const mod = self.module;
73 const ip = &mod.intern_pool;
70 const pt = self.pt;
71 const ip = &pt.zcu.intern_pool;
7472 assert(ip.typeOf(first) == ip.typeOf(last));
7573
7674 if (self.ranges.items.len == 0)
7775 return false;
7876
79 std.mem.sort(Range, self.ranges.items, mod, lessThan);
77 std.mem.sort(Range, self.ranges.items, pt, lessThan);
8078
8179 if (self.ranges.items[0].first != first or
8280 self.ranges.items[self.ranges.items.len - 1].last != last)
......@@ -95,10 +93,10 @@ pub fn spans(self: *RangeSet, first: InternPool.Index, last: InternPool.Index) !
9593 const prev = self.ranges.items[i];
9694
9795 // prev.last + 1 == cur.first
98 try counter.copy(Value.fromInterned(prev.last).toBigInt(&space, mod));
96 try counter.copy(Value.fromInterned(prev.last).toBigInt(&space, pt));
9997 try counter.addScalar(&counter, 1);
10098
101 const cur_start_int = Value.fromInterned(cur.first).toBigInt(&space, mod);
99 const cur_start_int = Value.fromInterned(cur.first).toBigInt(&space, pt);
102100 if (!cur_start_int.eql(counter.toConst())) {
103101 return false;
104102 }
src/Sema.zig+2671-2297
......@@ -5,7 +5,7 @@
55//! Does type checking, comptime control flow, and safety-check generation.
66//! This is the the heart of the Zig compiler.
77
8mod: *Module,
8pt: Zcu.PerThread,
99/// Alias to `mod.gpa`.
1010gpa: Allocator,
1111/// Points to the temporary arena allocator of the Sema.
......@@ -146,7 +146,7 @@ const ComptimeAlloc = struct {
146146fn newComptimeAlloc(sema: *Sema, block: *Block, ty: Type, alignment: Alignment) !ComptimeAllocIndex {
147147 const idx = sema.comptime_allocs.items.len;
148148 try sema.comptime_allocs.append(sema.gpa, .{
149 .val = .{ .interned = try sema.mod.intern(.{ .undef = ty.toIntern() }) },
149 .val = .{ .interned = try sema.pt.intern(.{ .undef = ty.toIntern() }) },
150150 .is_const = false,
151151 .alignment = alignment,
152152 .runtime_index = block.runtime_index,
......@@ -433,7 +433,7 @@ pub const Block = struct {
433433
434434 fn explain(cr: ComptimeReason, sema: *Sema, msg: ?*Module.ErrorMsg) !void {
435435 const parent = msg orelse return;
436 const mod = sema.mod;
436 const pt = sema.pt;
437437 const prefix = "expression is evaluated at comptime because ";
438438 switch (cr) {
439439 .c_import => |ci| {
......@@ -451,7 +451,7 @@ pub const Block = struct {
451451 ret_ty_src,
452452 parent,
453453 prefix ++ "the function returns a comptime-only type '{}'",
454 .{rt.return_ty.fmt(mod)},
454 .{rt.return_ty.fmt(pt)},
455455 );
456456 try sema.explainWhyTypeIsComptime(parent, ret_ty_src, rt.return_ty);
457457 },
......@@ -538,7 +538,7 @@ pub const Block = struct {
538538 }
539539
540540 pub fn wantSafety(block: *const Block) bool {
541 return block.want_safety orelse switch (block.sema.mod.optimizeMode()) {
541 return block.want_safety orelse switch (block.sema.pt.zcu.optimizeMode()) {
542542 .Debug => true,
543543 .ReleaseSafe => true,
544544 .ReleaseFast => false,
......@@ -737,11 +737,12 @@ pub const Block = struct {
737737
738738 fn addCmpVector(block: *Block, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref, cmp_op: std.math.CompareOperator) !Air.Inst.Ref {
739739 const sema = block.sema;
740 const mod = sema.mod;
740 const pt = sema.pt;
741 const mod = pt.zcu;
741742 return block.addInst(.{
742743 .tag = if (block.float_mode == .optimized) .cmp_vector_optimized else .cmp_vector,
743744 .data = .{ .ty_pl = .{
744 .ty = Air.internedToRef((try mod.vectorType(.{
745 .ty = Air.internedToRef((try pt.vectorType(.{
745746 .len = sema.typeOf(lhs).vectorLen(mod),
746747 .child = .bool_type,
747748 })).toIntern()),
......@@ -829,14 +830,14 @@ pub const Block = struct {
829830 }
830831
831832 pub fn ownerModule(block: Block) *Package.Module {
832 const zcu = block.sema.mod;
833 const zcu = block.sema.pt.zcu;
833834 return zcu.namespacePtr(block.namespace).fileScope(zcu).mod;
834835 }
835836
836837 fn trackZir(block: *Block, inst: Zir.Inst.Index) Allocator.Error!InternPool.TrackedInst.Index {
837838 const sema = block.sema;
838839 const gpa = sema.gpa;
839 const zcu = sema.mod;
840 const zcu = sema.pt.zcu;
840841 const ip = &zcu.intern_pool;
841842 const file_index = block.getFileScopeIndex(zcu);
842843 return ip.trackZir(gpa, file_index, inst);
......@@ -992,7 +993,8 @@ fn analyzeBodyInner(
992993
993994 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);
994995
995 const zcu = sema.mod;
996 const pt = sema.pt;
997 const zcu = pt.zcu;
996998 const map = &sema.inst_map;
997999 const tags = sema.code.instructions.items(.tag);
9981000 const datas = sema.code.instructions.items(.data);
......@@ -1777,7 +1779,7 @@ fn analyzeBodyInner(
17771779 const err_union_ty = sema.typeOf(err_union);
17781780 if (err_union_ty.zigTypeTag(zcu) != .ErrorUnion) {
17791781 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
1780 err_union_ty.fmt(zcu),
1782 err_union_ty.fmt(pt),
17811783 });
17821784 }
17831785 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
......@@ -1910,10 +1912,11 @@ pub fn toConstString(
19101912 air_inst: Air.Inst.Ref,
19111913 reason: NeededComptimeReason,
19121914) ![]u8 {
1915 const pt = sema.pt;
19131916 const coerced_inst = try sema.coerce(block, Type.slice_const_u8, air_inst, src);
19141917 const slice_val = try sema.resolveConstDefinedValue(block, src, coerced_inst, reason);
19151918 const arr_val = try sema.derefSliceAsArray(block, src, slice_val, reason);
1916 return arr_val.toAllocatedBytes(arr_val.typeOf(sema.mod), sema.arena, sema.mod);
1919 return arr_val.toAllocatedBytes(arr_val.typeOf(pt.zcu), sema.arena, pt);
19171920}
19181921
19191922pub fn resolveConstStringIntern(
......@@ -1945,7 +1948,8 @@ fn resolveDestType(
19451948 strat: enum { remove_eu_opt, remove_eu, remove_opt },
19461949 builtin_name: []const u8,
19471950) !Type {
1948 const mod = sema.mod;
1951 const pt = sema.pt;
1952 const mod = pt.zcu;
19491953 const remove_eu = switch (strat) {
19501954 .remove_eu_opt, .remove_eu => true,
19511955 .remove_opt => false,
......@@ -2062,7 +2066,8 @@ fn analyzeAsType(
20622066}
20632067
20642068pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize) !void {
2065 const mod = sema.mod;
2069 const pt = sema.pt;
2070 const mod = pt.zcu;
20662071 const comp = mod.comp;
20672072 const gpa = sema.gpa;
20682073 const ip = &mod.intern_pool;
......@@ -2076,16 +2081,16 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
20762081
20772082 // var addrs: [err_return_trace_addr_count]usize = undefined;
20782083 const err_return_trace_addr_count = 32;
2079 const addr_arr_ty = try mod.arrayType(.{
2084 const addr_arr_ty = try pt.arrayType(.{
20802085 .len = err_return_trace_addr_count,
20812086 .child = .usize_type,
20822087 });
2083 const addrs_ptr = try err_trace_block.addTy(.alloc, try mod.singleMutPtrType(addr_arr_ty));
2088 const addrs_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(addr_arr_ty));
20842089
20852090 // var st: StackTrace = undefined;
2086 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
2087 try stack_trace_ty.resolveFields(mod);
2088 const st_ptr = try err_trace_block.addTy(.alloc, try mod.singleMutPtrType(stack_trace_ty));
2091 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
2092 try stack_trace_ty.resolveFields(pt);
2093 const st_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(stack_trace_ty));
20892094
20902095 // st.instruction_addresses = &addrs;
20912096 const instruction_addresses_field_name = try ip.getOrPutString(gpa, "instruction_addresses", .no_embedded_nulls);
......@@ -2109,7 +2114,7 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
21092114fn resolveValue(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21102115 const val = (try sema.resolveValueAllowVariables(inst)) orelse return null;
21112116 if (val.isGenericPoison()) return error.GenericPoison;
2112 if (sema.mod.intern_pool.isVariable(val.toIntern())) return null;
2117 if (sema.pt.zcu.intern_pool.isVariable(val.toIntern())) return null;
21132118 return val;
21142119}
21152120
......@@ -2133,7 +2138,8 @@ fn resolveDefinedValue(
21332138 src: LazySrcLoc,
21342139 air_ref: Air.Inst.Ref,
21352140) CompileError!?Value {
2136 const mod = sema.mod;
2141 const pt = sema.pt;
2142 const mod = pt.zcu;
21372143 const val = try sema.resolveValue(air_ref) orelse return null;
21382144 if (val.isUndef(mod)) {
21392145 return sema.failWithUseOfUndef(block, src);
......@@ -2150,7 +2156,7 @@ fn resolveConstDefinedValue(
21502156 reason: NeededComptimeReason,
21512157) CompileError!Value {
21522158 const val = try sema.resolveConstValue(block, src, air_ref, reason);
2153 if (val.isUndef(sema.mod)) return sema.failWithUseOfUndef(block, src);
2159 if (val.isUndef(sema.pt.zcu)) return sema.failWithUseOfUndef(block, src);
21542160 return val;
21552161}
21562162
......@@ -2164,7 +2170,7 @@ fn resolveValueResolveLazy(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value
21642170/// Lazy values are recursively resolved.
21652171fn resolveValueIntable(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21662172 const val = (try sema.resolveValue(inst)) orelse return null;
2167 if (sema.mod.intern_pool.getBackingAddrTag(val.toIntern())) |addr| switch (addr) {
2173 if (sema.pt.zcu.intern_pool.getBackingAddrTag(val.toIntern())) |addr| switch (addr) {
21682174 .decl, .anon_decl, .comptime_alloc, .comptime_field => return null,
21692175 .int => {},
21702176 .eu_payload, .opt_payload, .arr_elem, .field => unreachable,
......@@ -2174,6 +2180,7 @@ fn resolveValueIntable(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21742180
21752181/// Returns all InternPool keys representing values, including `variable`, `undef`, and `generic_poison`.
21762182fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
2183 const pt = sema.pt;
21772184 assert(inst != .none);
21782185 // First section of indexes correspond to a set number of constant values.
21792186 if (@intFromEnum(inst) < InternPool.static_len) {
......@@ -2184,7 +2191,7 @@ fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Val
21842191 if (try sema.typeHasOnePossibleValue(sema.typeOf(inst))) |opv| {
21852192 if (inst.toInterned()) |ip_index| {
21862193 const val = Value.fromInterned(ip_index);
2187 if (val.getVariable(sema.mod) != null) return val;
2194 if (val.getVariable(pt.zcu) != null) return val;
21882195 }
21892196 return opv;
21902197 }
......@@ -2196,7 +2203,7 @@ fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Val
21962203 }
21972204 };
21982205 const val = Value.fromInterned(ip_index);
2199 if (val.isPtrToThreadLocal(sema.mod)) return null;
2206 if (val.isPtrToThreadLocal(pt.zcu)) return null;
22002207 return val;
22012208}
22022209
......@@ -2225,7 +2232,7 @@ pub fn resolveFinalDeclValue(
22252232 });
22262233 };
22272234 if (val.isGenericPoison()) return error.GenericPoison;
2228 if (val.canMutateComptimeVarState(sema.mod)) {
2235 if (val.canMutateComptimeVarState(sema.pt.zcu)) {
22292236 return sema.fail(block, src, "global variable contains reference to comptime var", .{});
22302237 }
22312238 return val;
......@@ -2254,19 +2261,20 @@ fn failWithDivideByZero(sema: *Sema, block: *Block, src: LazySrcLoc) CompileErro
22542261}
22552262
22562263fn failWithModRemNegative(sema: *Sema, block: *Block, src: LazySrcLoc, lhs_ty: Type, rhs_ty: Type) CompileError {
2264 const pt = sema.pt;
22572265 return sema.fail(block, src, "remainder division with '{}' and '{}': signed integers and floats must use @rem or @mod", .{
2258 lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
2266 lhs_ty.fmt(pt), rhs_ty.fmt(pt),
22592267 });
22602268}
22612269
22622270fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, non_optional_ty: Type) CompileError {
2263 const mod = sema.mod;
2271 const pt = sema.pt;
22642272 const msg = msg: {
22652273 const msg = try sema.errMsg(src, "expected optional type, found '{}'", .{
2266 non_optional_ty.fmt(mod),
2274 non_optional_ty.fmt(pt),
22672275 });
22682276 errdefer msg.destroy(sema.gpa);
2269 if (non_optional_ty.zigTypeTag(mod) == .ErrorUnion) {
2277 if (non_optional_ty.zigTypeTag(pt.zcu) == .ErrorUnion) {
22702278 try sema.errNote(src, msg, "consider using 'try', 'catch', or 'if'", .{});
22712279 }
22722280 try addDeclaredHereNote(sema, msg, non_optional_ty);
......@@ -2276,14 +2284,14 @@ fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, non
22762284}
22772285
22782286fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
2279 const mod = sema.mod;
2287 const pt = sema.pt;
22802288 const msg = msg: {
22812289 const msg = try sema.errMsg(src, "type '{}' does not support array initialization syntax", .{
2282 ty.fmt(mod),
2290 ty.fmt(pt),
22832291 });
22842292 errdefer msg.destroy(sema.gpa);
2285 if (ty.isSlice(mod)) {
2286 try sema.errNote(src, msg, "inferred array length is specified with an underscore: '[_]{}'", .{ty.elemType2(mod).fmt(mod)});
2293 if (ty.isSlice(pt.zcu)) {
2294 try sema.errNote(src, msg, "inferred array length is specified with an underscore: '[_]{}'", .{ty.elemType2(pt.zcu).fmt(pt)});
22872295 }
22882296 break :msg msg;
22892297 };
......@@ -2291,8 +2299,9 @@ fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty
22912299}
22922300
22932301fn failWithStructInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
2302 const pt = sema.pt;
22942303 return sema.fail(block, src, "type '{}' does not support struct initialization syntax", .{
2295 ty.fmt(sema.mod),
2304 ty.fmt(pt),
22962305 });
22972306}
22982307
......@@ -2303,17 +2312,19 @@ fn failWithErrorSetCodeMissing(
23032312 dest_err_set_ty: Type,
23042313 src_err_set_ty: Type,
23052314) CompileError {
2315 const pt = sema.pt;
23062316 return sema.fail(block, src, "expected type '{}', found type '{}'", .{
2307 dest_err_set_ty.fmt(sema.mod), src_err_set_ty.fmt(sema.mod),
2317 dest_err_set_ty.fmt(pt), src_err_set_ty.fmt(pt),
23082318 });
23092319}
23102320
23112321fn failWithIntegerOverflow(sema: *Sema, block: *Block, src: LazySrcLoc, int_ty: Type, val: Value, vector_index: usize) CompileError {
2312 const zcu = sema.mod;
2322 const pt = sema.pt;
2323 const zcu = pt.zcu;
23132324 if (int_ty.zigTypeTag(zcu) == .Vector) {
23142325 const msg = msg: {
23152326 const msg = try sema.errMsg(src, "overflow of vector type '{}' with value '{}'", .{
2316 int_ty.fmt(zcu), val.fmtValue(zcu, sema),
2327 int_ty.fmt(pt), val.fmtValue(pt, sema),
23172328 });
23182329 errdefer msg.destroy(sema.gpa);
23192330 try sema.errNote(src, msg, "when computing vector element at index '{d}'", .{vector_index});
......@@ -2322,12 +2333,13 @@ fn failWithIntegerOverflow(sema: *Sema, block: *Block, src: LazySrcLoc, int_ty:
23222333 return sema.failWithOwnedErrorMsg(block, msg);
23232334 }
23242335 return sema.fail(block, src, "overflow of integer type '{}' with value '{}'", .{
2325 int_ty.fmt(zcu), val.fmtValue(zcu, sema),
2336 int_ty.fmt(pt), val.fmtValue(pt, sema),
23262337 });
23272338}
23282339
23292340fn failWithInvalidComptimeFieldStore(sema: *Sema, block: *Block, init_src: LazySrcLoc, container_ty: Type, field_index: usize) CompileError {
2330 const mod = sema.mod;
2341 const pt = sema.pt;
2342 const mod = pt.zcu;
23312343 const msg = msg: {
23322344 const msg = try sema.errMsg(init_src, "value stored in comptime field does not match the default value of the field", .{});
23332345 errdefer msg.destroy(sema.gpa);
......@@ -2358,14 +2370,15 @@ fn failWithInvalidFieldAccess(
23582370 object_ty: Type,
23592371 field_name: InternPool.NullTerminatedString,
23602372) CompileError {
2361 const mod = sema.mod;
2373 const pt = sema.pt;
2374 const mod = pt.zcu;
23622375 const inner_ty = if (object_ty.isSinglePointer(mod)) object_ty.childType(mod) else object_ty;
23632376
23642377 if (inner_ty.zigTypeTag(mod) == .Optional) opt: {
23652378 const child_ty = inner_ty.optionalChild(mod);
23662379 if (!typeSupportsFieldAccess(mod, child_ty, field_name)) break :opt;
23672380 const msg = msg: {
2368 const msg = try sema.errMsg(src, "optional type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2381 const msg = try sema.errMsg(src, "optional type '{}' does not support field access", .{object_ty.fmt(pt)});
23692382 errdefer msg.destroy(sema.gpa);
23702383 try sema.errNote(src, msg, "consider using '.?', 'orelse', or 'if'", .{});
23712384 break :msg msg;
......@@ -2375,14 +2388,14 @@ fn failWithInvalidFieldAccess(
23752388 const child_ty = inner_ty.errorUnionPayload(mod);
23762389 if (!typeSupportsFieldAccess(mod, child_ty, field_name)) break :err;
23772390 const msg = msg: {
2378 const msg = try sema.errMsg(src, "error union type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2391 const msg = try sema.errMsg(src, "error union type '{}' does not support field access", .{object_ty.fmt(pt)});
23792392 errdefer msg.destroy(sema.gpa);
23802393 try sema.errNote(src, msg, "consider using 'try', 'catch', or 'if'", .{});
23812394 break :msg msg;
23822395 };
23832396 return sema.failWithOwnedErrorMsg(block, msg);
23842397 }
2385 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2398 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(pt)});
23862399}
23872400
23882401fn typeSupportsFieldAccess(mod: *const Module, ty: Type, field_name: InternPool.NullTerminatedString) bool {
......@@ -2408,7 +2421,8 @@ fn failWithComptimeErrorRetTrace(
24082421 src: LazySrcLoc,
24092422 name: InternPool.NullTerminatedString,
24102423) CompileError {
2411 const mod = sema.mod;
2424 const pt = sema.pt;
2425 const mod = pt.zcu;
24122426 const msg = msg: {
24132427 const msg = try sema.errMsg(src, "caught unexpected error '{}'", .{name.fmt(&mod.intern_pool)});
24142428 errdefer msg.destroy(sema.gpa);
......@@ -2430,7 +2444,7 @@ pub fn errNote(
24302444 comptime format: []const u8,
24312445 args: anytype,
24322446) error{OutOfMemory}!void {
2433 return sema.mod.errNote(src, parent, format, args);
2447 return sema.pt.zcu.errNote(src, parent, format, args);
24342448}
24352449
24362450fn addFieldErrNote(
......@@ -2442,8 +2456,7 @@ fn addFieldErrNote(
24422456 args: anytype,
24432457) !void {
24442458 @setCold(true);
2445 const zcu = sema.mod;
2446 const type_src = container_ty.srcLocOrNull(zcu) orelse return;
2459 const type_src = container_ty.srcLocOrNull(sema.pt.zcu) orelse return;
24472460 const field_src: LazySrcLoc = .{
24482461 .base_node_inst = type_src.base_node_inst,
24492462 .offset = .{ .container_field_name = @intCast(field_index) },
......@@ -2480,7 +2493,7 @@ pub fn fail(
24802493pub fn failWithOwnedErrorMsg(sema: *Sema, block: ?*Block, err_msg: *Module.ErrorMsg) error{ AnalysisFail, OutOfMemory } {
24812494 @setCold(true);
24822495 const gpa = sema.gpa;
2483 const mod = sema.mod;
2496 const mod = sema.pt.zcu;
24842497 const ip = &mod.intern_pool;
24852498
24862499 if (build_options.enable_debug_extensions and mod.comp.debug_compile_errors) {
......@@ -2545,8 +2558,7 @@ fn reparentOwnedErrorMsg(
25452558 comptime format: []const u8,
25462559 args: anytype,
25472560) !void {
2548 const mod = sema.mod;
2549 const msg_str = try std.fmt.allocPrint(mod.gpa, format, args);
2561 const msg_str = try std.fmt.allocPrint(sema.gpa, format, args);
25502562
25512563 const orig_notes = msg.notes.len;
25522564 msg.notes = try sema.gpa.realloc(msg.notes, orig_notes + 1);
......@@ -2630,16 +2642,16 @@ fn analyzeAsInt(
26302642 dest_ty: Type,
26312643 reason: NeededComptimeReason,
26322644) !u64 {
2633 const mod = sema.mod;
26342645 const coerced = try sema.coerce(block, dest_ty, air_ref, src);
26352646 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
2636 return (try val.getUnsignedIntAdvanced(mod, .sema)).?;
2647 return (try val.getUnsignedIntAdvanced(sema.pt, .sema)).?;
26372648}
26382649
26392650/// Given a ZIR extra index which points to a list of `Zir.Inst.Capture`,
26402651/// resolves this into a list of `InternPool.CaptureValue` allocated by `arena`.
26412652fn getCaptures(sema: *Sema, block: *Block, type_src: LazySrcLoc, extra_index: usize, captures_len: u32) ![]InternPool.CaptureValue {
2642 const zcu = sema.mod;
2653 const pt = sema.pt;
2654 const zcu = pt.zcu;
26432655 const ip = &zcu.intern_pool;
26442656 const parent_captures: InternPool.CaptureValue.Slice = zcu.namespacePtr(block.namespace).getType(zcu).getCaptures(zcu);
26452657
......@@ -2706,7 +2718,7 @@ fn wrapWipTy(sema: *Sema, wip_ty: anytype) @TypeOf(wip_ty) {
27062718 if (sema.builtin_type_target_index == .none) return wip_ty;
27072719 var new = wip_ty;
27082720 new.index = sema.builtin_type_target_index;
2709 sema.mod.intern_pool.resolveBuiltinType(new.index, wip_ty.index);
2721 sema.pt.zcu.intern_pool.resolveBuiltinType(new.index, wip_ty.index);
27102722 return new;
27112723}
27122724
......@@ -2714,7 +2726,8 @@ fn wrapWipTy(sema: *Sema, wip_ty: anytype) @TypeOf(wip_ty) {
27142726/// considered outdated on this update. If so, remove it from the pool
27152727/// and return `true`.
27162728fn maybeRemoveOutdatedType(sema: *Sema, ty: InternPool.Index) !bool {
2717 const zcu = sema.mod;
2729 const pt = sema.pt;
2730 const zcu = pt.zcu;
27182731
27192732 if (!zcu.comp.debug_incremental) return false;
27202733
......@@ -2737,7 +2750,8 @@ fn zirStructDecl(
27372750 extended: Zir.Inst.Extended.InstData,
27382751 inst: Zir.Inst.Index,
27392752) CompileError!Air.Inst.Ref {
2740 const mod = sema.mod;
2753 const pt = sema.pt;
2754 const mod = pt.zcu;
27412755 const gpa = sema.gpa;
27422756 const ip = &mod.intern_pool;
27432757 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
......@@ -2796,10 +2810,10 @@ fn zirStructDecl(
27962810 .captures = captures,
27972811 } },
27982812 };
2799 const wip_ty = sema.wrapWipTy(switch (try ip.getStructType(gpa, struct_init)) {
2813 const wip_ty = sema.wrapWipTy(switch (try ip.getStructType(gpa, pt.tid, struct_init)) {
28002814 .existing => |ty| wip: {
28012815 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
2802 break :wip (try ip.getStructType(gpa, struct_init)).wip;
2816 break :wip (try ip.getStructType(gpa, pt.tid, struct_init)).wip;
28032817 },
28042818 .wip => |wip| wip,
28052819 });
......@@ -2815,7 +2829,7 @@ fn zirStructDecl(
28152829 mod.declPtr(new_decl_index).owns_tv = true;
28162830 errdefer mod.abortAnonDecl(new_decl_index);
28172831
2818 if (sema.mod.comp.debug_incremental) {
2832 if (pt.zcu.comp.debug_incremental) {
28192833 try ip.addDependency(
28202834 sema.gpa,
28212835 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -2836,7 +2850,7 @@ fn zirStructDecl(
28362850 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
28372851 }
28382852
2839 try mod.finalizeAnonDecl(new_decl_index);
2853 try pt.finalizeAnonDecl(new_decl_index);
28402854 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
28412855 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
28422856 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
......@@ -2850,7 +2864,8 @@ fn createAnonymousDeclTypeNamed(
28502864 anon_prefix: []const u8,
28512865 inst: ?Zir.Inst.Index,
28522866) !InternPool.DeclIndex {
2853 const zcu = sema.mod;
2867 const pt = sema.pt;
2868 const zcu = pt.zcu;
28542869 const ip = &zcu.intern_pool;
28552870 const gpa = sema.gpa;
28562871 const namespace = block.namespace;
......@@ -2892,7 +2907,7 @@ fn createAnonymousDeclTypeNamed(
28922907 // some tooling may not support very long symbol names.
28932908 try writer.print("{}", .{Value.fmtValueFull(.{
28942909 .val = arg_val,
2895 .mod = zcu,
2910 .pt = pt,
28962911 .opt_sema = sema,
28972912 .depth = 1,
28982913 })});
......@@ -2953,7 +2968,8 @@ fn zirEnumDecl(
29532968 const tracy = trace(@src());
29542969 defer tracy.end();
29552970
2956 const mod = sema.mod;
2971 const pt = sema.pt;
2972 const mod = pt.zcu;
29572973 const gpa = sema.gpa;
29582974 const ip = &mod.intern_pool;
29592975 const small: Zir.Inst.EnumDecl.Small = @bitCast(extended.small);
......@@ -3026,10 +3042,10 @@ fn zirEnumDecl(
30263042 .captures = captures,
30273043 } },
30283044 };
3029 const wip_ty = sema.wrapWipTy(switch (try ip.getEnumType(gpa, enum_init)) {
3045 const wip_ty = sema.wrapWipTy(switch (try ip.getEnumType(gpa, pt.tid, enum_init)) {
30303046 .existing => |ty| wip: {
30313047 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3032 break :wip (try ip.getEnumType(gpa, enum_init)).wip;
3048 break :wip (try ip.getEnumType(gpa, pt.tid, enum_init)).wip;
30333049 },
30343050 .wip => |wip| wip,
30353051 });
......@@ -3051,7 +3067,7 @@ fn zirEnumDecl(
30513067 new_decl.owns_tv = true;
30523068 errdefer if (!done) mod.abortAnonDecl(new_decl_index);
30533069
3054 if (sema.mod.comp.debug_incremental) {
3070 if (pt.zcu.comp.debug_incremental) {
30553071 try mod.intern_pool.addDependency(
30563072 gpa,
30573073 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3118,21 +3134,21 @@ fn zirEnumDecl(
31183134 if (tag_type_ref != .none) {
31193135 const ty = try sema.resolveType(&enum_block, tag_ty_src, tag_type_ref);
31203136 if (ty.zigTypeTag(mod) != .Int and ty.zigTypeTag(mod) != .ComptimeInt) {
3121 return sema.fail(&enum_block, tag_ty_src, "expected integer tag type, found '{}'", .{ty.fmt(sema.mod)});
3137 return sema.fail(&enum_block, tag_ty_src, "expected integer tag type, found '{}'", .{ty.fmt(pt)});
31223138 }
31233139 break :ty ty;
31243140 } else if (fields_len == 0) {
3125 break :ty try mod.intType(.unsigned, 0);
3141 break :ty try pt.intType(.unsigned, 0);
31263142 } else {
31273143 const bits = std.math.log2_int_ceil(usize, fields_len);
3128 break :ty try mod.intType(.unsigned, bits);
3144 break :ty try pt.intType(.unsigned, bits);
31293145 }
31303146 };
31313147
31323148 wip_ty.setTagTy(ip, int_tag_ty.toIntern());
31333149
31343150 if (small.nonexhaustive and int_tag_ty.toIntern() != .comptime_int_type) {
3135 if (fields_len > 1 and std.math.log2_int(u64, fields_len) == int_tag_ty.bitSize(mod)) {
3151 if (fields_len > 1 and std.math.log2_int(u64, fields_len) == int_tag_ty.bitSize(pt)) {
31363152 return sema.fail(block, src, "non-exhaustive enum specifies every value", .{});
31373153 }
31383154 }
......@@ -3171,7 +3187,7 @@ fn zirEnumDecl(
31713187 .needed_comptime_reason = "enum tag value must be comptime-known",
31723188 });
31733189 if (!(try sema.intFitsInType(last_tag_val.?, int_tag_ty, null))) break :overflow true;
3174 last_tag_val = try mod.getCoerced(last_tag_val.?, int_tag_ty);
3190 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);
31753191 if (wip_ty.nextField(&mod.intern_pool, field_name, last_tag_val.?.toIntern())) |conflict| {
31763192 assert(conflict.kind == .value); // AstGen validated names are unique
31773193 const other_field_src: LazySrcLoc = .{
......@@ -3179,7 +3195,7 @@ fn zirEnumDecl(
31793195 .offset = .{ .container_field_value = conflict.prev_field_idx },
31803196 };
31813197 const msg = msg: {
3182 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(sema.mod, sema)});
3198 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(pt, sema)});
31833199 errdefer msg.destroy(gpa);
31843200 try sema.errNote(other_field_src, msg, "other occurrence here", .{});
31853201 break :msg msg;
......@@ -3190,9 +3206,9 @@ fn zirEnumDecl(
31903206 } else if (any_values) overflow: {
31913207 var overflow: ?usize = null;
31923208 last_tag_val = if (last_tag_val) |val|
3193 try sema.intAdd(val, try mod.intValue(int_tag_ty, 1), int_tag_ty, &overflow)
3209 try sema.intAdd(val, try pt.intValue(int_tag_ty, 1), int_tag_ty, &overflow)
31943210 else
3195 try mod.intValue(int_tag_ty, 0);
3211 try pt.intValue(int_tag_ty, 0);
31963212 if (overflow != null) break :overflow true;
31973213 if (wip_ty.nextField(&mod.intern_pool, field_name, last_tag_val.?.toIntern())) |conflict| {
31983214 assert(conflict.kind == .value); // AstGen validated names are unique
......@@ -3201,7 +3217,7 @@ fn zirEnumDecl(
32013217 .offset = .{ .container_field_value = conflict.prev_field_idx },
32023218 };
32033219 const msg = msg: {
3204 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(sema.mod, sema)});
3220 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(pt, sema)});
32053221 errdefer msg.destroy(gpa);
32063222 try sema.errNote(other_field_src, msg, "other occurrence here", .{});
32073223 break :msg msg;
......@@ -3211,21 +3227,21 @@ fn zirEnumDecl(
32113227 break :overflow false;
32123228 } else overflow: {
32133229 assert(wip_ty.nextField(&mod.intern_pool, field_name, .none) == null);
3214 last_tag_val = try mod.intValue(Type.comptime_int, field_i);
3230 last_tag_val = try pt.intValue(Type.comptime_int, field_i);
32153231 if (!try sema.intFitsInType(last_tag_val.?, int_tag_ty, null)) break :overflow true;
3216 last_tag_val = try mod.getCoerced(last_tag_val.?, int_tag_ty);
3232 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);
32173233 break :overflow false;
32183234 };
32193235
32203236 if (tag_overflow) {
32213237 const msg = try sema.errMsg(value_src, "enumeration value '{}' too large for type '{}'", .{
3222 last_tag_val.?.fmtValue(mod, sema), int_tag_ty.fmt(mod),
3238 last_tag_val.?.fmtValue(pt, sema), int_tag_ty.fmt(pt),
32233239 });
32243240 return sema.failWithOwnedErrorMsg(block, msg);
32253241 }
32263242 }
32273243
3228 try mod.finalizeAnonDecl(new_decl_index);
3244 try pt.finalizeAnonDecl(new_decl_index);
32293245 return Air.internedToRef(wip_ty.index);
32303246}
32313247
......@@ -3238,7 +3254,8 @@ fn zirUnionDecl(
32383254 const tracy = trace(@src());
32393255 defer tracy.end();
32403256
3241 const mod = sema.mod;
3257 const pt = sema.pt;
3258 const mod = pt.zcu;
32423259 const gpa = sema.gpa;
32433260 const ip = &mod.intern_pool;
32443261 const small: Zir.Inst.UnionDecl.Small = @bitCast(extended.small);
......@@ -3298,10 +3315,10 @@ fn zirUnionDecl(
32983315 .captures = captures,
32993316 } },
33003317 };
3301 const wip_ty = sema.wrapWipTy(switch (try ip.getUnionType(gpa, union_init)) {
3318 const wip_ty = sema.wrapWipTy(switch (try ip.getUnionType(gpa, pt.tid, union_init)) {
33023319 .existing => |ty| wip: {
33033320 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3304 break :wip (try ip.getUnionType(gpa, union_init)).wip;
3321 break :wip (try ip.getUnionType(gpa, pt.tid, union_init)).wip;
33053322 },
33063323 .wip => |wip| wip,
33073324 });
......@@ -3317,7 +3334,7 @@ fn zirUnionDecl(
33173334 mod.declPtr(new_decl_index).owns_tv = true;
33183335 errdefer mod.abortAnonDecl(new_decl_index);
33193336
3320 if (sema.mod.comp.debug_incremental) {
3337 if (pt.zcu.comp.debug_incremental) {
33213338 try mod.intern_pool.addDependency(
33223339 gpa,
33233340 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3338,7 +3355,7 @@ fn zirUnionDecl(
33383355 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
33393356 }
33403357
3341 try mod.finalizeAnonDecl(new_decl_index);
3358 try pt.finalizeAnonDecl(new_decl_index);
33423359 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
33433360 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
33443361 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
......@@ -3353,7 +3370,8 @@ fn zirOpaqueDecl(
33533370 const tracy = trace(@src());
33543371 defer tracy.end();
33553372
3356 const mod = sema.mod;
3373 const pt = sema.pt;
3374 const mod = pt.zcu;
33573375 const gpa = sema.gpa;
33583376 const ip = &mod.intern_pool;
33593377
......@@ -3387,10 +3405,10 @@ fn zirOpaqueDecl(
33873405 } },
33883406 };
33893407 // No `wrapWipTy` needed as no std.builtin types are opaque.
3390 const wip_ty = switch (try ip.getOpaqueType(gpa, opaque_init)) {
3408 const wip_ty = switch (try ip.getOpaqueType(gpa, pt.tid, opaque_init)) {
33913409 .existing => |ty| wip: {
33923410 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3393 break :wip (try ip.getOpaqueType(gpa, opaque_init)).wip;
3411 break :wip (try ip.getOpaqueType(gpa, pt.tid, opaque_init)).wip;
33943412 },
33953413 .wip => |wip| wip,
33963414 };
......@@ -3406,7 +3424,7 @@ fn zirOpaqueDecl(
34063424 mod.declPtr(new_decl_index).owns_tv = true;
34073425 errdefer mod.abortAnonDecl(new_decl_index);
34083426
3409 if (sema.mod.comp.debug_incremental) {
3427 if (pt.zcu.comp.debug_incremental) {
34103428 try ip.addDependency(
34113429 gpa,
34123430 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3426,7 +3444,7 @@ fn zirOpaqueDecl(
34263444 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
34273445 }
34283446
3429 try mod.finalizeAnonDecl(new_decl_index);
3447 try pt.finalizeAnonDecl(new_decl_index);
34303448
34313449 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
34323450}
......@@ -3438,7 +3456,8 @@ fn zirErrorSetDecl(
34383456 const tracy = trace(@src());
34393457 defer tracy.end();
34403458
3441 const mod = sema.mod;
3459 const pt = sema.pt;
3460 const mod = pt.zcu;
34423461 const gpa = sema.gpa;
34433462 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
34443463 const extra = sema.code.extraData(Zir.Inst.ErrorSetDecl, inst_data.payload_index);
......@@ -3457,20 +3476,22 @@ fn zirErrorSetDecl(
34573476 assert(!result.found_existing); // verified in AstGen
34583477 }
34593478
3460 return Air.internedToRef((try mod.errorSetFromUnsortedNames(names.keys())).toIntern());
3479 return Air.internedToRef((try pt.errorSetFromUnsortedNames(names.keys())).toIntern());
34613480}
34623481
34633482fn zirRetPtr(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
34643483 const tracy = trace(@src());
34653484 defer tracy.end();
34663485
3486 const pt = sema.pt;
3487
34673488 if (block.is_comptime or try sema.typeRequiresComptime(sema.fn_ret_ty)) {
3468 try sema.fn_ret_ty.resolveFields(sema.mod);
3489 try sema.fn_ret_ty.resolveFields(pt);
34693490 return sema.analyzeComptimeAlloc(block, sema.fn_ret_ty, .none);
34703491 }
34713492
3472 const target = sema.mod.getTarget();
3473 const ptr_type = try sema.mod.ptrTypeSema(.{
3493 const target = pt.zcu.getTarget();
3494 const ptr_type = try pt.ptrTypeSema(.{
34743495 .child = sema.fn_ret_ty.toIntern(),
34753496 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
34763497 });
......@@ -3511,7 +3532,8 @@ fn ensureResultUsed(
35113532 ty: Type,
35123533 src: LazySrcLoc,
35133534) CompileError!void {
3514 const mod = sema.mod;
3535 const pt = sema.pt;
3536 const mod = pt.zcu;
35153537 switch (ty.zigTypeTag(mod)) {
35163538 .Void, .NoReturn => return,
35173539 .ErrorSet => return sema.fail(block, src, "error set is ignored", .{}),
......@@ -3526,7 +3548,7 @@ fn ensureResultUsed(
35263548 },
35273549 else => {
35283550 const msg = msg: {
3529 const msg = try sema.errMsg(src, "value of type '{}' ignored", .{ty.fmt(sema.mod)});
3551 const msg = try sema.errMsg(src, "value of type '{}' ignored", .{ty.fmt(pt)});
35303552 errdefer msg.destroy(sema.gpa);
35313553 try sema.errNote(src, msg, "all non-void values must be used", .{});
35323554 try sema.errNote(src, msg, "to discard the value, assign it to '_'", .{});
......@@ -3541,7 +3563,8 @@ fn zirEnsureResultNonError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
35413563 const tracy = trace(@src());
35423564 defer tracy.end();
35433565
3544 const mod = sema.mod;
3566 const pt = sema.pt;
3567 const mod = pt.zcu;
35453568 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
35463569 const operand = try sema.resolveInst(inst_data.operand);
35473570 const src = block.nodeOffset(inst_data.src_node);
......@@ -3565,7 +3588,8 @@ fn zirEnsureErrUnionPayloadVoid(sema: *Sema, block: *Block, inst: Zir.Inst.Index
35653588 const tracy = trace(@src());
35663589 defer tracy.end();
35673590
3568 const mod = sema.mod;
3591 const pt = sema.pt;
3592 const mod = pt.zcu;
35693593 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
35703594 const src = block.nodeOffset(inst_data.src_node);
35713595 const operand = try sema.resolveInst(inst_data.operand);
......@@ -3604,7 +3628,8 @@ fn indexablePtrLen(
36043628 src: LazySrcLoc,
36053629 object: Air.Inst.Ref,
36063630) CompileError!Air.Inst.Ref {
3607 const mod = sema.mod;
3631 const pt = sema.pt;
3632 const mod = pt.zcu;
36083633 const object_ty = sema.typeOf(object);
36093634 const is_pointer_to = object_ty.isSinglePointer(mod);
36103635 const indexable_ty = if (is_pointer_to) object_ty.childType(mod) else object_ty;
......@@ -3619,7 +3644,8 @@ fn indexablePtrLenOrNone(
36193644 src: LazySrcLoc,
36203645 operand: Air.Inst.Ref,
36213646) CompileError!Air.Inst.Ref {
3622 const mod = sema.mod;
3647 const pt = sema.pt;
3648 const mod = pt.zcu;
36233649 const operand_ty = sema.typeOf(operand);
36243650 try checkMemOperand(sema, block, src, operand_ty);
36253651 if (operand_ty.ptrSize(mod) == .Many) return .none;
......@@ -3632,6 +3658,7 @@ fn zirAllocExtended(
36323658 block: *Block,
36333659 extended: Zir.Inst.Extended.InstData,
36343660) CompileError!Air.Inst.Ref {
3661 const pt = sema.pt;
36353662 const gpa = sema.gpa;
36363663 const extra = sema.code.extraData(Zir.Inst.AllocExtended, extended.operand);
36373664 const ty_src = block.src(.{ .node_offset_var_decl_ty = extra.data.src_node });
......@@ -3673,9 +3700,9 @@ fn zirAllocExtended(
36733700 if (!small.is_const) {
36743701 try sema.validateVarType(block, ty_src, var_ty, false);
36753702 }
3676 const target = sema.mod.getTarget();
3677 try var_ty.resolveLayout(sema.mod);
3678 const ptr_type = try sema.mod.ptrTypeSema(.{
3703 const target = pt.zcu.getTarget();
3704 try var_ty.resolveLayout(pt);
3705 const ptr_type = try sema.pt.ptrTypeSema(.{
36793706 .child = var_ty.toIntern(),
36803707 .flags = .{
36813708 .alignment = alignment,
......@@ -3717,7 +3744,8 @@ fn zirAllocComptime(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
37173744}
37183745
37193746fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
3720 const mod = sema.mod;
3747 const pt = sema.pt;
3748 const mod = pt.zcu;
37213749 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
37223750 const alloc = try sema.resolveInst(inst_data.operand);
37233751 const alloc_ty = sema.typeOf(alloc);
......@@ -3749,7 +3777,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37493777 assert(ptr.byte_offset == 0);
37503778 const alloc_index = ptr.base_addr.comptime_alloc;
37513779 const ct_alloc = sema.getComptimeAlloc(alloc_index);
3752 const interned = try ct_alloc.val.intern(mod, sema.arena);
3780 const interned = try ct_alloc.val.intern(pt, sema.arena);
37533781 if (interned.canMutateComptimeVarState(mod)) {
37543782 // Preserve the comptime alloc, just make the pointer const.
37553783 ct_alloc.val = .{ .interned = interned.toIntern() };
......@@ -3757,7 +3785,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37573785 return sema.makePtrConst(block, alloc);
37583786 } else {
37593787 // Promote the constant to an anon decl.
3760 const new_mut_ptr = Air.internedToRef(try mod.intern(.{ .ptr = .{
3788 const new_mut_ptr = Air.internedToRef(try pt.intern(.{ .ptr = .{
37613789 .ty = alloc_ty.toIntern(),
37623790 .base_addr = .{ .anon_decl = .{
37633791 .val = interned.toIntern(),
......@@ -3778,7 +3806,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37783806 // The value was initialized through RLS, so we didn't detect the runtime condition earlier.
37793807 // TODO: source location of runtime control flow
37803808 const init_src = block.src(.{ .node_offset_bin_rhs = inst_data.src_node });
3781 return sema.fail(block, init_src, "value with comptime-only type '{}' depends on runtime control flow", .{elem_ty.fmt(mod)});
3809 return sema.fail(block, init_src, "value with comptime-only type '{}' depends on runtime control flow", .{elem_ty.fmt(pt)});
37823810 }
37833811
37843812 // This is a runtime value.
......@@ -3788,7 +3816,8 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37883816/// If `alloc` is an inferred allocation, `resolved_inferred_ty` is taken to be its resolved
37893817/// type. Otherwise, it may be `null`, and the type will be inferred from `alloc`.
37903818fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref, resolved_alloc_ty: ?Type) CompileError!?InternPool.Index {
3791 const zcu = sema.mod;
3819 const pt = sema.pt;
3820 const zcu = pt.zcu;
37923821
37933822 const alloc_ty = resolved_alloc_ty orelse sema.typeOf(alloc);
37943823 const ptr_info = alloc_ty.ptrInfo(zcu);
......@@ -3831,7 +3860,7 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
38313860
38323861 const ct_alloc = try sema.newComptimeAlloc(block, elem_ty, ptr_info.flags.alignment);
38333862
3834 const alloc_ptr = try zcu.intern(.{ .ptr = .{
3863 const alloc_ptr = try pt.intern(.{ .ptr = .{
38353864 .ty = alloc_ty.toIntern(),
38363865 .base_addr = .{ .comptime_alloc = ct_alloc },
38373866 .byte_offset = 0,
......@@ -3909,7 +3938,7 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39093938 const idx_val = (try sema.resolveValue(data.rhs)).?;
39103939 break :blk .{
39113940 data.lhs,
3912 .{ .elem = try idx_val.toUnsignedIntSema(zcu) },
3941 .{ .elem = try idx_val.toUnsignedIntSema(pt) },
39133942 };
39143943 },
39153944 .bitcast => .{
......@@ -3935,32 +3964,32 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39353964 };
39363965 const new_ptr_ty = tmp_air.typeOfIndex(air_ptr, &zcu.intern_pool).toIntern();
39373966 const new_ptr = switch (method) {
3938 .same_addr => try zcu.intern_pool.getCoerced(sema.gpa, decl_parent_ptr, new_ptr_ty),
3967 .same_addr => try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, decl_parent_ptr, new_ptr_ty),
39393968 .opt_payload => ptr: {
39403969 // Set the optional to non-null at comptime.
39413970 // If the payload is OPV, we must use that value instead of undef.
39423971 const opt_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
39433972 const payload_ty = opt_ty.optionalChild(zcu);
3944 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3945 const opt_val = try zcu.intern(.{ .opt = .{
3973 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
3974 const opt_val = try pt.intern(.{ .opt = .{
39463975 .ty = opt_ty.toIntern(),
39473976 .val = payload_val.toIntern(),
39483977 } });
39493978 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), Value.fromInterned(opt_val), opt_ty);
3950 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrOptPayload(zcu)).toIntern();
3979 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrOptPayload(pt)).toIntern();
39513980 },
39523981 .eu_payload => ptr: {
39533982 // Set the error union to non-error at comptime.
39543983 // If the payload is OPV, we must use that value instead of undef.
39553984 const eu_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
39563985 const payload_ty = eu_ty.errorUnionPayload(zcu);
3957 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3958 const eu_val = try zcu.intern(.{ .error_union = .{
3986 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
3987 const eu_val = try pt.intern(.{ .error_union = .{
39593988 .ty = eu_ty.toIntern(),
39603989 .val = .{ .payload = payload_val.toIntern() },
39613990 } });
39623991 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), Value.fromInterned(eu_val), eu_ty);
3963 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrEuPayload(zcu)).toIntern();
3992 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrEuPayload(pt)).toIntern();
39643993 },
39653994 .field => |idx| ptr: {
39663995 const maybe_union_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
......@@ -3969,14 +3998,14 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39693998 // If the payload is OPV, there will not be a payload store, so we store that value.
39703999 // Otherwise, there will be a payload store to process later, so undef will suffice.
39714000 const payload_ty = Type.fromInterned(union_obj.field_types.get(&zcu.intern_pool)[idx]);
3972 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3973 const tag_val = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), idx);
3974 const store_val = try zcu.unionValue(maybe_union_ty, tag_val, payload_val);
4001 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
4002 const tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), idx);
4003 const store_val = try pt.unionValue(maybe_union_ty, tag_val, payload_val);
39754004 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), store_val, maybe_union_ty);
39764005 }
3977 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrField(idx, zcu)).toIntern();
4006 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrField(idx, pt)).toIntern();
39784007 },
3979 .elem => |idx| (try Value.fromInterned(decl_parent_ptr).ptrElem(idx, zcu)).toIntern(),
4008 .elem => |idx| (try Value.fromInterned(decl_parent_ptr).ptrElem(idx, pt)).toIntern(),
39804009 };
39814010 try ptr_mapping.put(air_ptr, new_ptr);
39824011 }
......@@ -4020,7 +4049,8 @@ fn finishResolveComptimeKnownAllocPtr(
40204049 alloc_inst: Air.Inst.Index,
40214050 comptime_info: MaybeComptimeAlloc,
40224051) CompileError!?InternPool.Index {
4023 const zcu = sema.mod;
4052 const pt = sema.pt;
4053 const zcu = pt.zcu;
40244054
40254055 // We're almost done - we have the resolved comptime value. We just need to
40264056 // eliminate the now-dead runtime instructions.
......@@ -4041,19 +4071,19 @@ fn finishResolveComptimeKnownAllocPtr(
40414071
40424072 if (Value.fromInterned(result_val).canMutateComptimeVarState(zcu)) {
40434073 const alloc_index = existing_comptime_alloc orelse a: {
4044 const idx = try sema.newComptimeAlloc(block, alloc_ty.childType(zcu), alloc_ty.ptrAlignment(zcu));
4074 const idx = try sema.newComptimeAlloc(block, alloc_ty.childType(zcu), alloc_ty.ptrAlignment(pt));
40454075 const alloc = sema.getComptimeAlloc(idx);
40464076 alloc.val = .{ .interned = result_val };
40474077 break :a idx;
40484078 };
40494079 sema.getComptimeAlloc(alloc_index).is_const = true;
4050 return try zcu.intern(.{ .ptr = .{
4080 return try pt.intern(.{ .ptr = .{
40514081 .ty = alloc_ty.toIntern(),
40524082 .base_addr = .{ .comptime_alloc = alloc_index },
40534083 .byte_offset = 0,
40544084 } });
40554085 } else {
4056 return try zcu.intern(.{ .ptr = .{
4086 return try pt.intern(.{ .ptr = .{
40574087 .ty = alloc_ty.toIntern(),
40584088 .base_addr = .{ .anon_decl = .{
40594089 .orig_ty = alloc_ty.toIntern(),
......@@ -4065,9 +4095,9 @@ fn finishResolveComptimeKnownAllocPtr(
40654095}
40664096
40674097fn makePtrTyConst(sema: *Sema, ptr_ty: Type) CompileError!Type {
4068 var ptr_info = ptr_ty.ptrInfo(sema.mod);
4098 var ptr_info = ptr_ty.ptrInfo(sema.pt.zcu);
40694099 ptr_info.flags.is_const = true;
4070 return sema.mod.ptrTypeSema(ptr_info);
4100 return sema.pt.ptrTypeSema(ptr_info);
40714101}
40724102
40734103fn makePtrConst(sema: *Sema, block: *Block, alloc: Air.Inst.Ref) CompileError!Air.Inst.Ref {
......@@ -4076,7 +4106,7 @@ fn makePtrConst(sema: *Sema, block: *Block, alloc: Air.Inst.Ref) CompileError!Ai
40764106
40774107 // Detect if a comptime value simply needs to have its type changed.
40784108 if (try sema.resolveValue(alloc)) |val| {
4079 return Air.internedToRef((try sema.mod.getCoerced(val, const_ptr_ty)).toIntern());
4109 return Air.internedToRef((try sema.pt.getCoerced(val, const_ptr_ty)).toIntern());
40804110 }
40814111
40824112 return block.addBitCast(const_ptr_ty, alloc);
......@@ -4103,14 +4133,16 @@ fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
41034133 const tracy = trace(@src());
41044134 defer tracy.end();
41054135
4136 const pt = sema.pt;
4137
41064138 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41074139 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
41084140 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
41094141 if (block.is_comptime) {
41104142 return sema.analyzeComptimeAlloc(block, var_ty, .none);
41114143 }
4112 const target = sema.mod.getTarget();
4113 const ptr_type = try sema.mod.ptrTypeSema(.{
4144 const target = pt.zcu.getTarget();
4145 const ptr_type = try pt.ptrTypeSema(.{
41144146 .child = var_ty.toIntern(),
41154147 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
41164148 });
......@@ -4125,6 +4157,8 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
41254157 const tracy = trace(@src());
41264158 defer tracy.end();
41274159
4160 const pt = sema.pt;
4161
41284162 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41294163 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
41304164 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
......@@ -4132,8 +4166,8 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
41324166 return sema.analyzeComptimeAlloc(block, var_ty, .none);
41334167 }
41344168 try sema.validateVarType(block, ty_src, var_ty, false);
4135 const target = sema.mod.getTarget();
4136 const ptr_type = try sema.mod.ptrTypeSema(.{
4169 const target = pt.zcu.getTarget();
4170 const ptr_type = try pt.ptrTypeSema(.{
41374171 .child = var_ty.toIntern(),
41384172 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
41394173 });
......@@ -4181,7 +4215,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
41814215 const tracy = trace(@src());
41824216 defer tracy.end();
41834217
4184 const mod = sema.mod;
4218 const pt = sema.pt;
4219 const mod = pt.zcu;
41854220 const gpa = sema.gpa;
41864221 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41874222 const src = block.nodeOffset(inst_data.src_node);
......@@ -4206,7 +4241,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42064241 .anon_decl => |a| a.val,
42074242 .comptime_alloc => |i| val: {
42084243 const alloc = sema.getComptimeAlloc(i);
4209 break :val (try alloc.val.intern(mod, sema.arena)).toIntern();
4244 break :val (try alloc.val.intern(pt, sema.arena)).toIntern();
42104245 },
42114246 else => unreachable,
42124247 };
......@@ -4232,7 +4267,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42324267 }
42334268 const final_elem_ty = try sema.resolvePeerTypes(block, ty_src, peer_vals, .none);
42344269
4235 const final_ptr_ty = try mod.ptrTypeSema(.{
4270 const final_ptr_ty = try pt.ptrTypeSema(.{
42364271 .child = final_elem_ty.toIntern(),
42374272 .flags = .{
42384273 .alignment = ia1.alignment,
......@@ -4244,7 +4279,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42444279 try sema.validateVarType(block, ty_src, final_elem_ty, false);
42454280 } else if (try sema.resolveComptimeKnownAllocPtr(block, ptr, final_ptr_ty)) |ptr_val| {
42464281 const const_ptr_ty = try sema.makePtrTyConst(final_ptr_ty);
4247 const new_const_ptr = try mod.getCoerced(Value.fromInterned(ptr_val), const_ptr_ty);
4282 const new_const_ptr = try pt.getCoerced(Value.fromInterned(ptr_val), const_ptr_ty);
42484283
42494284 // Remap the ZIR operand to the resolved pointer value
42504285 sema.inst_map.putAssumeCapacity(inst_data.operand.toIndex().?, Air.internedToRef(new_const_ptr.toIntern()));
......@@ -4252,7 +4287,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42524287 // Unless the block is comptime, `alloc_inferred` always produces
42534288 // a runtime constant. The final inferred type needs to be
42544289 // fully resolved so it can be lowered in codegen.
4255 try final_elem_ty.resolveFully(mod);
4290 try final_elem_ty.resolveFully(pt);
42564291
42574292 return;
42584293 }
......@@ -4261,7 +4296,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42614296 // The alloc wasn't comptime-known per the above logic, so the
42624297 // type cannot be comptime-only.
42634298 // TODO: source location of runtime control flow
4264 return sema.fail(block, src, "value with comptime-only type '{}' depends on runtime control flow", .{final_elem_ty.fmt(mod)});
4299 return sema.fail(block, src, "value with comptime-only type '{}' depends on runtime control flow", .{final_elem_ty.fmt(pt)});
42654300 }
42664301
42674302 // Change it to a normal alloc.
......@@ -4318,7 +4353,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
43184353}
43194354
43204355fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
4321 const mod = sema.mod;
4356 const pt = sema.pt;
4357 const mod = pt.zcu;
43224358 const gpa = sema.gpa;
43234359 const ip = &mod.intern_pool;
43244360 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -4355,7 +4391,7 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
43554391 if (!object_ty.isIndexable(mod)) {
43564392 // Instead of using checkIndexable we customize this error.
43574393 const msg = msg: {
4358 const msg = try sema.errMsg(arg_src, "type '{}' is not indexable and not a range", .{object_ty.fmt(sema.mod)});
4394 const msg = try sema.errMsg(arg_src, "type '{}' is not indexable and not a range", .{object_ty.fmt(pt)});
43594395 errdefer msg.destroy(sema.gpa);
43604396 try sema.errNote(arg_src, msg, "for loop operand must be a range, array, slice, tuple, or vector", .{});
43614397
......@@ -4387,10 +4423,10 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
43874423 .input_index = len_idx,
43884424 } });
43894425 try sema.errNote(a_src, msg, "length {} here", .{
4390 v.fmtValue(sema.mod, sema),
4426 v.fmtValue(pt, sema),
43914427 });
43924428 try sema.errNote(arg_src, msg, "length {} here", .{
4393 arg_val.fmtValue(sema.mod, sema),
4429 arg_val.fmtValue(pt, sema),
43944430 });
43954431 break :msg msg;
43964432 };
......@@ -4427,7 +4463,7 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
44274463 .input_index = i,
44284464 } });
44294465 try sema.errNote(arg_src, msg, "type '{}' has no upper bound", .{
4430 object_ty.fmt(sema.mod),
4466 object_ty.fmt(pt),
44314467 });
44324468 }
44334469 break :msg msg;
......@@ -4453,7 +4489,8 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
44534489/// Given a `*E!?T`, returns a (valid) `*T`.
44544490/// May invalidate already-stored payload data.
44554491fn optEuBasePtrInit(sema: *Sema, block: *Block, ptr: Air.Inst.Ref, src: LazySrcLoc) CompileError!Air.Inst.Ref {
4456 const mod = sema.mod;
4492 const pt = sema.pt;
4493 const mod = pt.zcu;
44574494 var base_ptr = ptr;
44584495 while (true) switch (sema.typeOf(base_ptr).childType(mod).zigTypeTag(mod)) {
44594496 .ErrorUnion => base_ptr = try sema.analyzeErrUnionPayloadPtr(block, src, base_ptr, false, true),
......@@ -4471,7 +4508,8 @@ fn zirOptEuBasePtrInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compile
44714508}
44724509
44734510fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
4474 const mod = sema.mod;
4511 const pt = sema.pt;
4512 const mod = pt.zcu;
44754513 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
44764514 const src = block.nodeOffset(pl_node.src_node);
44774515 const extra = sema.code.extraData(Zir.Inst.Bin, pl_node.payload_index).data;
......@@ -4503,10 +4541,10 @@ fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
45034541 switch (val_ty.zigTypeTag(mod)) {
45044542 .Array, .Vector => {},
45054543 else => if (!val_ty.isTuple(mod)) {
4506 return sema.fail(block, src, "expected array of '{}', found '{}'", .{ elem_ty.fmt(mod), val_ty.fmt(mod) });
4544 return sema.fail(block, src, "expected array of '{}', found '{}'", .{ elem_ty.fmt(pt), val_ty.fmt(pt) });
45074545 },
45084546 }
4509 const want_ty = try mod.arrayType(.{
4547 const want_ty = try pt.arrayType(.{
45104548 .len = val_ty.arrayLen(mod),
45114549 .child = elem_ty.toIntern(),
45124550 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
......@@ -4522,7 +4560,8 @@ fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
45224560}
45234561
45244562fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
4525 const mod = sema.mod;
4563 const pt = sema.pt;
4564 const mod = pt.zcu;
45264565 const un_tok = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
45274566 const src = block.tokenOffset(un_tok.src_tok);
45284567 // In case of GenericPoison, we don't actually have a type, so this will be
......@@ -4538,7 +4577,7 @@ fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
45384577 if (ty_operand.isGenericPoison()) return;
45394578 if (ty_operand.optEuBaseType(mod).zigTypeTag(mod) != .Pointer) {
45404579 return sema.failWithOwnedErrorMsg(block, msg: {
4541 const msg = try sema.errMsg(src, "expected type '{}', found pointer", .{ty_operand.fmt(mod)});
4580 const msg = try sema.errMsg(src, "expected type '{}', found pointer", .{ty_operand.fmt(pt)});
45424581 errdefer msg.destroy(sema.gpa);
45434582 try sema.errNote(src, msg, "address-of operator always returns a pointer", .{});
45444583 break :msg msg;
......@@ -4551,7 +4590,8 @@ fn zirValidateArrayInitRefTy(
45514590 block: *Block,
45524591 inst: Zir.Inst.Index,
45534592) CompileError!Air.Inst.Ref {
4554 const mod = sema.mod;
4593 const pt = sema.pt;
4594 const mod = pt.zcu;
45554595 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
45564596 const src = block.nodeOffset(pl_node.src_node);
45574597 const extra = sema.code.extraData(Zir.Inst.ArrayInitRefTy, pl_node.payload_index).data;
......@@ -4565,7 +4605,7 @@ fn zirValidateArrayInitRefTy(
45654605 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
45664606 .Slice, .Many => {
45674607 // Use array of correct length
4568 const arr_ty = try mod.arrayType(.{
4608 const arr_ty = try pt.arrayType(.{
45694609 .len = extra.elem_count,
45704610 .child = ptr_ty.childType(mod).toIntern(),
45714611 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
......@@ -4593,7 +4633,8 @@ fn zirValidateArrayInitTy(
45934633 inst: Zir.Inst.Index,
45944634 is_result_ty: bool,
45954635) CompileError!void {
4596 const mod = sema.mod;
4636 const pt = sema.pt;
4637 const mod = pt.zcu;
45974638 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
45984639 const src = block.nodeOffset(inst_data.src_node);
45994640 const ty_src: LazySrcLoc = if (is_result_ty) src else block.src(.{ .node_offset_init_ty = inst_data.src_node });
......@@ -4615,7 +4656,8 @@ fn validateArrayInitTy(
46154656 init_count: u32,
46164657 ty: Type,
46174658) CompileError!void {
4618 const mod = sema.mod;
4659 const pt = sema.pt;
4660 const mod = pt.zcu;
46194661 switch (ty.zigTypeTag(mod)) {
46204662 .Array => {
46214663 const array_len = ty.arrayLen(mod);
......@@ -4636,7 +4678,7 @@ fn validateArrayInitTy(
46364678 return;
46374679 },
46384680 .Struct => if (ty.isTuple(mod)) {
4639 try ty.resolveFields(mod);
4681 try ty.resolveFields(pt);
46404682 const array_len = ty.arrayLen(mod);
46414683 if (init_count > array_len) {
46424684 return sema.fail(block, src, "expected at most {d} tuple fields; found {d}", .{
......@@ -4656,7 +4698,8 @@ fn zirValidateStructInitTy(
46564698 inst: Zir.Inst.Index,
46574699 is_result_ty: bool,
46584700) CompileError!void {
4659 const mod = sema.mod;
4701 const pt = sema.pt;
4702 const mod = pt.zcu;
46604703 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
46614704 const src = block.nodeOffset(inst_data.src_node);
46624705 const ty = sema.resolveType(block, src, inst_data.operand) catch |err| switch (err) {
......@@ -4681,7 +4724,8 @@ fn zirValidatePtrStructInit(
46814724 const tracy = trace(@src());
46824725 defer tracy.end();
46834726
4684 const mod = sema.mod;
4727 const pt = sema.pt;
4728 const mod = pt.zcu;
46854729 const validate_inst = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
46864730 const init_src = block.nodeOffset(validate_inst.src_node);
46874731 const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
......@@ -4716,7 +4760,8 @@ fn validateUnionInit(
47164760 instrs: []const Zir.Inst.Index,
47174761 union_ptr: Air.Inst.Ref,
47184762) CompileError!void {
4719 const mod = sema.mod;
4763 const pt = sema.pt;
4764 const mod = pt.zcu;
47204765 const gpa = sema.gpa;
47214766
47224767 if (instrs.len != 1) {
......@@ -4814,7 +4859,7 @@ fn validateUnionInit(
48144859 }
48154860
48164861 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
4817 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
4862 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
48184863 const field_type = union_ty.unionFieldType(tag_val, mod).?;
48194864
48204865 if (try sema.typeHasOnePossibleValue(field_type)) |field_only_value| {
......@@ -4848,7 +4893,7 @@ fn validateUnionInit(
48484893 }
48494894 block.instructions.shrinkRetainingCapacity(block_index);
48504895
4851 const union_val = try mod.intern(.{ .un = .{
4896 const union_val = try pt.intern(.{ .un = .{
48524897 .ty = union_ty.toIntern(),
48534898 .tag = tag_val.toIntern(),
48544899 .val = val.toIntern(),
......@@ -4875,7 +4920,8 @@ fn validateStructInit(
48754920 init_src: LazySrcLoc,
48764921 instrs: []const Zir.Inst.Index,
48774922) CompileError!void {
4878 const mod = sema.mod;
4923 const pt = sema.pt;
4924 const mod = pt.zcu;
48794925 const gpa = sema.gpa;
48804926 const ip = &mod.intern_pool;
48814927
......@@ -4914,7 +4960,7 @@ fn validateStructInit(
49144960 if (block.is_comptime and
49154961 (try sema.resolveDefinedValue(block, init_src, struct_ptr)) != null)
49164962 {
4917 try struct_ty.resolveLayout(mod);
4963 try struct_ty.resolveLayout(pt);
49184964 // In this case the only thing we need to do is evaluate the implicit
49194965 // store instructions for default field values, and report any missing fields.
49204966 // Avoid the cost of the extra machinery for detecting a comptime struct init value.
......@@ -4922,7 +4968,7 @@ fn validateStructInit(
49224968 const i: u32 = @intCast(i_usize);
49234969 if (field_ptr != .none) continue;
49244970
4925 try struct_ty.resolveStructFieldInits(mod);
4971 try struct_ty.resolveStructFieldInits(pt);
49264972 const default_val = struct_ty.structFieldDefaultValue(i, mod);
49274973 if (default_val.toIntern() == .unreachable_value) {
49284974 const field_name = struct_ty.structFieldName(i, mod).unwrap() orelse {
......@@ -4971,7 +5017,7 @@ fn validateStructInit(
49715017 const air_tags = sema.air_instructions.items(.tag);
49725018 const air_datas = sema.air_instructions.items(.data);
49735019
4974 try struct_ty.resolveStructFieldInits(mod);
5020 try struct_ty.resolveStructFieldInits(pt);
49755021
49765022 // We collect the comptime field values in case the struct initialization
49775023 // ends up being comptime-known.
......@@ -5094,7 +5140,7 @@ fn validateStructInit(
50945140 for (block.instructions.items[first_block_index..]) |cur_inst| {
50955141 while (field_ptr_ref == .none and init_index < instrs.len) : (init_index += 1) {
50965142 const field_ty = struct_ty.structFieldType(field_indices[init_index], mod);
5097 if (try field_ty.onePossibleValue(mod)) |_| continue;
5143 if (try field_ty.onePossibleValue(pt)) |_| continue;
50985144 field_ptr_ref = sema.inst_map.get(instrs[init_index]).?;
50995145 }
51005146 switch (air_tags[@intFromEnum(cur_inst)]) {
......@@ -5122,7 +5168,7 @@ fn validateStructInit(
51225168 }
51235169 block.instructions.shrinkRetainingCapacity(block_index);
51245170
5125 const struct_val = try mod.intern(.{ .aggregate = .{
5171 const struct_val = try pt.intern(.{ .aggregate = .{
51265172 .ty = struct_ty.toIntern(),
51275173 .storage = .{ .elems = field_values },
51285174 } });
......@@ -5130,7 +5176,7 @@ fn validateStructInit(
51305176 try sema.storePtr2(block, init_src, struct_ptr, init_src, struct_init, init_src, .store);
51315177 return;
51325178 }
5133 try struct_ty.resolveLayout(mod);
5179 try struct_ty.resolveLayout(pt);
51345180
51355181 // Our task is to insert `store` instructions for all the default field values.
51365182 for (found_fields, 0..) |field_ptr, i| {
......@@ -5152,7 +5198,8 @@ fn zirValidatePtrArrayInit(
51525198 block: *Block,
51535199 inst: Zir.Inst.Index,
51545200) CompileError!void {
5155 const mod = sema.mod;
5201 const pt = sema.pt;
5202 const mod = pt.zcu;
51565203 const validate_inst = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
51575204 const init_src = block.nodeOffset(validate_inst.src_node);
51585205 const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
......@@ -5175,7 +5222,7 @@ fn zirValidatePtrArrayInit(
51755222 var root_msg: ?*Module.ErrorMsg = null;
51765223 errdefer if (root_msg) |msg| msg.destroy(sema.gpa);
51775224
5178 try array_ty.resolveStructFieldInits(mod);
5225 try array_ty.resolveStructFieldInits(pt);
51795226 var i = instrs.len;
51805227 while (i < array_len) : (i += 1) {
51815228 const default_val = array_ty.structFieldDefaultValue(i, mod).toIntern();
......@@ -5218,7 +5265,7 @@ fn zirValidatePtrArrayInit(
52185265 // sentinel-terminated array, the sentinel will not have been populated by
52195266 // any ZIR instructions at comptime; we need to do that here.
52205267 if (array_ty.sentinel(mod)) |sentinel_val| {
5221 const array_len_ref = try mod.intRef(Type.usize, array_len);
5268 const array_len_ref = try pt.intRef(Type.usize, array_len);
52225269 const sentinel_ptr = try sema.elemPtrArray(block, init_src, init_src, array_ptr, init_src, array_len_ref, true, true);
52235270 const sentinel = Air.internedToRef(sentinel_val.toIntern());
52245271 try sema.storePtr2(block, init_src, sentinel_ptr, init_src, sentinel, init_src, .store);
......@@ -5244,8 +5291,8 @@ fn zirValidatePtrArrayInit(
52445291
52455292 if (array_ty.isTuple(mod)) {
52465293 if (array_ty.structFieldIsComptime(i, mod))
5247 try array_ty.resolveStructFieldInits(mod);
5248 if (try array_ty.structFieldValueComptime(mod, i)) |opv| {
5294 try array_ty.resolveStructFieldInits(pt);
5295 if (try array_ty.structFieldValueComptime(pt, i)) |opv| {
52495296 element_vals[i] = opv.toIntern();
52505297 continue;
52515298 }
......@@ -5347,7 +5394,7 @@ fn zirValidatePtrArrayInit(
53475394 }
53485395 block.instructions.shrinkRetainingCapacity(block_index);
53495396
5350 const array_val = try mod.intern(.{ .aggregate = .{
5397 const array_val = try pt.intern(.{ .aggregate = .{
53515398 .ty = array_ty.toIntern(),
53525399 .storage = .{ .elems = element_vals },
53535400 } });
......@@ -5357,18 +5404,19 @@ fn zirValidatePtrArrayInit(
53575404}
53585405
53595406fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5360 const mod = sema.mod;
5407 const pt = sema.pt;
5408 const mod = pt.zcu;
53615409 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
53625410 const src = block.nodeOffset(inst_data.src_node);
53635411 const operand = try sema.resolveInst(inst_data.operand);
53645412 const operand_ty = sema.typeOf(operand);
53655413
53665414 if (operand_ty.zigTypeTag(mod) != .Pointer) {
5367 return sema.fail(block, src, "cannot dereference non-pointer type '{}'", .{operand_ty.fmt(mod)});
5415 return sema.fail(block, src, "cannot dereference non-pointer type '{}'", .{operand_ty.fmt(pt)});
53685416 } else switch (operand_ty.ptrSize(mod)) {
53695417 .One, .C => {},
5370 .Many => return sema.fail(block, src, "index syntax required for unknown-length pointer type '{}'", .{operand_ty.fmt(mod)}),
5371 .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(mod)}),
5418 .Many => return sema.fail(block, src, "index syntax required for unknown-length pointer type '{}'", .{operand_ty.fmt(pt)}),
5419 .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(pt)}),
53725420 }
53735421
53745422 if ((try sema.typeHasOnePossibleValue(operand_ty.childType(mod))) != null) {
......@@ -5386,7 +5434,7 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
53865434 const msg = try sema.errMsg(
53875435 src,
53885436 "values of type '{}' must be comptime-known, but operand value is runtime-known",
5389 .{elem_ty.fmt(mod)},
5437 .{elem_ty.fmt(pt)},
53905438 );
53915439 errdefer msg.destroy(sema.gpa);
53925440
......@@ -5398,7 +5446,8 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
53985446}
53995447
54005448fn zirValidateDestructure(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5401 const mod = sema.mod;
5449 const pt = sema.pt;
5450 const mod = pt.zcu;
54025451 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
54035452 const extra = sema.code.extraData(Zir.Inst.ValidateDestructure, inst_data.payload_index).data;
54045453 const src = block.nodeOffset(inst_data.src_node);
......@@ -5414,7 +5463,7 @@ fn zirValidateDestructure(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
54145463
54155464 if (!can_destructure) {
54165465 return sema.failWithOwnedErrorMsg(block, msg: {
5417 const msg = try sema.errMsg(src, "type '{}' cannot be destructured", .{operand_ty.fmt(mod)});
5466 const msg = try sema.errMsg(src, "type '{}' cannot be destructured", .{operand_ty.fmt(pt)});
54185467 errdefer msg.destroy(sema.gpa);
54195468 try sema.errNote(destructure_src, msg, "result destructured here", .{});
54205469 break :msg msg;
......@@ -5441,7 +5490,8 @@ fn failWithBadMemberAccess(
54415490 field_src: LazySrcLoc,
54425491 field_name: InternPool.NullTerminatedString,
54435492) CompileError {
5444 const mod = sema.mod;
5493 const pt = sema.pt;
5494 const mod = pt.zcu;
54455495 const kw_name = switch (agg_ty.zigTypeTag(mod)) {
54465496 .Union => "union",
54475497 .Struct => "struct",
......@@ -5451,12 +5501,12 @@ fn failWithBadMemberAccess(
54515501 };
54525502 if (agg_ty.getOwnerDeclOrNull(mod)) |some| if (mod.declIsRoot(some)) {
54535503 return sema.fail(block, field_src, "root struct of file '{}' has no member named '{}'", .{
5454 agg_ty.fmt(mod), field_name.fmt(&mod.intern_pool),
5504 agg_ty.fmt(pt), field_name.fmt(&mod.intern_pool),
54555505 });
54565506 };
54575507
54585508 return sema.fail(block, field_src, "{s} '{}' has no member named '{}'", .{
5459 kw_name, agg_ty.fmt(mod), field_name.fmt(&mod.intern_pool),
5509 kw_name, agg_ty.fmt(pt), field_name.fmt(&mod.intern_pool),
54605510 });
54615511}
54625512
......@@ -5468,8 +5518,8 @@ fn failWithBadStructFieldAccess(
54685518 field_src: LazySrcLoc,
54695519 field_name: InternPool.NullTerminatedString,
54705520) CompileError {
5471 const zcu = sema.mod;
5472 const gpa = sema.gpa;
5521 const zcu = sema.pt.zcu;
5522 const ip = &zcu.intern_pool;
54735523 const decl = zcu.declPtr(struct_type.decl.unwrap().?);
54745524 const fqn = try decl.fullyQualifiedName(zcu);
54755525
......@@ -5477,9 +5527,9 @@ fn failWithBadStructFieldAccess(
54775527 const msg = try sema.errMsg(
54785528 field_src,
54795529 "no field named '{}' in struct '{}'",
5480 .{ field_name.fmt(&zcu.intern_pool), fqn.fmt(&zcu.intern_pool) },
5530 .{ field_name.fmt(ip), fqn.fmt(ip) },
54815531 );
5482 errdefer msg.destroy(gpa);
5532 errdefer msg.destroy(sema.gpa);
54835533 try sema.errNote(struct_ty.srcLoc(zcu), msg, "struct declared here", .{});
54845534 break :msg msg;
54855535 };
......@@ -5494,7 +5544,8 @@ fn failWithBadUnionFieldAccess(
54945544 field_src: LazySrcLoc,
54955545 field_name: InternPool.NullTerminatedString,
54965546) CompileError {
5497 const zcu = sema.mod;
5547 const zcu = sema.pt.zcu;
5548 const ip = &zcu.intern_pool;
54985549 const gpa = sema.gpa;
54995550
55005551 const decl = zcu.declPtr(union_obj.decl);
......@@ -5504,7 +5555,7 @@ fn failWithBadUnionFieldAccess(
55045555 const msg = try sema.errMsg(
55055556 field_src,
55065557 "no field named '{}' in union '{}'",
5507 .{ field_name.fmt(&zcu.intern_pool), fqn.fmt(&zcu.intern_pool) },
5558 .{ field_name.fmt(ip), fqn.fmt(ip) },
55085559 );
55095560 errdefer msg.destroy(gpa);
55105561 try sema.errNote(union_ty.srcLoc(zcu), msg, "union declared here", .{});
......@@ -5514,9 +5565,9 @@ fn failWithBadUnionFieldAccess(
55145565}
55155566
55165567fn addDeclaredHereNote(sema: *Sema, parent: *Module.ErrorMsg, decl_ty: Type) !void {
5517 const mod = sema.mod;
5518 const src_loc = decl_ty.srcLocOrNull(mod) orelse return;
5519 const category = switch (decl_ty.zigTypeTag(mod)) {
5568 const zcu = sema.pt.zcu;
5569 const src_loc = decl_ty.srcLocOrNull(zcu) orelse return;
5570 const category = switch (decl_ty.zigTypeTag(zcu)) {
55205571 .Union => "union",
55215572 .Struct => "struct",
55225573 .Enum => "enum",
......@@ -5575,7 +5626,8 @@ fn storeToInferredAllocComptime(
55755626 operand: Air.Inst.Ref,
55765627 iac: *Air.Inst.Data.InferredAllocComptime,
55775628) CompileError!void {
5578 const zcu = sema.mod;
5629 const pt = sema.pt;
5630 const zcu = pt.zcu;
55795631 const operand_ty = sema.typeOf(operand);
55805632 // There will be only one store_to_inferred_ptr because we are running at comptime.
55815633 // The alloc will turn into a Decl or a ComptimeAlloc.
......@@ -5584,7 +5636,7 @@ fn storeToInferredAllocComptime(
55845636 .needed_comptime_reason = "value being stored to a comptime variable must be comptime-known",
55855637 });
55865638 };
5587 const alloc_ty = try zcu.ptrTypeSema(.{
5639 const alloc_ty = try pt.ptrTypeSema(.{
55885640 .child = operand_ty.toIntern(),
55895641 .flags = .{
55905642 .alignment = iac.alignment,
......@@ -5592,7 +5644,7 @@ fn storeToInferredAllocComptime(
55925644 },
55935645 });
55945646 if (iac.is_const and !operand_val.canMutateComptimeVarState(zcu)) {
5595 iac.ptr = try zcu.intern(.{ .ptr = .{
5647 iac.ptr = try pt.intern(.{ .ptr = .{
55965648 .ty = alloc_ty.toIntern(),
55975649 .base_addr = .{ .anon_decl = .{
55985650 .val = operand_val.toIntern(),
......@@ -5603,7 +5655,7 @@ fn storeToInferredAllocComptime(
56035655 } else {
56045656 const alloc_index = try sema.newComptimeAlloc(block, operand_ty, iac.alignment);
56055657 sema.getComptimeAlloc(alloc_index).val = .{ .interned = operand_val.toIntern() };
5606 iac.ptr = try zcu.intern(.{ .ptr = .{
5658 iac.ptr = try pt.intern(.{ .ptr = .{
56075659 .ty = alloc_ty.toIntern(),
56085660 .base_addr = .{ .comptime_alloc = alloc_index },
56095661 .byte_offset = 0,
......@@ -5624,7 +5676,8 @@ fn zirStoreNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!v
56245676 const tracy = trace(@src());
56255677 defer tracy.end();
56265678
5627 const mod = sema.mod;
5679 const pt = sema.pt;
5680 const mod = pt.zcu;
56285681 const zir_tags = sema.code.instructions.items(.tag);
56295682 const zir_datas = sema.code.instructions.items(.data);
56305683 const inst_data = zir_datas[@intFromEnum(inst)].pl_node;
......@@ -5662,23 +5715,23 @@ fn zirStoreNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!v
56625715fn zirStr(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
56635716 const bytes = sema.code.instructions.items(.data)[@intFromEnum(inst)].str.get(sema.code);
56645717 return sema.addStrLit(
5665 try sema.mod.intern_pool.getOrPutString(sema.gpa, bytes, .maybe_embedded_nulls),
5718 try sema.pt.zcu.intern_pool.getOrPutString(sema.gpa, bytes, .maybe_embedded_nulls),
56665719 bytes.len,
56675720 );
56685721}
56695722
56705723fn addNullTerminatedStrLit(sema: *Sema, string: InternPool.NullTerminatedString) CompileError!Air.Inst.Ref {
5671 return sema.addStrLit(string.toString(), string.length(&sema.mod.intern_pool));
5724 return sema.addStrLit(string.toString(), string.length(&sema.pt.zcu.intern_pool));
56725725}
56735726
56745727fn addStrLit(sema: *Sema, string: InternPool.String, len: u64) CompileError!Air.Inst.Ref {
5675 const mod = sema.mod;
5676 const array_ty = try mod.arrayType(.{
5728 const pt = sema.pt;
5729 const array_ty = try pt.arrayType(.{
56775730 .len = len,
56785731 .sentinel = .zero_u8,
56795732 .child = .u8_type,
56805733 });
5681 const val = try mod.intern(.{ .aggregate = .{
5734 const val = try pt.intern(.{ .aggregate = .{
56825735 .ty = array_ty.toIntern(),
56835736 .storage = .{ .bytes = string },
56845737 } });
......@@ -5690,16 +5743,16 @@ fn anonDeclRef(sema: *Sema, val: InternPool.Index) CompileError!Air.Inst.Ref {
56905743}
56915744
56925745fn refValue(sema: *Sema, val: InternPool.Index) CompileError!InternPool.Index {
5693 const mod = sema.mod;
5694 const ptr_ty = (try mod.ptrTypeSema(.{
5695 .child = mod.intern_pool.typeOf(val),
5746 const pt = sema.pt;
5747 const ptr_ty = (try pt.ptrTypeSema(.{
5748 .child = pt.zcu.intern_pool.typeOf(val),
56965749 .flags = .{
56975750 .alignment = .none,
56985751 .is_const = true,
56995752 .address_space = .generic,
57005753 },
57015754 })).toIntern();
5702 return mod.intern(.{ .ptr = .{
5755 return pt.intern(.{ .ptr = .{
57035756 .ty = ptr_ty,
57045757 .base_addr = .{ .anon_decl = .{
57055758 .val = val,
......@@ -5715,7 +5768,7 @@ fn zirInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
57155768 defer tracy.end();
57165769
57175770 const int = sema.code.instructions.items(.data)[@intFromEnum(inst)].int;
5718 return sema.mod.intRef(Type.comptime_int, int);
5771 return sema.pt.intRef(Type.comptime_int, int);
57195772}
57205773
57215774fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -5723,7 +5776,6 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57235776 const tracy = trace(@src());
57245777 defer tracy.end();
57255778
5726 const mod = sema.mod;
57275779 const int = sema.code.instructions.items(.data)[@intFromEnum(inst)].str;
57285780 const byte_count = int.len * @sizeOf(std.math.big.Limb);
57295781 const limb_bytes = sema.code.string_bytes[@intFromEnum(int.start)..][0..byte_count];
......@@ -5734,7 +5786,7 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57345786 const limbs = try sema.arena.alloc(std.math.big.Limb, int.len);
57355787 @memcpy(mem.sliceAsBytes(limbs), limb_bytes);
57365788
5737 return Air.internedToRef((try mod.intValue_big(Type.comptime_int, .{
5789 return Air.internedToRef((try sema.pt.intValue_big(Type.comptime_int, .{
57385790 .limbs = limbs,
57395791 .positive = true,
57405792 })).toIntern());
......@@ -5743,7 +5795,7 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57435795fn zirFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
57445796 _ = block;
57455797 const number = sema.code.instructions.items(.data)[@intFromEnum(inst)].float;
5746 return Air.internedToRef((try sema.mod.floatValue(
5798 return Air.internedToRef((try sema.pt.floatValue(
57475799 Type.comptime_float,
57485800 number,
57495801 )).toIntern());
......@@ -5754,7 +5806,7 @@ fn zirFloat128(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
57545806 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
57555807 const extra = sema.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;
57565808 const number = extra.get();
5757 return Air.internedToRef((try sema.mod.floatValue(Type.comptime_float, number)).toIntern());
5809 return Air.internedToRef((try sema.pt.floatValue(Type.comptime_float, number)).toIntern());
57585810}
57595811
57605812fn zirCompileError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
......@@ -5775,10 +5827,11 @@ fn zirCompileLog(
57755827 block: *Block,
57765828 extended: Zir.Inst.Extended.InstData,
57775829) CompileError!Air.Inst.Ref {
5778 const mod = sema.mod;
5830 const pt = sema.pt;
5831 const mod = pt.zcu;
57795832
57805833 var managed = mod.compile_log_text.toManaged(sema.gpa);
5781 defer sema.mod.compile_log_text = managed.moveToUnmanaged();
5834 defer pt.zcu.compile_log_text = managed.moveToUnmanaged();
57825835 const writer = managed.writer();
57835836
57845837 const extra = sema.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
......@@ -5792,10 +5845,10 @@ fn zirCompileLog(
57925845 const arg_ty = sema.typeOf(arg);
57935846 if (try sema.resolveValueResolveLazy(arg)) |val| {
57945847 try writer.print("@as({}, {})", .{
5795 arg_ty.fmt(mod), val.fmtValue(mod, sema),
5848 arg_ty.fmt(pt), val.fmtValue(pt, sema),
57965849 });
57975850 } else {
5798 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(mod)});
5851 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(pt)});
57995852 }
58005853 }
58015854 try writer.print("\n", .{});
......@@ -5835,7 +5888,8 @@ fn zirLoop(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError
58355888 const tracy = trace(@src());
58365889 defer tracy.end();
58375890
5838 const mod = sema.mod;
5891 const pt = sema.pt;
5892 const mod = pt.zcu;
58395893 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
58405894 const src = parent_block.nodeOffset(inst_data.src_node);
58415895 const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
......@@ -5906,7 +5960,8 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
59065960 const tracy = trace(@src());
59075961 defer tracy.end();
59085962
5909 const zcu = sema.mod;
5963 const pt = sema.pt;
5964 const zcu = pt.zcu;
59105965 const comp = zcu.comp;
59115966 const gpa = sema.gpa;
59125967 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -6005,7 +6060,7 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
60056060 zcu.astGenFile(result.file, result.file_index, path_digest, root_decl) catch |err|
60066061 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
60076062
6008 try zcu.ensureFileAnalyzed(result.file_index);
6063 try pt.ensureFileAnalyzed(result.file_index);
60096064 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
60106065 return sema.analyzeDeclVal(parent_block, src, file_root_decl_index);
60116066}
......@@ -6147,7 +6202,8 @@ fn resolveAnalyzedBlock(
61476202 defer tracy.end();
61486203
61496204 const gpa = sema.gpa;
6150 const mod = sema.mod;
6205 const pt = sema.pt;
6206 const mod = pt.zcu;
61516207
61526208 // Blocks must terminate with noreturn instruction.
61536209 assert(child_block.instructions.items.len != 0);
......@@ -6258,7 +6314,7 @@ fn resolveAnalyzedBlock(
62586314 const type_src = src; // TODO: better source location
62596315 if (try sema.typeRequiresComptime(resolved_ty)) {
62606316 const msg = msg: {
6261 const msg = try sema.errMsg(type_src, "value with comptime-only type '{}' depends on runtime control flow", .{resolved_ty.fmt(mod)});
6317 const msg = try sema.errMsg(type_src, "value with comptime-only type '{}' depends on runtime control flow", .{resolved_ty.fmt(pt)});
62626318 errdefer msg.destroy(sema.gpa);
62636319
62646320 const runtime_src = child_block.runtime_cond orelse child_block.runtime_loop.?;
......@@ -6353,7 +6409,8 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
63536409 const tracy = trace(@src());
63546410 defer tracy.end();
63556411
6356 const mod = sema.mod;
6412 const pt = sema.pt;
6413 const mod = pt.zcu;
63576414 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
63586415 const extra = sema.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;
63596416 const src = block.nodeOffset(inst_data.src_node);
......@@ -6388,7 +6445,8 @@ fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
63886445 const tracy = trace(@src());
63896446 defer tracy.end();
63906447
6391 const mod = sema.mod;
6448 const pt = sema.pt;
6449 const mod = pt.zcu;
63926450 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
63936451 const extra = sema.code.extraData(Zir.Inst.ExportValue, inst_data.payload_index).data;
63946452 const src = block.nodeOffset(inst_data.src_node);
......@@ -6421,7 +6479,8 @@ pub fn analyzeExport(
64216479 exported_decl_index: InternPool.DeclIndex,
64226480) !void {
64236481 const gpa = sema.gpa;
6424 const mod = sema.mod;
6482 const pt = sema.pt;
6483 const mod = pt.zcu;
64256484
64266485 if (options.linkage == .internal)
64276486 return;
......@@ -6433,7 +6492,7 @@ pub fn analyzeExport(
64336492
64346493 if (!try sema.validateExternType(export_ty, .other)) {
64356494 const msg = msg: {
6436 const msg = try sema.errMsg(src, "unable to export type '{}'", .{export_ty.fmt(mod)});
6495 const msg = try sema.errMsg(src, "unable to export type '{}'", .{export_ty.fmt(pt)});
64376496 errdefer msg.destroy(gpa);
64386497
64396498 try sema.explainWhyTypeIsNotExtern(msg, src, export_ty, .other);
......@@ -6460,7 +6519,8 @@ pub fn analyzeExport(
64606519}
64616520
64626521fn zirSetAlignStack(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
6463 const mod = sema.mod;
6522 const pt = sema.pt;
6523 const mod = pt.zcu;
64646524 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
64656525 const operand_src = block.builtinCallArgSrc(extra.node, 0);
64666526 const src = block.nodeOffset(extra.node);
......@@ -6502,7 +6562,8 @@ fn zirSetAlignStack(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
65026562}
65036563
65046564fn zirSetCold(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
6505 const mod = sema.mod;
6565 const pt = sema.pt;
6566 const mod = pt.zcu;
65066567 const ip = &mod.intern_pool;
65076568 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
65086569 const operand_src = block.builtinCallArgSrc(extra.node, 0);
......@@ -6628,7 +6689,8 @@ fn addDbgVar(
66286689) CompileError!void {
66296690 if (block.is_comptime or block.ownerModule().strip) return;
66306691
6631 const mod = sema.mod;
6692 const pt = sema.pt;
6693 const mod = pt.zcu;
66326694 const operand_ty = sema.typeOf(operand);
66336695 const val_ty = switch (air_tag) {
66346696 .dbg_var_ptr => operand_ty.childType(mod),
......@@ -6669,7 +6731,8 @@ fn addDbgVar(
66696731}
66706732
66716733fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6672 const mod = sema.mod;
6734 const pt = sema.pt;
6735 const mod = pt.zcu;
66736736 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
66746737 const src = block.tokenOffset(inst_data.src_tok);
66756738 const decl_name = try mod.intern_pool.getOrPutString(
......@@ -6682,7 +6745,8 @@ fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
66826745}
66836746
66846747fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6685 const mod = sema.mod;
6748 const pt = sema.pt;
6749 const mod = pt.zcu;
66866750 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
66876751 const src = block.tokenOffset(inst_data.src_tok);
66886752 const decl_name = try mod.intern_pool.getOrPutString(
......@@ -6695,7 +6759,8 @@ fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
66956759}
66966760
66976761fn lookupIdentifier(sema: *Sema, block: *Block, src: LazySrcLoc, name: InternPool.NullTerminatedString) !InternPool.DeclIndex {
6698 const mod = sema.mod;
6762 const pt = sema.pt;
6763 const mod = pt.zcu;
66996764 var namespace = block.namespace;
67006765 while (true) {
67016766 if (try sema.lookupInNamespace(block, src, namespace.toOptional(), name, false)) |decl_index| {
......@@ -6716,7 +6781,8 @@ fn lookupInNamespace(
67166781 ident_name: InternPool.NullTerminatedString,
67176782 observe_usingnamespace: bool,
67186783) CompileError!?InternPool.DeclIndex {
6719 const mod = sema.mod;
6784 const pt = sema.pt;
6785 const mod = pt.zcu;
67206786
67216787 const namespace_index = opt_namespace_index.unwrap() orelse return null;
67226788 const namespace = mod.namespacePtr(namespace_index);
......@@ -6811,7 +6877,8 @@ fn lookupInNamespace(
68116877}
68126878
68136879fn funcDeclSrc(sema: *Sema, func_inst: Air.Inst.Ref) !?*Decl {
6814 const mod = sema.mod;
6880 const pt = sema.pt;
6881 const mod = pt.zcu;
68156882 const func_val = (try sema.resolveValue(func_inst)) orelse return null;
68166883 if (func_val.isUndef(mod)) return null;
68176884 const owner_decl_index = switch (mod.intern_pool.indexToKey(func_val.toIntern())) {
......@@ -6827,18 +6894,19 @@ fn funcDeclSrc(sema: *Sema, func_inst: Air.Inst.Ref) !?*Decl {
68276894}
68286895
68296896pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref {
6830 const mod = sema.mod;
6897 const pt = sema.pt;
6898 const mod = pt.zcu;
68316899 const gpa = sema.gpa;
68326900
68336901 if (block.is_comptime or block.is_typeof) {
6834 const index_val = try mod.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
6902 const index_val = try pt.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
68356903 return Air.internedToRef(index_val.toIntern());
68366904 }
68376905
68386906 if (!block.ownerModule().error_tracing) return .none;
68396907
6840 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6841 try stack_trace_ty.resolveFields(mod);
6908 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6909 try stack_trace_ty.resolveFields(pt);
68426910 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
68436911 const field_index = sema.structFieldIndex(block, stack_trace_ty, field_name, LazySrcLoc.unneeded) catch |err| switch (err) {
68446912 error.AnalysisFail => @panic("std.builtin.StackTrace is corrupt"),
......@@ -6864,7 +6932,8 @@ fn popErrorReturnTrace(
68646932 operand: Air.Inst.Ref,
68656933 saved_error_trace_index: Air.Inst.Ref,
68666934) CompileError!void {
6867 const mod = sema.mod;
6935 const pt = sema.pt;
6936 const mod = pt.zcu;
68686937 const gpa = sema.gpa;
68696938 var is_non_error: ?bool = null;
68706939 var is_non_error_inst: Air.Inst.Ref = undefined;
......@@ -6878,9 +6947,9 @@ fn popErrorReturnTrace(
68786947 // AstGen determined this result does not go to an error-handling expr (try/catch/return etc.), or
68796948 // the result is comptime-known to be a non-error. Either way, pop unconditionally.
68806949
6881 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6882 try stack_trace_ty.resolveFields(mod);
6883 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
6950 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6951 try stack_trace_ty.resolveFields(pt);
6952 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
68846953 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
68856954 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
68866955 const field_ptr = try sema.structFieldPtr(block, src, err_return_trace, field_name, src, stack_trace_ty, true);
......@@ -6904,9 +6973,9 @@ fn popErrorReturnTrace(
69046973 defer then_block.instructions.deinit(gpa);
69056974
69066975 // If non-error, then pop the error return trace by restoring the index.
6907 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6908 try stack_trace_ty.resolveFields(mod);
6909 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
6976 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6977 try stack_trace_ty.resolveFields(pt);
6978 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
69106979 const err_return_trace = try then_block.addTy(.err_return_trace, ptr_stack_trace_ty);
69116980 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
69126981 const field_ptr = try sema.structFieldPtr(&then_block, src, err_return_trace, field_name, src, stack_trace_ty, true);
......@@ -6947,7 +7016,8 @@ fn zirCall(
69477016 const tracy = trace(@src());
69487017 defer tracy.end();
69497018
6950 const mod = sema.mod;
7019 const pt = sema.pt;
7020 const mod = pt.zcu;
69517021 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
69527022 const callee_src = block.src(.{ .node_offset_call_func = inst_data.src_node });
69537023 const call_src = block.nodeOffset(inst_data.src_node);
......@@ -7031,8 +7101,8 @@ fn zirCall(
70317101 // If any input is an error-type, we might need to pop any trace it generated. Otherwise, we only
70327102 // need to clean-up our own trace if we were passed to a non-error-handling expression.
70337103 if (input_is_error or (pop_error_return_trace and return_ty.isError(mod))) {
7034 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
7035 try stack_trace_ty.resolveFields(mod);
7104 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
7105 try stack_trace_ty.resolveFields(pt);
70367106 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, "index", .no_embedded_nulls);
70377107 const field_index = try sema.structFieldIndex(block, stack_trace_ty, field_name, call_src);
70387108
......@@ -7065,7 +7135,8 @@ fn checkCallArgumentCount(
70657135 total_args: usize,
70667136 member_fn: bool,
70677137) !Type {
7068 const mod = sema.mod;
7138 const pt = sema.pt;
7139 const mod = pt.zcu;
70697140 const func_ty = func_ty: {
70707141 switch (callee_ty.zigTypeTag(mod)) {
70717142 .Fn => break :func_ty callee_ty,
......@@ -7082,7 +7153,7 @@ fn checkCallArgumentCount(
70827153 {
70837154 const msg = msg: {
70847155 const msg = try sema.errMsg(func_src, "cannot call optional type '{}'", .{
7085 callee_ty.fmt(mod),
7156 callee_ty.fmt(pt),
70867157 });
70877158 errdefer msg.destroy(sema.gpa);
70887159 try sema.errNote(func_src, msg, "consider using '.?', 'orelse' or 'if'", .{});
......@@ -7093,7 +7164,7 @@ fn checkCallArgumentCount(
70937164 },
70947165 else => {},
70957166 }
7096 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(mod)});
7167 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(pt)});
70977168 };
70987169
70997170 const func_ty_info = mod.typeToFunc(func_ty).?;
......@@ -7142,7 +7213,8 @@ fn callBuiltin(
71427213 args: []const Air.Inst.Ref,
71437214 operation: CallOperation,
71447215) !void {
7145 const mod = sema.mod;
7216 const pt = sema.pt;
7217 const mod = pt.zcu;
71467218 const callee_ty = sema.typeOf(builtin_fn);
71477219 const func_ty = func_ty: {
71487220 switch (callee_ty.zigTypeTag(mod)) {
......@@ -7155,7 +7227,7 @@ fn callBuiltin(
71557227 },
71567228 else => {},
71577229 }
7158 std.debug.panic("type '{}' is not a function calling builtin fn", .{callee_ty.fmt(mod)});
7230 std.debug.panic("type '{}' is not a function calling builtin fn", .{callee_ty.fmt(pt)});
71597231 };
71607232
71617233 const func_ty_info = mod.typeToFunc(func_ty).?;
......@@ -7261,7 +7333,8 @@ const CallArgsInfo = union(enum) {
72617333 func_ty_info: InternPool.Key.FuncType,
72627334 func_inst: Air.Inst.Ref,
72637335 ) CompileError!Air.Inst.Ref {
7264 const mod = sema.mod;
7336 const pt = sema.pt;
7337 const mod = pt.zcu;
72657338 const param_count = func_ty_info.param_types.len;
72667339 const uncoerced_arg: Air.Inst.Ref = switch (cai) {
72677340 inline .resolved, .call_builtin => |resolved| resolved.args[arg_index],
......@@ -7438,7 +7511,8 @@ fn analyzeCall(
74387511 call_dbg_node: ?Zir.Inst.Index,
74397512 operation: CallOperation,
74407513) CompileError!Air.Inst.Ref {
7441 const mod = sema.mod;
7514 const pt = sema.pt;
7515 const mod = pt.zcu;
74427516 const ip = &mod.intern_pool;
74437517
74447518 const callee_ty = sema.typeOf(func);
......@@ -7741,10 +7815,10 @@ fn analyzeCall(
77417815 const ies = try sema.arena.create(InferredErrorSet);
77427816 ies.* = .{ .func = .none };
77437817 sema.fn_ret_ty_ies = ies;
7744 sema.fn_ret_ty = Type.fromInterned((try ip.get(gpa, .{ .error_union_type = .{
7818 sema.fn_ret_ty = Type.fromInterned(try pt.intern(.{ .error_union_type = .{
77457819 .error_set_type = .adhoc_inferred_error_set_type,
77467820 .payload_type = sema.fn_ret_ty.toIntern(),
7747 } })));
7821 } }));
77487822 }
77497823
77507824 // This `res2` is here instead of directly breaking from `res` due to a stage1
......@@ -7816,7 +7890,7 @@ fn analyzeCall(
78167890 // TODO: check whether any external comptime memory was mutated by the
78177891 // comptime function call. If so, then do not memoize the call here.
78187892 if (should_memoize and !Value.fromInterned(result_interned).canMutateComptimeVarState(mod)) {
7819 _ = try mod.intern(.{ .memoized_call = .{
7893 _ = try pt.intern(.{ .memoized_call = .{
78207894 .func = module_fn_index,
78217895 .arg_values = memoized_arg_values,
78227896 .result = result_transformed,
......@@ -7921,7 +7995,8 @@ fn analyzeCall(
79217995}
79227996
79237997fn handleTailCall(sema: *Sema, block: *Block, call_src: LazySrcLoc, func_ty: Type, result: Air.Inst.Ref) !Air.Inst.Ref {
7924 const mod = sema.mod;
7998 const pt = sema.pt;
7999 const mod = pt.zcu;
79258000 const target = mod.getTarget();
79268001 const backend = mod.comp.getZigBackend();
79278002 if (!target_util.supportsTailCall(target, backend)) {
......@@ -7932,7 +8007,7 @@ fn handleTailCall(sema: *Sema, block: *Block, call_src: LazySrcLoc, func_ty: Typ
79328007 const func_decl = mod.funcOwnerDeclPtr(sema.owner_func_index);
79338008 if (!func_ty.eql(func_decl.typeOf(mod), mod)) {
79348009 return sema.fail(block, call_src, "unable to perform tail call: type of function being called '{}' does not match type of calling function '{}'", .{
7935 func_ty.fmt(mod), func_decl.typeOf(mod).fmt(mod),
8010 func_ty.fmt(pt), func_decl.typeOf(mod).fmt(pt),
79368011 });
79378012 }
79388013 _ = try block.addUnOp(.ret, result);
......@@ -7954,7 +8029,7 @@ fn analyzeInlineCallArg(
79548029 func_ty_info: InternPool.Key.FuncType,
79558030 func_inst: Air.Inst.Ref,
79568031) !?Air.Inst.Ref {
7957 const mod = ics.sema.mod;
8032 const mod = ics.sema.pt.zcu;
79588033 const ip = &mod.intern_pool;
79598034 const zir_tags = ics.callee().code.instructions.items(.tag);
79608035 switch (zir_tags[@intFromEnum(inst)]) {
......@@ -8084,7 +8159,8 @@ fn instantiateGenericCall(
80848159 call_tag: Air.Inst.Tag,
80858160 call_dbg_node: ?Zir.Inst.Index,
80868161) CompileError!Air.Inst.Ref {
8087 const zcu = sema.mod;
8162 const pt = sema.pt;
8163 const zcu = pt.zcu;
80888164 const gpa = sema.gpa;
80898165 const ip = &zcu.intern_pool;
80908166
......@@ -8127,7 +8203,7 @@ fn instantiateGenericCall(
81278203 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
81288204 // new, monomorphized function, with the comptime parameters elided.
81298205 var child_sema: Sema = .{
8130 .mod = zcu,
8206 .pt = pt,
81318207 .gpa = gpa,
81328208 .arena = sema.arena,
81338209 .code = fn_zir,
......@@ -8358,7 +8434,8 @@ fn instantiateGenericCall(
83588434}
83598435
83608436fn resolveTupleLazyValues(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
8361 const mod = sema.mod;
8437 const pt = sema.pt;
8438 const mod = pt.zcu;
83628439 const ip = &mod.intern_pool;
83638440 const tuple = switch (ip.indexToKey(ty.toIntern())) {
83648441 .anon_struct_type => |tuple| tuple,
......@@ -8373,9 +8450,8 @@ fn resolveTupleLazyValues(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type)
83738450}
83748451
83758452fn zirIntType(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8376 const mod = sema.mod;
83778453 const int_type = sema.code.instructions.items(.data)[@intFromEnum(inst)].int_type;
8378 const ty = try mod.intType(int_type.signedness, int_type.bit_count);
8454 const ty = try sema.pt.intType(int_type.signedness, int_type.bit_count);
83798455 return Air.internedToRef(ty.toIntern());
83808456}
83818457
......@@ -8383,22 +8459,24 @@ fn zirOptionalType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
83838459 const tracy = trace(@src());
83848460 defer tracy.end();
83858461
8386 const mod = sema.mod;
8462 const pt = sema.pt;
8463 const mod = pt.zcu;
83878464 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
83888465 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
83898466 const child_type = try sema.resolveType(block, operand_src, inst_data.operand);
83908467 if (child_type.zigTypeTag(mod) == .Opaque) {
8391 return sema.fail(block, operand_src, "opaque type '{}' cannot be optional", .{child_type.fmt(mod)});
8468 return sema.fail(block, operand_src, "opaque type '{}' cannot be optional", .{child_type.fmt(pt)});
83928469 } else if (child_type.zigTypeTag(mod) == .Null) {
8393 return sema.fail(block, operand_src, "type '{}' cannot be optional", .{child_type.fmt(mod)});
8470 return sema.fail(block, operand_src, "type '{}' cannot be optional", .{child_type.fmt(pt)});
83948471 }
8395 const opt_type = try mod.optionalType(child_type.toIntern());
8472 const opt_type = try pt.optionalType(child_type.toIntern());
83968473
83978474 return Air.internedToRef(opt_type.toIntern());
83988475}
83998476
84008477fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8401 const mod = sema.mod;
8478 const pt = sema.pt;
8479 const mod = pt.zcu;
84028480 const bin = sema.code.instructions.items(.data)[@intFromEnum(inst)].bin;
84038481 const maybe_wrapped_indexable_ty = sema.resolveType(block, LazySrcLoc.unneeded, bin.lhs) catch |err| switch (err) {
84048482 // Since this is a ZIR instruction that returns a type, encountering
......@@ -8409,7 +8487,7 @@ fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
84098487 else => |e| return e,
84108488 };
84118489 const indexable_ty = maybe_wrapped_indexable_ty.optEuBaseType(mod);
8412 try indexable_ty.resolveFields(mod);
8490 try indexable_ty.resolveFields(pt);
84138491 assert(indexable_ty.isIndexable(mod)); // validated by a previous instruction
84148492 if (indexable_ty.zigTypeTag(mod) == .Struct) {
84158493 const elem_type = indexable_ty.structFieldType(@intFromEnum(bin.rhs), mod);
......@@ -8421,7 +8499,8 @@ fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
84218499}
84228500
84238501fn zirElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8424 const mod = sema.mod;
8502 const pt = sema.pt;
8503 const mod = pt.zcu;
84258504 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84268505 const maybe_wrapped_ptr_ty = sema.resolveType(block, LazySrcLoc.unneeded, un_node.operand) catch |err| switch (err) {
84278506 error.GenericPoison => return .generic_poison_type,
......@@ -8439,7 +8518,8 @@ fn zirElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
84398518}
84408519
84418520fn zirIndexablePtrElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8442 const mod = sema.mod;
8521 const pt = sema.pt;
8522 const mod = pt.zcu;
84438523 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84448524 const src = block.nodeOffset(un_node.src_node);
84458525 const ptr_ty = sema.resolveType(block, src, un_node.operand) catch |err| switch (err) {
......@@ -8455,7 +8535,8 @@ fn zirIndexablePtrElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
84558535}
84568536
84578537fn zirVectorElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8458 const mod = sema.mod;
8538 const pt = sema.pt;
8539 const mod = pt.zcu;
84598540 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84608541 const vec_ty = sema.resolveType(block, LazySrcLoc.unneeded, un_node.operand) catch |err| switch (err) {
84618542 // Since this is a ZIR instruction that returns a type, encountering
......@@ -8466,13 +8547,12 @@ fn zirVectorElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
84668547 else => |e| return e,
84678548 };
84688549 if (!vec_ty.isVector(mod)) {
8469 return sema.fail(block, block.nodeOffset(un_node.src_node), "expected vector type, found '{}'", .{vec_ty.fmt(mod)});
8550 return sema.fail(block, block.nodeOffset(un_node.src_node), "expected vector type, found '{}'", .{vec_ty.fmt(pt)});
84708551 }
84718552 return Air.internedToRef(vec_ty.childType(mod).toIntern());
84728553}
84738554
84748555fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8475 const mod = sema.mod;
84768556 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
84778557 const len_src = block.builtinCallArgSrc(inst_data.src_node, 0);
84788558 const elem_type_src = block.builtinCallArgSrc(inst_data.src_node, 1);
......@@ -8482,7 +8562,7 @@ fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
84828562 }));
84838563 const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);
84848564 try sema.checkVectorElemType(block, elem_type_src, elem_type);
8485 const vector_type = try mod.vectorType(.{
8565 const vector_type = try sema.pt.vectorType(.{
84868566 .len = len,
84878567 .child = elem_type.toIntern(),
84888568 });
......@@ -8502,7 +8582,7 @@ fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
85028582 });
85038583 const elem_type = try sema.resolveType(block, elem_src, extra.rhs);
85048584 try sema.validateArrayElemType(block, elem_type, elem_src);
8505 const array_ty = try sema.mod.arrayType(.{
8585 const array_ty = try sema.pt.arrayType(.{
85068586 .len = len,
85078587 .child = elem_type.toIntern(),
85088588 });
......@@ -8529,7 +8609,7 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
85298609 const sentinel_val = try sema.resolveConstDefinedValue(block, sentinel_src, sentinel, .{
85308610 .needed_comptime_reason = "array sentinel value must be comptime-known",
85318611 });
8532 const array_ty = try sema.mod.arrayType(.{
8612 const array_ty = try sema.pt.arrayType(.{
85338613 .len = len,
85348614 .sentinel = sentinel_val.toIntern(),
85358615 .child = elem_type.toIntern(),
......@@ -8539,9 +8619,10 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
85398619}
85408620
85418621fn validateArrayElemType(sema: *Sema, block: *Block, elem_type: Type, elem_src: LazySrcLoc) !void {
8542 const mod = sema.mod;
8622 const pt = sema.pt;
8623 const mod = pt.zcu;
85438624 if (elem_type.zigTypeTag(mod) == .Opaque) {
8544 return sema.fail(block, elem_src, "array of opaque type '{}' not allowed", .{elem_type.fmt(mod)});
8625 return sema.fail(block, elem_src, "array of opaque type '{}' not allowed", .{elem_type.fmt(pt)});
85458626 } else if (elem_type.zigTypeTag(mod) == .NoReturn) {
85468627 return sema.fail(block, elem_src, "array of 'noreturn' not allowed", .{});
85478628 }
......@@ -8567,7 +8648,8 @@ fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
85678648 const tracy = trace(@src());
85688649 defer tracy.end();
85698650
8570 const mod = sema.mod;
8651 const pt = sema.pt;
8652 const mod = pt.zcu;
85718653 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
85728654 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
85738655 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -8577,40 +8659,41 @@ fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
85778659
85788660 if (error_set.zigTypeTag(mod) != .ErrorSet) {
85798661 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{
8580 error_set.fmt(mod),
8662 error_set.fmt(pt),
85818663 });
85828664 }
85838665 try sema.validateErrorUnionPayloadType(block, payload, rhs_src);
8584 const err_union_ty = try mod.errorUnionType(error_set, payload);
8666 const err_union_ty = try pt.errorUnionType(error_set, payload);
85858667 return Air.internedToRef(err_union_ty.toIntern());
85868668}
85878669
85888670fn validateErrorUnionPayloadType(sema: *Sema, block: *Block, payload_ty: Type, payload_src: LazySrcLoc) !void {
8589 const mod = sema.mod;
8671 const pt = sema.pt;
8672 const mod = pt.zcu;
85908673 if (payload_ty.zigTypeTag(mod) == .Opaque) {
85918674 return sema.fail(block, payload_src, "error union with payload of opaque type '{}' not allowed", .{
8592 payload_ty.fmt(mod),
8675 payload_ty.fmt(pt),
85938676 });
85948677 } else if (payload_ty.zigTypeTag(mod) == .ErrorSet) {
85958678 return sema.fail(block, payload_src, "error union with payload of error set type '{}' not allowed", .{
8596 payload_ty.fmt(mod),
8679 payload_ty.fmt(pt),
85978680 });
85988681 }
85998682}
86008683
86018684fn zirErrorValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
86028685 _ = block;
8603 const mod = sema.mod;
8686 const pt = sema.pt;
86048687 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
8605 const name = try mod.intern_pool.getOrPutString(
8688 const name = try pt.zcu.intern_pool.getOrPutString(
86068689 sema.gpa,
86078690 inst_data.get(sema.code),
86088691 .no_embedded_nulls,
86098692 );
8610 _ = try mod.getErrorValue(name);
8693 _ = try pt.zcu.getErrorValue(name);
86118694 // Create an error set type with only this error value, and return the value.
8612 const error_set_type = try mod.singleErrorSetType(name);
8613 return Air.internedToRef((try mod.intern(.{ .err = .{
8695 const error_set_type = try pt.singleErrorSetType(name);
8696 return Air.internedToRef((try pt.intern(.{ .err = .{
86148697 .ty = error_set_type.toIntern(),
86158698 .name = name,
86168699 } })));
......@@ -8620,21 +8703,22 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86208703 const tracy = trace(@src());
86218704 defer tracy.end();
86228705
8623 const mod = sema.mod;
8706 const pt = sema.pt;
8707 const mod = pt.zcu;
86248708 const ip = &mod.intern_pool;
86258709 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
86268710 const src = block.nodeOffset(extra.node);
86278711 const operand_src = block.builtinCallArgSrc(extra.node, 0);
86288712 const uncasted_operand = try sema.resolveInst(extra.operand);
86298713 const operand = try sema.coerce(block, Type.anyerror, uncasted_operand, operand_src);
8630 const err_int_ty = try mod.errorIntType();
8714 const err_int_ty = try pt.errorIntType();
86318715
86328716 if (try sema.resolveValue(operand)) |val| {
86338717 if (val.isUndef(mod)) {
8634 return mod.undefRef(err_int_ty);
8718 return pt.undefRef(err_int_ty);
86358719 }
86368720 const err_name = ip.indexToKey(val.toIntern()).err.name;
8637 return Air.internedToRef((try mod.intValue(
8721 return Air.internedToRef((try pt.intValue(
86388722 err_int_ty,
86398723 try mod.getErrorValue(err_name),
86408724 )).toIntern());
......@@ -8646,10 +8730,10 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86468730 else => |err_set_ty_index| {
86478731 const names = ip.indexToKey(err_set_ty_index).error_set_type.names;
86488732 switch (names.len) {
8649 0 => return Air.internedToRef((try mod.intValue(err_int_ty, 0)).toIntern()),
8733 0 => return Air.internedToRef((try pt.intValue(err_int_ty, 0)).toIntern()),
86508734 1 => {
86518735 const int: Module.ErrorInt = @intCast(mod.global_error_set.getIndex(names.get(ip)[0]).?);
8652 return mod.intRef(err_int_ty, int);
8736 return pt.intRef(err_int_ty, int);
86538737 },
86548738 else => {},
86558739 }
......@@ -8664,19 +8748,20 @@ fn zirErrorFromInt(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86648748 const tracy = trace(@src());
86658749 defer tracy.end();
86668750
8667 const mod = sema.mod;
8751 const pt = sema.pt;
8752 const mod = pt.zcu;
86688753 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
86698754 const src = block.nodeOffset(extra.node);
86708755 const operand_src = block.builtinCallArgSrc(extra.node, 0);
86718756 const uncasted_operand = try sema.resolveInst(extra.operand);
8672 const err_int_ty = try mod.errorIntType();
8757 const err_int_ty = try pt.errorIntType();
86738758 const operand = try sema.coerce(block, err_int_ty, uncasted_operand, operand_src);
86748759
86758760 if (try sema.resolveDefinedValue(block, operand_src, operand)) |value| {
8676 const int = try sema.usizeCast(block, operand_src, try value.toUnsignedIntSema(mod));
8761 const int = try sema.usizeCast(block, operand_src, try value.toUnsignedIntSema(pt));
86778762 if (int > mod.global_error_set.count() or int == 0)
86788763 return sema.fail(block, operand_src, "integer value '{d}' represents no error", .{int});
8679 return Air.internedToRef((try mod.intern(.{ .err = .{
8764 return Air.internedToRef((try pt.intern(.{ .err = .{
86808765 .ty = .anyerror_type,
86818766 .name = mod.global_error_set.keys()[int],
86828767 } })));
......@@ -8684,7 +8769,7 @@ fn zirErrorFromInt(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86848769 try sema.requireRuntimeBlock(block, src, operand_src);
86858770 if (block.wantSafety()) {
86868771 const is_lt_len = try block.addUnOp(.cmp_lt_errors_len, operand);
8687 const zero_val = Air.internedToRef((try mod.intValue(err_int_ty, 0)).toIntern());
8772 const zero_val = Air.internedToRef((try pt.intValue(err_int_ty, 0)).toIntern());
86888773 const is_non_zero = try block.addBinOp(.cmp_neq, operand, zero_val);
86898774 const ok = try block.addBinOp(.bool_and, is_lt_len, is_non_zero);
86908775 try sema.addSafetyCheck(block, src, ok, .invalid_error_code);
......@@ -8702,7 +8787,8 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
87028787 const tracy = trace(@src());
87038788 defer tracy.end();
87048789
8705 const mod = sema.mod;
8790 const pt = sema.pt;
8791 const mod = pt.zcu;
87068792 const ip = &mod.intern_pool;
87078793 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
87088794 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -8723,9 +8809,9 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
87238809 const lhs_ty = try sema.analyzeAsType(block, lhs_src, lhs);
87248810 const rhs_ty = try sema.analyzeAsType(block, rhs_src, rhs);
87258811 if (lhs_ty.zigTypeTag(mod) != .ErrorSet)
8726 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{lhs_ty.fmt(mod)});
8812 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{lhs_ty.fmt(pt)});
87278813 if (rhs_ty.zigTypeTag(mod) != .ErrorSet)
8728 return sema.fail(block, rhs_src, "expected error set type, found '{}'", .{rhs_ty.fmt(mod)});
8814 return sema.fail(block, rhs_src, "expected error set type, found '{}'", .{rhs_ty.fmt(pt)});
87298815
87308816 // Anything merged with anyerror is anyerror.
87318817 if (lhs_ty.toIntern() == .anyerror_type or rhs_ty.toIntern() == .anyerror_type) {
......@@ -8758,16 +8844,18 @@ fn zirEnumLiteral(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87588844 const tracy = trace(@src());
87598845 defer tracy.end();
87608846
8761 const mod = sema.mod;
8847 const pt = sema.pt;
8848 const mod = pt.zcu;
87628849 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
87638850 const name = inst_data.get(sema.code);
8764 return Air.internedToRef((try mod.intern(.{
8851 return Air.internedToRef((try pt.intern(.{
87658852 .enum_literal = try mod.intern_pool.getOrPutString(sema.gpa, name, .no_embedded_nulls),
87668853 })));
87678854}
87688855
87698856fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8770 const mod = sema.mod;
8857 const pt = sema.pt;
8858 const mod = pt.zcu;
87718859 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
87728860 const src = block.nodeOffset(inst_data.src_node);
87738861 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -8777,7 +8865,7 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87778865 const enum_tag: Air.Inst.Ref = switch (operand_ty.zigTypeTag(mod)) {
87788866 .Enum => operand,
87798867 .Union => blk: {
8780 try operand_ty.resolveFields(mod);
8868 try operand_ty.resolveFields(pt);
87818869 const tag_ty = operand_ty.unionTagType(mod) orelse {
87828870 return sema.fail(
87838871 block,
......@@ -8791,7 +8879,7 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87918879 },
87928880 else => {
87938881 return sema.fail(block, operand_src, "expected enum or tagged union, found '{}'", .{
8794 operand_ty.fmt(mod),
8882 operand_ty.fmt(pt),
87958883 });
87968884 },
87978885 };
......@@ -8802,20 +8890,20 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88028890 // https://github.com/ziglang/zig/issues/15909
88038891 if (enum_tag_ty.enumFieldCount(mod) == 0 and !enum_tag_ty.isNonexhaustiveEnum(mod)) {
88048892 return sema.fail(block, operand_src, "cannot use @intFromEnum on empty enum '{}'", .{
8805 enum_tag_ty.fmt(mod),
8893 enum_tag_ty.fmt(pt),
88068894 });
88078895 }
88088896
88098897 if (try sema.typeHasOnePossibleValue(enum_tag_ty)) |opv| {
8810 return Air.internedToRef((try mod.getCoerced(opv, int_tag_ty)).toIntern());
8898 return Air.internedToRef((try pt.getCoerced(opv, int_tag_ty)).toIntern());
88118899 }
88128900
88138901 if (try sema.resolveValue(enum_tag)) |enum_tag_val| {
88148902 if (enum_tag_val.isUndef(mod)) {
8815 return mod.undefRef(int_tag_ty);
8903 return pt.undefRef(int_tag_ty);
88168904 }
88178905
8818 const val = try enum_tag_val.intFromEnum(enum_tag_ty, mod);
8906 const val = try enum_tag_val.intFromEnum(enum_tag_ty, pt);
88198907 return Air.internedToRef(val.toIntern());
88208908 }
88218909
......@@ -8824,7 +8912,8 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88248912}
88258913
88268914fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8827 const mod = sema.mod;
8915 const pt = sema.pt;
8916 const mod = pt.zcu;
88288917 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
88298918 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
88308919 const src = block.nodeOffset(inst_data.src_node);
......@@ -8833,7 +8922,7 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88338922 const operand = try sema.resolveInst(extra.rhs);
88348923
88358924 if (dest_ty.zigTypeTag(mod) != .Enum) {
8836 return sema.fail(block, src, "expected enum, found '{}'", .{dest_ty.fmt(mod)});
8925 return sema.fail(block, src, "expected enum, found '{}'", .{dest_ty.fmt(pt)});
88378926 }
88388927 _ = try sema.checkIntType(block, operand_src, sema.typeOf(operand));
88398928
......@@ -8841,10 +8930,10 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88418930 if (dest_ty.isNonexhaustiveEnum(mod)) {
88428931 const int_tag_ty = dest_ty.intTagType(mod);
88438932 if (try sema.intFitsInType(int_val, int_tag_ty, null)) {
8844 return Air.internedToRef((try mod.getCoerced(int_val, dest_ty)).toIntern());
8933 return Air.internedToRef((try pt.getCoerced(int_val, dest_ty)).toIntern());
88458934 }
88468935 return sema.fail(block, src, "int value '{}' out of range of non-exhaustive enum '{}'", .{
8847 int_val.fmtValue(mod, sema), dest_ty.fmt(mod),
8936 int_val.fmtValue(pt, sema), dest_ty.fmt(pt),
88488937 });
88498938 }
88508939 if (int_val.isUndef(mod)) {
......@@ -8852,10 +8941,10 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88528941 }
88538942 if (!(try sema.enumHasInt(dest_ty, int_val))) {
88548943 return sema.fail(block, src, "enum '{}' has no tag with value '{}'", .{
8855 dest_ty.fmt(mod), int_val.fmtValue(mod, sema),
8944 dest_ty.fmt(pt), int_val.fmtValue(pt, sema),
88568945 });
88578946 }
8858 return Air.internedToRef((try mod.getCoerced(int_val, dest_ty)).toIntern());
8947 return Air.internedToRef((try pt.getCoerced(int_val, dest_ty)).toIntern());
88598948 }
88608949
88618950 if (dest_ty.intTagType(mod).zigTypeTag(mod) == .ComptimeInt) {
......@@ -8909,7 +8998,8 @@ fn analyzeOptionalPayloadPtr(
89098998 safety_check: bool,
89108999 initializing: bool,
89119000) CompileError!Air.Inst.Ref {
8912 const zcu = sema.mod;
9001 const pt = sema.pt;
9002 const zcu = pt.zcu;
89139003 const optional_ptr_ty = sema.typeOf(optional_ptr);
89149004 assert(optional_ptr_ty.zigTypeTag(zcu) == .Pointer);
89159005
......@@ -8919,7 +9009,7 @@ fn analyzeOptionalPayloadPtr(
89199009 }
89209010
89219011 const child_type = opt_type.optionalChild(zcu);
8922 const child_pointer = try zcu.ptrTypeSema(.{
9012 const child_pointer = try pt.ptrTypeSema(.{
89239013 .child = child_type.toIntern(),
89249014 .flags = .{
89259015 .is_const = optional_ptr_ty.isConstPtr(zcu),
......@@ -8932,8 +9022,8 @@ fn analyzeOptionalPayloadPtr(
89329022 if (sema.isComptimeMutablePtr(ptr_val)) {
89339023 // Set the optional to non-null at comptime.
89349024 // If the payload is OPV, we must use that value instead of undef.
8935 const payload_val = try sema.typeHasOnePossibleValue(child_type) orelse try zcu.undefValue(child_type);
8936 const opt_val = try zcu.intern(.{ .opt = .{
9025 const payload_val = try sema.typeHasOnePossibleValue(child_type) orelse try pt.undefValue(child_type);
9026 const opt_val = try pt.intern(.{ .opt = .{
89379027 .ty = opt_type.toIntern(),
89389028 .val = payload_val.toIntern(),
89399029 } });
......@@ -8943,13 +9033,13 @@ fn analyzeOptionalPayloadPtr(
89439033 const opt_payload_ptr = try block.addTyOp(.optional_payload_ptr_set, child_pointer, optional_ptr);
89449034 try sema.checkKnownAllocPtr(block, optional_ptr, opt_payload_ptr);
89459035 }
8946 return Air.internedToRef((try ptr_val.ptrOptPayload(zcu)).toIntern());
9036 return Air.internedToRef((try ptr_val.ptrOptPayload(pt)).toIntern());
89479037 }
89489038 if (try sema.pointerDeref(block, src, ptr_val, optional_ptr_ty)) |val| {
89499039 if (val.isNull(zcu)) {
89509040 return sema.fail(block, src, "unable to unwrap null", .{});
89519041 }
8952 return Air.internedToRef((try ptr_val.ptrOptPayload(zcu)).toIntern());
9042 return Air.internedToRef((try ptr_val.ptrOptPayload(pt)).toIntern());
89539043 }
89549044 }
89559045
......@@ -8978,7 +9068,8 @@ fn zirOptionalPayload(
89789068 const tracy = trace(@src());
89799069 defer tracy.end();
89809070
8981 const mod = sema.mod;
9071 const pt = sema.pt;
9072 const mod = pt.zcu;
89829073 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
89839074 const src = block.nodeOffset(inst_data.src_node);
89849075 const operand = try sema.resolveInst(inst_data.operand);
......@@ -8992,7 +9083,7 @@ fn zirOptionalPayload(
89929083 // TODO https://github.com/ziglang/zig/issues/6597
89939084 if (true) break :t operand_ty;
89949085 const ptr_info = operand_ty.ptrInfo(mod);
8995 break :t try mod.ptrTypeSema(.{
9086 break :t try pt.ptrTypeSema(.{
89969087 .child = ptr_info.child,
89979088 .flags = .{
89989089 .alignment = ptr_info.flags.alignment,
......@@ -9030,7 +9121,8 @@ fn zirErrUnionPayload(
90309121 const tracy = trace(@src());
90319122 defer tracy.end();
90329123
9033 const mod = sema.mod;
9124 const pt = sema.pt;
9125 const mod = pt.zcu;
90349126 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
90359127 const src = block.nodeOffset(inst_data.src_node);
90369128 const operand = try sema.resolveInst(inst_data.operand);
......@@ -9038,7 +9130,7 @@ fn zirErrUnionPayload(
90389130 const err_union_ty = sema.typeOf(operand);
90399131 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
90409132 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
9041 err_union_ty.fmt(mod),
9133 err_union_ty.fmt(pt),
90429134 });
90439135 }
90449136 return sema.analyzeErrUnionPayload(block, src, err_union_ty, operand, operand_src, false);
......@@ -9053,7 +9145,8 @@ fn analyzeErrUnionPayload(
90539145 operand_src: LazySrcLoc,
90549146 safety_check: bool,
90559147) CompileError!Air.Inst.Ref {
9056 const mod = sema.mod;
9148 const pt = sema.pt;
9149 const mod = pt.zcu;
90579150 const payload_ty = err_union_ty.errorUnionPayload(mod);
90589151 if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
90599152 if (val.getErrorName(mod).unwrap()) |name| {
......@@ -9098,19 +9191,20 @@ fn analyzeErrUnionPayloadPtr(
90989191 safety_check: bool,
90999192 initializing: bool,
91009193) CompileError!Air.Inst.Ref {
9101 const zcu = sema.mod;
9194 const pt = sema.pt;
9195 const zcu = pt.zcu;
91029196 const operand_ty = sema.typeOf(operand);
91039197 assert(operand_ty.zigTypeTag(zcu) == .Pointer);
91049198
91059199 if (operand_ty.childType(zcu).zigTypeTag(zcu) != .ErrorUnion) {
91069200 return sema.fail(block, src, "expected error union type, found '{}'", .{
9107 operand_ty.childType(zcu).fmt(zcu),
9201 operand_ty.childType(zcu).fmt(pt),
91089202 });
91099203 }
91109204
91119205 const err_union_ty = operand_ty.childType(zcu);
91129206 const payload_ty = err_union_ty.errorUnionPayload(zcu);
9113 const operand_pointer_ty = try zcu.ptrTypeSema(.{
9207 const operand_pointer_ty = try pt.ptrTypeSema(.{
91149208 .child = payload_ty.toIntern(),
91159209 .flags = .{
91169210 .is_const = operand_ty.isConstPtr(zcu),
......@@ -9123,8 +9217,8 @@ fn analyzeErrUnionPayloadPtr(
91239217 if (sema.isComptimeMutablePtr(ptr_val)) {
91249218 // Set the error union to non-error at comptime.
91259219 // If the payload is OPV, we must use that value instead of undef.
9126 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
9127 const eu_val = try zcu.intern(.{ .error_union = .{
9220 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
9221 const eu_val = try pt.intern(.{ .error_union = .{
91289222 .ty = err_union_ty.toIntern(),
91299223 .val = .{ .payload = payload_val.toIntern() },
91309224 } });
......@@ -9135,13 +9229,13 @@ fn analyzeErrUnionPayloadPtr(
91359229 const eu_payload_ptr = try block.addTyOp(.errunion_payload_ptr_set, operand_pointer_ty, operand);
91369230 try sema.checkKnownAllocPtr(block, operand, eu_payload_ptr);
91379231 }
9138 return Air.internedToRef((try ptr_val.ptrEuPayload(zcu)).toIntern());
9232 return Air.internedToRef((try ptr_val.ptrEuPayload(pt)).toIntern());
91399233 }
91409234 if (try sema.pointerDeref(block, src, ptr_val, operand_ty)) |val| {
91419235 if (val.getErrorName(zcu).unwrap()) |name| {
91429236 return sema.failWithComptimeErrorRetTrace(block, src, name);
91439237 }
9144 return Air.internedToRef((try ptr_val.ptrEuPayload(zcu)).toIntern());
9238 return Air.internedToRef((try ptr_val.ptrEuPayload(pt)).toIntern());
91459239 }
91469240 }
91479241
......@@ -9175,18 +9269,19 @@ fn zirErrUnionCode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
91759269}
91769270
91779271fn analyzeErrUnionCode(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref) CompileError!Air.Inst.Ref {
9178 const mod = sema.mod;
9272 const pt = sema.pt;
9273 const mod = pt.zcu;
91799274 const operand_ty = sema.typeOf(operand);
91809275 if (operand_ty.zigTypeTag(mod) != .ErrorUnion) {
91819276 return sema.fail(block, src, "expected error union type, found '{}'", .{
9182 operand_ty.fmt(mod),
9277 operand_ty.fmt(pt),
91839278 });
91849279 }
91859280
91869281 const result_ty = operand_ty.errorUnionSet(mod);
91879282
91889283 if (try sema.resolveDefinedValue(block, src, operand)) |val| {
9189 return Air.internedToRef((try mod.intern(.{ .err = .{
9284 return Air.internedToRef((try pt.intern(.{ .err = .{
91909285 .ty = result_ty.toIntern(),
91919286 .name = mod.intern_pool.indexToKey(val.toIntern()).error_union.val.err_name,
91929287 } })));
......@@ -9208,13 +9303,14 @@ fn zirErrUnionCodePtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
92089303}
92099304
92109305fn analyzeErrUnionCodePtr(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref) CompileError!Air.Inst.Ref {
9211 const mod = sema.mod;
9306 const pt = sema.pt;
9307 const mod = pt.zcu;
92129308 const operand_ty = sema.typeOf(operand);
92139309 assert(operand_ty.zigTypeTag(mod) == .Pointer);
92149310
92159311 if (operand_ty.childType(mod).zigTypeTag(mod) != .ErrorUnion) {
92169312 return sema.fail(block, src, "expected error union type, found '{}'", .{
9217 operand_ty.childType(mod).fmt(mod),
9313 operand_ty.childType(mod).fmt(pt),
92189314 });
92199315 }
92209316
......@@ -9223,7 +9319,7 @@ fn analyzeErrUnionCodePtr(sema: *Sema, block: *Block, src: LazySrcLoc, operand:
92239319 if (try sema.resolveDefinedValue(block, src, operand)) |pointer_val| {
92249320 if (try sema.pointerDeref(block, src, pointer_val, operand_ty)) |val| {
92259321 assert(val.getErrorName(mod) != .none);
9226 return Air.internedToRef((try mod.intern(.{ .err = .{
9322 return Air.internedToRef((try pt.intern(.{ .err = .{
92279323 .ty = result_ty.toIntern(),
92289324 .name = mod.intern_pool.indexToKey(val.toIntern()).error_union.val.err_name,
92299325 } })));
......@@ -9240,10 +9336,11 @@ fn zirFunc(
92409336 inst: Zir.Inst.Index,
92419337 inferred_error_set: bool,
92429338) CompileError!Air.Inst.Ref {
9243 const mod = sema.mod;
9339 const pt = sema.pt;
9340 const mod = pt.zcu;
92449341 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
92459342 const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
9246 const target = sema.mod.getTarget();
9343 const target = mod.getTarget();
92479344 const ret_ty_src = block.src(.{ .node_offset_fn_type_ret_ty = inst_data.src_node });
92489345
92499346 var extra_index = extra.end;
......@@ -9372,7 +9469,8 @@ fn handleExternLibName(
93729469 lib_name: []const u8,
93739470) CompileError!void {
93749471 blk: {
9375 const mod = sema.mod;
9472 const pt = sema.pt;
9473 const mod = pt.zcu;
93769474 const comp = mod.comp;
93779475 const target = mod.getTarget();
93789476 log.debug("extern fn symbol expected in lib '{s}'", .{lib_name});
......@@ -9485,7 +9583,8 @@ fn funcCommon(
94859583 noalias_bits: u32,
94869584 is_noinline: bool,
94879585) CompileError!Air.Inst.Ref {
9488 const mod = sema.mod;
9586 const pt = sema.pt;
9587 const mod = pt.zcu;
94899588 const gpa = sema.gpa;
94909589 const target = mod.getTarget();
94919590 const ip = &mod.intern_pool;
......@@ -9539,13 +9638,13 @@ fn funcCommon(
95399638 if (!param_ty.isValidParamType(mod)) {
95409639 const opaque_str = if (param_ty.zigTypeTag(mod) == .Opaque) "opaque " else "";
95419640 return sema.fail(block, param_src, "parameter of {s}type '{}' not allowed", .{
9542 opaque_str, param_ty.fmt(mod),
9641 opaque_str, param_ty.fmt(pt),
95439642 });
95449643 }
95459644 if (!this_generic and !target_util.fnCallConvAllowsZigTypes(target, cc_resolved) and !try sema.validateExternType(param_ty, .param_ty)) {
95469645 const msg = msg: {
95479646 const msg = try sema.errMsg(param_src, "parameter of type '{}' not allowed in function with calling convention '{s}'", .{
9548 param_ty.fmt(mod), @tagName(cc_resolved),
9647 param_ty.fmt(pt), @tagName(cc_resolved),
95499648 });
95509649 errdefer msg.destroy(sema.gpa);
95519650
......@@ -9559,7 +9658,7 @@ fn funcCommon(
95599658 if (is_source_decl and requires_comptime and !param_is_comptime and has_body and !block.is_comptime) {
95609659 const msg = msg: {
95619660 const msg = try sema.errMsg(param_src, "parameter of type '{}' must be declared comptime", .{
9562 param_ty.fmt(mod),
9661 param_ty.fmt(pt),
95639662 });
95649663 errdefer msg.destroy(sema.gpa);
95659664
......@@ -9580,7 +9679,7 @@ fn funcCommon(
95809679 const err_code_size = target.ptrBitWidth();
95819680 switch (i) {
95829681 0 => if (param_ty.zigTypeTag(mod) != .Pointer) return sema.fail(block, param_src, "first parameter of function with 'Interrupt' calling convention must be a pointer type", .{}),
9583 1 => if (param_ty.bitSize(mod) != err_code_size) return sema.fail(block, param_src, "second parameter of function with 'Interrupt' calling convention must be a {d}-bit integer", .{err_code_size}),
9682 1 => if (param_ty.bitSize(pt) != err_code_size) return sema.fail(block, param_src, "second parameter of function with 'Interrupt' calling convention must be a {d}-bit integer", .{err_code_size}),
95849683 else => return sema.fail(block, param_src, "'Interrupt' calling convention supports up to 2 parameters, found {d}", .{i + 1}),
95859684 }
95869685 } else return sema.fail(block, param_src, "parameters are not allowed with 'Interrupt' calling convention", .{}),
......@@ -9606,7 +9705,7 @@ fn funcCommon(
96069705 if (inferred_error_set) {
96079706 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
96089707 }
9609 const func_index = try ip.getFuncInstance(gpa, .{
9708 const func_index = try ip.getFuncInstance(gpa, pt.tid, .{
96109709 .param_types = param_types,
96119710 .noalias_bits = noalias_bits,
96129711 .bare_return_type = bare_return_type.toIntern(),
......@@ -9655,7 +9754,7 @@ fn funcCommon(
96559754 assert(has_body);
96569755 if (!ret_poison)
96579756 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
9658 const func_index = try ip.getFuncDeclIes(gpa, .{
9757 const func_index = try ip.getFuncDeclIes(gpa, pt.tid, .{
96599758 .owner_decl = sema.owner_decl_index,
96609759
96619760 .param_types = param_types,
......@@ -9695,7 +9794,7 @@ fn funcCommon(
96959794 );
96969795 }
96979796
9698 const func_ty = try ip.getFuncType(gpa, .{
9797 const func_ty = try ip.getFuncType(gpa, pt.tid, .{
96999798 .param_types = param_types,
97009799 .noalias_bits = noalias_bits,
97019800 .comptime_bits = comptime_bits,
......@@ -9718,7 +9817,7 @@ fn funcCommon(
97189817 if (opt_lib_name) |lib_name| try sema.handleExternLibName(block, block.src(.{
97199818 .node_offset_lib_name = src_node_offset,
97209819 }), lib_name);
9721 const func_index = try ip.getExternFunc(gpa, .{
9820 const func_index = try ip.getExternFunc(gpa, pt.tid, .{
97229821 .ty = func_ty,
97239822 .decl = sema.owner_decl_index,
97249823 .lib_name = try mod.intern_pool.getOrPutStringOpt(gpa, opt_lib_name, .no_embedded_nulls),
......@@ -9743,7 +9842,7 @@ fn funcCommon(
97439842 }
97449843
97459844 if (has_body) {
9746 const func_index = try ip.getFuncDecl(gpa, .{
9845 const func_index = try ip.getFuncDecl(gpa, pt.tid, .{
97479846 .owner_decl = sema.owner_decl_index,
97489847 .ty = func_ty,
97499848 .cc = cc,
......@@ -9809,7 +9908,8 @@ fn finishFunc(
98099908 is_generic: bool,
98109909 final_is_generic: bool,
98119910) CompileError!Air.Inst.Ref {
9812 const mod = sema.mod;
9911 const pt = sema.pt;
9912 const mod = pt.zcu;
98139913 const ip = &mod.intern_pool;
98149914 const gpa = sema.gpa;
98159915 const target = mod.getTarget();
......@@ -9822,7 +9922,7 @@ fn finishFunc(
98229922 if (!return_type.isValidReturnType(mod)) {
98239923 const opaque_str = if (return_type.zigTypeTag(mod) == .Opaque) "opaque " else "";
98249924 return sema.fail(block, ret_ty_src, "{s}return type '{}' not allowed", .{
9825 opaque_str, return_type.fmt(mod),
9925 opaque_str, return_type.fmt(pt),
98269926 });
98279927 }
98289928 if (!ret_poison and !target_util.fnCallConvAllowsZigTypes(target, cc_resolved) and
......@@ -9830,7 +9930,7 @@ fn finishFunc(
98309930 {
98319931 const msg = msg: {
98329932 const msg = try sema.errMsg(ret_ty_src, "return type '{}' not allowed in function with calling convention '{s}'", .{
9833 return_type.fmt(mod), @tagName(cc_resolved),
9933 return_type.fmt(pt), @tagName(cc_resolved),
98349934 });
98359935 errdefer msg.destroy(gpa);
98369936
......@@ -9852,7 +9952,7 @@ fn finishFunc(
98529952 const msg = try sema.errMsg(
98539953 ret_ty_src,
98549954 "function with comptime-only return type '{}' requires all parameters to be comptime",
9855 .{return_type.fmt(mod)},
9955 .{return_type.fmt(pt)},
98569956 );
98579957 try sema.explainWhyTypeIsComptime(msg, ret_ty_src, return_type);
98589958
......@@ -9938,8 +10038,8 @@ fn finishFunc(
993810038 if (!final_is_generic and sema.wantErrorReturnTracing(return_type)) {
993910039 // Make sure that StackTrace's fields are resolved so that the backend can
994010040 // lower this fn type.
9941 const unresolved_stack_trace_ty = try mod.getBuiltinType("StackTrace");
9942 try unresolved_stack_trace_ty.resolveFields(mod);
10041 const unresolved_stack_trace_ty = try pt.getBuiltinType("StackTrace");
10042 try unresolved_stack_trace_ty.resolveFields(pt);
994310043 }
994410044
994510045 return Air.internedToRef(if (opt_func_index != .none) opt_func_index else func_ty);
......@@ -10068,7 +10168,8 @@ fn analyzeAs(
1006810168 zir_operand: Zir.Inst.Ref,
1006910169 no_cast_to_comptime_int: bool,
1007010170) CompileError!Air.Inst.Ref {
10071 const mod = sema.mod;
10171 const pt = sema.pt;
10172 const mod = pt.zcu;
1007210173 const operand = try sema.resolveInst(zir_operand);
1007310174 const operand_air_inst = sema.resolveInst(zir_dest_type) catch |err| switch (err) {
1007410175 error.GenericPoison => return operand,
......@@ -10098,7 +10199,8 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1009810199 const tracy = trace(@src());
1009910200 defer tracy.end();
1010010201
10101 const zcu = sema.mod;
10202 const pt = sema.pt;
10203 const zcu = pt.zcu;
1010210204 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1010310205 const ptr_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1010410206 const operand = try sema.resolveInst(inst_data.operand);
......@@ -10106,12 +10208,12 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1010610208 const ptr_ty = operand_ty.scalarType(zcu);
1010710209 const is_vector = operand_ty.zigTypeTag(zcu) == .Vector;
1010810210 if (!ptr_ty.isPtrAtRuntime(zcu)) {
10109 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(zcu)});
10211 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(pt)});
1011010212 }
1011110213 const pointee_ty = ptr_ty.childType(zcu);
1011210214 if (try sema.typeRequiresComptime(ptr_ty)) {
1011310215 const msg = msg: {
10114 const msg = try sema.errMsg(ptr_src, "comptime-only type '{}' has no pointer address", .{pointee_ty.fmt(zcu)});
10216 const msg = try sema.errMsg(ptr_src, "comptime-only type '{}' has no pointer address", .{pointee_ty.fmt(pt)});
1011510217 errdefer msg.destroy(sema.gpa);
1011610218 try sema.explainWhyTypeIsComptime(msg, ptr_src, pointee_ty);
1011710219 break :msg msg;
......@@ -10121,32 +10223,32 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1012110223 if (try sema.resolveValueIntable(operand)) |operand_val| ct: {
1012210224 if (!is_vector) {
1012310225 if (operand_val.isUndef(zcu)) {
10124 return Air.internedToRef((try zcu.undefValue(Type.usize)).toIntern());
10226 return Air.internedToRef((try pt.undefValue(Type.usize)).toIntern());
1012510227 }
10126 return Air.internedToRef((try zcu.intValue(
10228 return Air.internedToRef((try pt.intValue(
1012710229 Type.usize,
10128 (try operand_val.getUnsignedIntAdvanced(zcu, .sema)).?,
10230 (try operand_val.getUnsignedIntAdvanced(pt, .sema)).?,
1012910231 )).toIntern());
1013010232 }
1013110233 const len = operand_ty.vectorLen(zcu);
10132 const dest_ty = try zcu.vectorType(.{ .child = .usize_type, .len = len });
10234 const dest_ty = try pt.vectorType(.{ .child = .usize_type, .len = len });
1013310235 const new_elems = try sema.arena.alloc(InternPool.Index, len);
1013410236 for (new_elems, 0..) |*new_elem, i| {
10135 const ptr_val = try operand_val.elemValue(zcu, i);
10237 const ptr_val = try operand_val.elemValue(pt, i);
1013610238 if (ptr_val.isUndef(zcu)) {
10137 new_elem.* = (try zcu.undefValue(Type.usize)).toIntern();
10239 new_elem.* = (try pt.undefValue(Type.usize)).toIntern();
1013810240 continue;
1013910241 }
10140 const addr = try ptr_val.getUnsignedIntAdvanced(zcu, .sema) orelse {
10242 const addr = try ptr_val.getUnsignedIntAdvanced(pt, .sema) orelse {
1014110243 // A vector element wasn't an integer pointer. This is a runtime operation.
1014210244 break :ct;
1014310245 };
10144 new_elem.* = (try zcu.intValue(
10246 new_elem.* = (try pt.intValue(
1014510247 Type.usize,
1014610248 addr,
1014710249 )).toIntern();
1014810250 }
10149 return Air.internedToRef(try zcu.intern(.{ .aggregate = .{
10251 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
1015010252 .ty = dest_ty.toIntern(),
1015110253 .storage = .{ .elems = new_elems },
1015210254 } }));
......@@ -10157,10 +10259,10 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1015710259 return block.addUnOp(.int_from_ptr, operand);
1015810260 }
1015910261 const len = operand_ty.vectorLen(zcu);
10160 const dest_ty = try zcu.vectorType(.{ .child = .usize_type, .len = len });
10262 const dest_ty = try pt.vectorType(.{ .child = .usize_type, .len = len });
1016110263 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
1016210264 for (new_elems, 0..) |*new_elem, i| {
10163 const idx_ref = try zcu.intRef(Type.usize, i);
10265 const idx_ref = try pt.intRef(Type.usize, i);
1016410266 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
1016510267 new_elem.* = try block.addUnOp(.int_from_ptr, old_elem);
1016610268 }
......@@ -10171,7 +10273,8 @@ fn zirFieldVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1017110273 const tracy = trace(@src());
1017210274 defer tracy.end();
1017310275
10174 const mod = sema.mod;
10276 const pt = sema.pt;
10277 const mod = pt.zcu;
1017510278 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1017610279 const src = block.nodeOffset(inst_data.src_node);
1017710280 const field_name_src = block.src(.{ .node_offset_field_name = inst_data.src_node });
......@@ -10189,7 +10292,8 @@ fn zirFieldPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1018910292 const tracy = trace(@src());
1019010293 defer tracy.end();
1019110294
10192 const mod = sema.mod;
10295 const pt = sema.pt;
10296 const mod = pt.zcu;
1019310297 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1019410298 const src = block.nodeOffset(inst_data.src_node);
1019510299 const field_name_src = block.src(.{ .node_offset_field_name = inst_data.src_node });
......@@ -10207,7 +10311,8 @@ fn zirStructInitFieldPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compi
1020710311 const tracy = trace(@src());
1020810312 defer tracy.end();
1020910313
10210 const mod = sema.mod;
10314 const pt = sema.pt;
10315 const mod = pt.zcu;
1021110316 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1021210317 const src = block.nodeOffset(inst_data.src_node);
1021310318 const field_name_src = block.src(.{ .node_offset_field_name_init = inst_data.src_node });
......@@ -10284,7 +10389,8 @@ fn intCast(
1028410389 operand_src: LazySrcLoc,
1028510390 runtime_safety: bool,
1028610391) CompileError!Air.Inst.Ref {
10287 const mod = sema.mod;
10392 const pt = sema.pt;
10393 const mod = pt.zcu;
1028810394 const operand_ty = sema.typeOf(operand);
1028910395 const dest_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, dest_ty, dest_ty_src);
1029010396 const operand_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, operand_ty, operand_src);
......@@ -10307,7 +10413,7 @@ fn intCast(
1030710413
1030810414 if (wanted_bits == 0) {
1030910415 const ok = if (is_vector) ok: {
10310 const zeros = try sema.splat(operand_ty, try mod.intValue(operand_scalar_ty, 0));
10416 const zeros = try sema.splat(operand_ty, try pt.intValue(operand_scalar_ty, 0));
1031110417 const zero_inst = Air.internedToRef(zeros.toIntern());
1031210418 const is_in_range = try block.addCmpVector(operand, zero_inst, .eq);
1031310419 const all_in_range = try block.addInst(.{
......@@ -10316,7 +10422,7 @@ fn intCast(
1031610422 });
1031710423 break :ok all_in_range;
1031810424 } else ok: {
10319 const zero_inst = Air.internedToRef((try mod.intValue(operand_ty, 0)).toIntern());
10425 const zero_inst = Air.internedToRef((try pt.intValue(operand_ty, 0)).toIntern());
1032010426 const is_in_range = try block.addBinOp(.cmp_lte, operand, zero_inst);
1032110427 break :ok is_in_range;
1032210428 };
......@@ -10339,7 +10445,7 @@ fn intCast(
1033910445 // range shrinkage
1034010446 // requirement: int value fits into target type
1034110447 if (wanted_value_bits < actual_value_bits) {
10342 const dest_max_val_scalar = try dest_scalar_ty.maxIntScalar(mod, operand_scalar_ty);
10448 const dest_max_val_scalar = try dest_scalar_ty.maxIntScalar(pt, operand_scalar_ty);
1034310449 const dest_max_val = try sema.splat(operand_ty, dest_max_val_scalar);
1034410450 const dest_max = Air.internedToRef(dest_max_val.toIntern());
1034510451
......@@ -10348,8 +10454,8 @@ fn intCast(
1034810454
1034910455 // Reinterpret the sign-bit as part of the value. This will make
1035010456 // negative differences (`operand` > `dest_max`) appear too big.
10351 const unsigned_scalar_operand_ty = try mod.intType(.unsigned, actual_bits);
10352 const unsigned_operand_ty = if (is_vector) try mod.vectorType(.{
10457 const unsigned_scalar_operand_ty = try pt.intType(.unsigned, actual_bits);
10458 const unsigned_operand_ty = if (is_vector) try pt.vectorType(.{
1035310459 .len = dest_ty.vectorLen(mod),
1035410460 .child = unsigned_scalar_operand_ty.toIntern(),
1035510461 }) else unsigned_scalar_operand_ty;
......@@ -10358,14 +10464,14 @@ fn intCast(
1035810464 // If the destination type is signed, then we need to double its
1035910465 // range to account for negative values.
1036010466 const dest_range_val = if (wanted_info.signedness == .signed) range_val: {
10361 const one_scalar = try mod.intValue(unsigned_scalar_operand_ty, 1);
10362 const one = if (is_vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
10467 const one_scalar = try pt.intValue(unsigned_scalar_operand_ty, 1);
10468 const one = if (is_vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
1036310469 .ty = unsigned_operand_ty.toIntern(),
1036410470 .storage = .{ .repeated_elem = one_scalar.toIntern() },
10365 } }))) else one_scalar;
10366 const range_minus_one = try dest_max_val.shl(one, unsigned_operand_ty, sema.arena, mod);
10471 } })) else one_scalar;
10472 const range_minus_one = try dest_max_val.shl(one, unsigned_operand_ty, sema.arena, pt);
1036710473 break :range_val try sema.intAdd(range_minus_one, one, unsigned_operand_ty, undefined);
10368 } else try mod.getCoerced(dest_max_val, unsigned_operand_ty);
10474 } else try pt.getCoerced(dest_max_val, unsigned_operand_ty);
1036910475 const dest_range = Air.internedToRef(dest_range_val.toIntern());
1037010476
1037110477 const ok = if (is_vector) ok: {
......@@ -10405,7 +10511,7 @@ fn intCast(
1040510511 // no shrinkage, yes sign loss
1040610512 // requirement: signed to unsigned >= 0
1040710513 const ok = if (is_vector) ok: {
10408 const scalar_zero = try mod.intValue(operand_scalar_ty, 0);
10514 const scalar_zero = try pt.intValue(operand_scalar_ty, 0);
1040910515 const zero_val = try sema.splat(operand_ty, scalar_zero);
1041010516 const zero_inst = Air.internedToRef(zero_val.toIntern());
1041110517 const is_in_range = try block.addCmpVector(operand, zero_inst, .gte);
......@@ -10418,7 +10524,7 @@ fn intCast(
1041810524 });
1041910525 break :ok all_in_range;
1042010526 } else ok: {
10421 const zero_inst = Air.internedToRef((try mod.intValue(operand_ty, 0)).toIntern());
10527 const zero_inst = Air.internedToRef((try pt.intValue(operand_ty, 0)).toIntern());
1042210528 const is_in_range = try block.addBinOp(.cmp_gte, operand, zero_inst);
1042310529 break :ok is_in_range;
1042410530 };
......@@ -10432,7 +10538,8 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1043210538 const tracy = trace(@src());
1043310539 defer tracy.end();
1043410540
10435 const mod = sema.mod;
10541 const pt = sema.pt;
10542 const mod = pt.zcu;
1043610543 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1043710544 const src = block.nodeOffset(inst_data.src_node);
1043810545 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -10457,14 +10564,14 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1045710564 .Type,
1045810565 .Undefined,
1045910566 .Void,
10460 => return sema.fail(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)}),
10567 => return sema.fail(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)}),
1046110568
1046210569 .Enum => {
1046310570 const msg = msg: {
10464 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
10571 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)});
1046510572 errdefer msg.destroy(sema.gpa);
1046610573 switch (operand_ty.zigTypeTag(mod)) {
10467 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
10574 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(pt)}),
1046810575 else => {},
1046910576 }
1047010577
......@@ -10475,11 +10582,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1047510582
1047610583 .Pointer => {
1047710584 const msg = msg: {
10478 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
10585 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)});
1047910586 errdefer msg.destroy(sema.gpa);
1048010587 switch (operand_ty.zigTypeTag(mod)) {
10481 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
10482 .Pointer => try sema.errNote(src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(mod)}),
10588 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(pt)}),
10589 .Pointer => try sema.errNote(src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(pt)}),
1048310590 else => {},
1048410591 }
1048510592
......@@ -10494,7 +10601,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1049410601 else => unreachable,
1049510602 };
1049610603 return sema.fail(block, src, "cannot @bitCast to '{}'; {s} does not have a guaranteed in-memory layout", .{
10497 dest_ty.fmt(mod), container,
10604 dest_ty.fmt(pt), container,
1049810605 });
1049910606 },
1050010607
......@@ -10521,14 +10628,14 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1052110628 .Type,
1052210629 .Undefined,
1052310630 .Void,
10524 => return sema.fail(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)}),
10631 => return sema.fail(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)}),
1052510632
1052610633 .Enum => {
1052710634 const msg = msg: {
10528 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)});
10635 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)});
1052910636 errdefer msg.destroy(sema.gpa);
1053010637 switch (dest_ty.zigTypeTag(mod)) {
10531 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromEnum to cast to '{}'", .{dest_ty.fmt(mod)}),
10638 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromEnum to cast to '{}'", .{dest_ty.fmt(pt)}),
1053210639 else => {},
1053310640 }
1053410641
......@@ -10538,11 +10645,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1053810645 },
1053910646 .Pointer => {
1054010647 const msg = msg: {
10541 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)});
10648 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)});
1054210649 errdefer msg.destroy(sema.gpa);
1054310650 switch (dest_ty.zigTypeTag(mod)) {
10544 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromPtr to cast to '{}'", .{dest_ty.fmt(mod)}),
10545 .Pointer => try sema.errNote(operand_src, msg, "use @ptrCast to cast to '{}'", .{dest_ty.fmt(mod)}),
10651 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromPtr to cast to '{}'", .{dest_ty.fmt(pt)}),
10652 .Pointer => try sema.errNote(operand_src, msg, "use @ptrCast to cast to '{}'", .{dest_ty.fmt(pt)}),
1054610653 else => {},
1054710654 }
1054810655
......@@ -10557,7 +10664,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1055710664 else => unreachable,
1055810665 };
1055910666 return sema.fail(block, operand_src, "cannot @bitCast from '{}'; {s} does not have a guaranteed in-memory layout", .{
10560 operand_ty.fmt(mod), container,
10667 operand_ty.fmt(pt), container,
1056110668 });
1056210669 },
1056310670
......@@ -10575,7 +10682,8 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1057510682 const tracy = trace(@src());
1057610683 defer tracy.end();
1057710684
10578 const mod = sema.mod;
10685 const pt = sema.pt;
10686 const mod = pt.zcu;
1057910687 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1058010688 const src = block.nodeOffset(inst_data.src_node);
1058110689 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -10599,7 +10707,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1059910707 block,
1060010708 src,
1060110709 "expected float or vector type, found '{}'",
10602 .{dest_ty.fmt(mod)},
10710 .{dest_ty.fmt(pt)},
1060310711 ),
1060410712 };
1060510713
......@@ -10609,21 +10717,21 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1060910717 block,
1061010718 operand_src,
1061110719 "expected float or vector type, found '{}'",
10612 .{operand_ty.fmt(mod)},
10720 .{operand_ty.fmt(pt)},
1061310721 ),
1061410722 }
1061510723
1061610724 if (try sema.resolveValue(operand)) |operand_val| {
1061710725 if (!is_vector) {
10618 return Air.internedToRef((try operand_val.floatCast(dest_ty, mod)).toIntern());
10726 return Air.internedToRef((try operand_val.floatCast(dest_ty, pt)).toIntern());
1061910727 }
1062010728 const vec_len = operand_ty.vectorLen(mod);
1062110729 const new_elems = try sema.arena.alloc(InternPool.Index, vec_len);
1062210730 for (new_elems, 0..) |*new_elem, i| {
10623 const old_elem = try operand_val.elemValue(mod, i);
10624 new_elem.* = (try old_elem.floatCast(dest_scalar_ty, mod)).toIntern();
10731 const old_elem = try operand_val.elemValue(pt, i);
10732 new_elem.* = (try old_elem.floatCast(dest_scalar_ty, pt)).toIntern();
1062510733 }
10626 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
10734 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
1062710735 .ty = dest_ty.toIntern(),
1062810736 .storage = .{ .elems = new_elems },
1062910737 } }));
......@@ -10644,7 +10752,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1064410752 const vec_len = operand_ty.vectorLen(mod);
1064510753 const new_elems = try sema.arena.alloc(Air.Inst.Ref, vec_len);
1064610754 for (new_elems, 0..) |*new_elem, i| {
10647 const idx_ref = try mod.intRef(Type.usize, i);
10755 const idx_ref = try pt.intRef(Type.usize, i);
1064810756 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
1064910757 new_elem.* = try block.addTyOp(.fptrunc, dest_scalar_ty, old_elem);
1065010758 }
......@@ -10681,10 +10789,9 @@ fn zirElemValImm(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1068110789 const tracy = trace(@src());
1068210790 defer tracy.end();
1068310791
10684 const mod = sema.mod;
1068510792 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].elem_val_imm;
1068610793 const array = try sema.resolveInst(inst_data.operand);
10687 const elem_index = try mod.intRef(Type.usize, inst_data.idx);
10794 const elem_index = try sema.pt.intRef(Type.usize, inst_data.idx);
1068810795 return sema.elemVal(block, LazySrcLoc.unneeded, array, elem_index, LazySrcLoc.unneeded, false);
1068910796}
1069010797
......@@ -10692,7 +10799,8 @@ fn zirElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1069210799 const tracy = trace(@src());
1069310800 defer tracy.end();
1069410801
10695 const mod = sema.mod;
10802 const pt = sema.pt;
10803 const mod = pt.zcu;
1069610804 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1069710805 const src = block.nodeOffset(inst_data.src_node);
1069810806 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -10703,7 +10811,7 @@ fn zirElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1070310811 const capture_src = block.src(.{ .for_capture_from_input = inst_data.src_node });
1070410812 const msg = msg: {
1070510813 const msg = try sema.errMsg(capture_src, "pointer capture of non pointer type '{}'", .{
10706 indexable_ty.fmt(mod),
10814 indexable_ty.fmt(pt),
1070710815 });
1070810816 errdefer msg.destroy(sema.gpa);
1070910817 if (indexable_ty.isIndexable(mod)) {
......@@ -10734,12 +10842,13 @@ fn zirArrayInitElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compile
1073410842 const tracy = trace(@src());
1073510843 defer tracy.end();
1073610844
10737 const mod = sema.mod;
10845 const pt = sema.pt;
10846 const mod = pt.zcu;
1073810847 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1073910848 const src = block.nodeOffset(inst_data.src_node);
1074010849 const extra = sema.code.extraData(Zir.Inst.ElemPtrImm, inst_data.payload_index).data;
1074110850 const array_ptr = try sema.resolveInst(extra.ptr);
10742 const elem_index = try sema.mod.intRef(Type.usize, extra.index);
10851 const elem_index = try pt.intRef(Type.usize, extra.index);
1074310852 const array_ty = sema.typeOf(array_ptr).childType(mod);
1074410853 switch (array_ty.zigTypeTag(mod)) {
1074510854 .Array, .Vector => {},
......@@ -10892,7 +11001,7 @@ const SwitchProngAnalysis = struct {
1089211001 inline_case_capture,
1089311002 );
1089411003
10895 if (sema.typeOf(capture_ref).isNoReturn(sema.mod)) {
11004 if (sema.typeOf(capture_ref).isNoReturn(sema.pt.zcu)) {
1089611005 // This prong should be unreachable!
1089711006 return .unreachable_value;
1089811007 }
......@@ -10948,7 +11057,7 @@ const SwitchProngAnalysis = struct {
1094811057 inline_case_capture,
1094911058 );
1095011059
10951 if (sema.typeOf(capture_ref).isNoReturn(sema.mod)) {
11060 if (sema.typeOf(capture_ref).isNoReturn(sema.pt.zcu)) {
1095211061 // No need to analyze any further, the prong is unreachable
1095311062 return;
1095411063 }
......@@ -10968,7 +11077,8 @@ const SwitchProngAnalysis = struct {
1096811077 inline_case_capture: Air.Inst.Ref,
1096911078 ) CompileError!Air.Inst.Ref {
1097011079 const sema = spa.sema;
10971 const mod = sema.mod;
11080 const pt = sema.pt;
11081 const mod = pt.zcu;
1097211082 const operand_ty = sema.typeOf(spa.operand);
1097311083 if (operand_ty.zigTypeTag(mod) != .Union) {
1097411084 const tag_capture_src: LazySrcLoc = .{
......@@ -10976,7 +11086,7 @@ const SwitchProngAnalysis = struct {
1097611086 .offset = .{ .switch_tag_capture = capture_src.offset.switch_capture },
1097711087 };
1097811088 return sema.fail(block, tag_capture_src, "cannot capture tag of non-union type '{}'", .{
10979 operand_ty.fmt(mod),
11089 operand_ty.fmt(pt),
1098011090 });
1098111091 }
1098211092 assert(inline_case_capture != .none);
......@@ -10993,7 +11103,8 @@ const SwitchProngAnalysis = struct {
1099311103 inline_case_capture: Air.Inst.Ref,
1099411104 ) CompileError!Air.Inst.Ref {
1099511105 const sema = spa.sema;
10996 const zcu = sema.mod;
11106 const pt = sema.pt;
11107 const zcu = pt.zcu;
1099711108 const ip = &zcu.intern_pool;
1099811109
1099911110 const zir_datas = sema.code.instructions.items(.data);
......@@ -11010,7 +11121,7 @@ const SwitchProngAnalysis = struct {
1101011121 const union_obj = zcu.typeToUnion(operand_ty).?;
1101111122 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
1101211123 if (capture_byref) {
11013 const ptr_field_ty = try zcu.ptrTypeSema(.{
11124 const ptr_field_ty = try pt.ptrTypeSema(.{
1101411125 .child = field_ty.toIntern(),
1101511126 .flags = .{
1101611127 .is_const = !operand_ptr_ty.ptrIsMutable(zcu),
......@@ -11019,7 +11130,7 @@ const SwitchProngAnalysis = struct {
1101911130 },
1102011131 });
1102111132 if (try sema.resolveDefinedValue(block, operand_src, spa.operand_ptr)) |union_ptr| {
11022 return Air.internedToRef((try union_ptr.ptrField(field_index, zcu)).toIntern());
11133 return Air.internedToRef((try union_ptr.ptrField(field_index, pt)).toIntern());
1102311134 }
1102411135 return block.addStructFieldPtr(spa.operand_ptr, field_index, ptr_field_ty);
1102511136 } else {
......@@ -11078,7 +11189,7 @@ const SwitchProngAnalysis = struct {
1107811189 const dummy_captures = try sema.arena.alloc(Air.Inst.Ref, case_vals.len);
1107911190 for (dummy_captures, field_indices) |*dummy, field_idx| {
1108011191 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_idx]);
11081 dummy.* = try zcu.undefRef(field_ty);
11192 dummy.* = try pt.undefRef(field_ty);
1108211193 }
1108311194
1108411195 const case_srcs = try sema.arena.alloc(?LazySrcLoc, case_vals.len);
......@@ -11113,7 +11224,7 @@ const SwitchProngAnalysis = struct {
1111311224 const dummy_captures = try sema.arena.alloc(Air.Inst.Ref, case_vals.len);
1111411225 for (field_indices, dummy_captures) |field_idx, *dummy| {
1111511226 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_idx]);
11116 const field_ptr_ty = try zcu.ptrTypeSema(.{
11227 const field_ptr_ty = try pt.ptrTypeSema(.{
1111711228 .child = field_ty.toIntern(),
1111811229 .flags = .{
1111911230 .is_const = operand_ptr_info.flags.is_const,
......@@ -11122,7 +11233,7 @@ const SwitchProngAnalysis = struct {
1112211233 .alignment = union_obj.fieldAlign(ip, field_idx),
1112311234 },
1112411235 });
11125 dummy.* = try zcu.undefRef(field_ptr_ty);
11236 dummy.* = try pt.undefRef(field_ptr_ty);
1112611237 }
1112711238 const case_srcs = try sema.arena.alloc(?LazySrcLoc, case_vals.len);
1112811239 for (case_srcs, 0..) |*case_src, i| {
......@@ -11148,9 +11259,9 @@ const SwitchProngAnalysis = struct {
1114811259 };
1114911260
1115011261 if (try sema.resolveDefinedValue(block, operand_src, spa.operand_ptr)) |op_ptr_val| {
11151 if (op_ptr_val.isUndef(zcu)) return zcu.undefRef(capture_ptr_ty);
11152 const field_ptr_val = try op_ptr_val.ptrField(first_field_index, zcu);
11153 return Air.internedToRef((try zcu.getCoerced(field_ptr_val, capture_ptr_ty)).toIntern());
11262 if (op_ptr_val.isUndef(zcu)) return pt.undefRef(capture_ptr_ty);
11263 const field_ptr_val = try op_ptr_val.ptrField(first_field_index, pt);
11264 return Air.internedToRef((try pt.getCoerced(field_ptr_val, capture_ptr_ty)).toIntern());
1115411265 }
1115511266
1115611267 try sema.requireRuntimeBlock(block, operand_src, null);
......@@ -11158,9 +11269,9 @@ const SwitchProngAnalysis = struct {
1115811269 }
1115911270
1116011271 if (try sema.resolveDefinedValue(block, operand_src, spa.operand)) |operand_val| {
11161 if (operand_val.isUndef(zcu)) return zcu.undefRef(capture_ty);
11272 if (operand_val.isUndef(zcu)) return pt.undefRef(capture_ty);
1116211273 const union_val = ip.indexToKey(operand_val.toIntern()).un;
11163 if (Value.fromInterned(union_val.tag).isUndef(zcu)) return zcu.undefRef(capture_ty);
11274 if (Value.fromInterned(union_val.tag).isUndef(zcu)) return pt.undefRef(capture_ty);
1116411275 const uncoerced = Air.internedToRef(union_val.val);
1116511276 return sema.coerce(block, capture_ty, uncoerced, operand_src);
1116611277 }
......@@ -11304,7 +11415,7 @@ const SwitchProngAnalysis = struct {
1130411415
1130511416 if (case_vals.len == 1) {
1130611417 const item_val = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, case_vals[0], undefined) catch unreachable;
11307 const item_ty = try zcu.singleErrorSetType(item_val.getErrorName(zcu).unwrap().?);
11418 const item_ty = try pt.singleErrorSetType(item_val.getErrorName(zcu).unwrap().?);
1130811419 return sema.bitCast(block, item_ty, spa.operand, operand_src, null);
1130911420 }
1131011421
......@@ -11314,7 +11425,7 @@ const SwitchProngAnalysis = struct {
1131411425 const err_val = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, err, undefined) catch unreachable;
1131511426 names.putAssumeCapacityNoClobber(err_val.getErrorName(zcu).unwrap().?, {});
1131611427 }
11317 const error_ty = try zcu.errorSetFromUnsortedNames(names.keys());
11428 const error_ty = try pt.errorSetFromUnsortedNames(names.keys());
1131811429 return sema.bitCast(block, error_ty, spa.operand, operand_src, null);
1131911430 },
1132011431 else => {
......@@ -11336,7 +11447,8 @@ fn switchCond(
1133611447 src: LazySrcLoc,
1133711448 operand: Air.Inst.Ref,
1133811449) CompileError!Air.Inst.Ref {
11339 const mod = sema.mod;
11450 const pt = sema.pt;
11451 const mod = pt.zcu;
1134011452 const operand_ty = sema.typeOf(operand);
1134111453 switch (operand_ty.zigTypeTag(mod)) {
1134211454 .Type,
......@@ -11353,7 +11465,7 @@ fn switchCond(
1135311465 .Enum,
1135411466 => {
1135511467 if (operand_ty.isSlice(mod)) {
11356 return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(mod)});
11468 return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(pt)});
1135711469 }
1135811470 if ((try sema.typeHasOnePossibleValue(operand_ty))) |opv| {
1135911471 return Air.internedToRef(opv.toIntern());
......@@ -11362,7 +11474,7 @@ fn switchCond(
1136211474 },
1136311475
1136411476 .Union => {
11365 try operand_ty.resolveFields(mod);
11477 try operand_ty.resolveFields(pt);
1136611478 const enum_ty = operand_ty.unionTagType(mod) orelse {
1136711479 const msg = msg: {
1136811480 const msg = try sema.errMsg(src, "switch on union with no attached enum", .{});
......@@ -11388,7 +11500,7 @@ fn switchCond(
1138811500 .Vector,
1138911501 .Frame,
1139011502 .AnyFrame,
11391 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(mod)}),
11503 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(pt)}),
1139211504 }
1139311505}
1139411506
......@@ -11398,7 +11510,8 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1139811510 const tracy = trace(@src());
1139911511 defer tracy.end();
1140011512
11401 const mod = sema.mod;
11513 const pt = sema.pt;
11514 const mod = pt.zcu;
1140211515 const gpa = sema.gpa;
1140311516 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1140411517 const switch_src = block.nodeOffset(inst_data.src_node);
......@@ -11489,7 +11602,7 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1148911602
1149011603 if (operand_err_set.zigTypeTag(mod) != .ErrorUnion) {
1149111604 return sema.fail(block, switch_src, "expected error union type, found '{}'", .{
11492 operand_ty.fmt(mod),
11605 operand_ty.fmt(pt),
1149311606 });
1149411607 }
1149511608
......@@ -11571,7 +11684,7 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1157111684 if (operand_val.errorUnionIsPayload(mod)) {
1157211685 return sema.resolveBlockBody(block, main_operand_src, &child_block, non_error_case.body, inst, merges);
1157311686 } else {
11574 const err_val = Value.fromInterned(try mod.intern(.{
11687 const err_val = Value.fromInterned(try pt.intern(.{
1157511688 .err = .{
1157611689 .ty = operand_err_set_ty.toIntern(),
1157711690 .name = operand_val.getErrorName(mod).unwrap().?,
......@@ -11708,7 +11821,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1170811821 const tracy = trace(@src());
1170911822 defer tracy.end();
1171011823
11711 const mod = sema.mod;
11824 const pt = sema.pt;
11825 const mod = pt.zcu;
1171211826 const gpa = sema.gpa;
1171311827 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1171411828 const src = block.nodeOffset(inst_data.src_node);
......@@ -11783,7 +11897,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1178311897 // Duplicate checking variables later also used for `inline else`.
1178411898 var seen_enum_fields: []?LazySrcLoc = &.{};
1178511899 var seen_errors = SwitchErrorSet.init(gpa);
11786 var range_set = RangeSet.init(gpa, mod);
11900 var range_set = RangeSet.init(gpa, pt);
1178711901 var true_count: u8 = 0;
1178811902 var false_count: u8 = 0;
1178911903
......@@ -11924,7 +12038,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1192412038 operand_ty.srcLoc(mod),
1192512039 msg,
1192612040 "enum '{}' declared here",
11927 .{operand_ty.fmt(mod)},
12041 .{operand_ty.fmt(pt)},
1192812042 );
1192912043 break :msg msg;
1193012044 };
......@@ -12030,8 +12144,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1203012144
1203112145 check_range: {
1203212146 if (operand_ty.zigTypeTag(mod) == .Int) {
12033 const min_int = try operand_ty.minInt(mod, operand_ty);
12034 const max_int = try operand_ty.maxInt(mod, operand_ty);
12147 const min_int = try operand_ty.minInt(pt, operand_ty);
12148 const max_int = try operand_ty.maxInt(pt, operand_ty);
1203512149 if (try range_set.spans(min_int.toIntern(), max_int.toIntern())) {
1203612150 if (special_prong == .@"else") {
1203712151 return sema.fail(
......@@ -12136,7 +12250,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1213612250 block,
1213712251 src,
1213812252 "else prong required when switching on type '{}'",
12139 .{operand_ty.fmt(mod)},
12253 .{operand_ty.fmt(pt)},
1214012254 );
1214112255 }
1214212256
......@@ -12212,7 +12326,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1221212326 .ComptimeFloat,
1221312327 .Float,
1221412328 => return sema.fail(block, operand_src, "invalid switch operand type '{}'", .{
12215 operand_ty.fmt(mod),
12329 operand_ty.fmt(pt),
1221612330 }),
1221712331 }
1221812332
......@@ -12386,7 +12500,8 @@ fn analyzeSwitchRuntimeBlock(
1238612500 cond_dbg_node_index: Zir.Inst.Index,
1238712501 allow_err_code_unwrap: bool,
1238812502) CompileError!Air.Inst.Ref {
12389 const mod = sema.mod;
12503 const pt = sema.pt;
12504 const mod = pt.zcu;
1239012505 const gpa = sema.gpa;
1239112506 const ip = &mod.intern_pool;
1239212507
......@@ -12496,9 +12611,9 @@ fn analyzeSwitchRuntimeBlock(
1249612611 var item = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, item_first_ref, undefined) catch unreachable;
1249712612 const item_last = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, item_last_ref, undefined) catch unreachable;
1249812613
12499 while (item.compareScalar(.lte, item_last, operand_ty, mod)) : ({
12614 while (item.compareScalar(.lte, item_last, operand_ty, pt)) : ({
1250012615 // Previous validation has resolved any possible lazy values.
12501 item = sema.intAddScalar(item, try mod.intValue(operand_ty, 1), operand_ty) catch |err| switch (err) {
12616 item = sema.intAddScalar(item, try pt.intValue(operand_ty, 1), operand_ty) catch |err| switch (err) {
1250212617 error.Overflow => unreachable,
1250312618 else => |e| return e,
1250412619 };
......@@ -12537,7 +12652,7 @@ fn analyzeSwitchRuntimeBlock(
1253712652 cases_extra.appendAssumeCapacity(@intFromEnum(item_ref));
1253812653 cases_extra.appendSliceAssumeCapacity(@ptrCast(case_block.instructions.items));
1253912654
12540 if (item.compareScalar(.eq, item_last, operand_ty, mod)) break;
12655 if (item.compareScalar(.eq, item_last, operand_ty, pt)) break;
1254112656 }
1254212657 }
1254312658
......@@ -12744,14 +12859,14 @@ fn analyzeSwitchRuntimeBlock(
1274412859 .Enum => {
1274512860 if (operand_ty.isNonexhaustiveEnum(mod) and !union_originally) {
1274612861 return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12747 operand_ty.fmt(mod),
12862 operand_ty.fmt(pt),
1274812863 });
1274912864 }
1275012865 for (seen_enum_fields, 0..) |f, i| {
1275112866 if (f != null) continue;
1275212867 cases_len += 1;
1275312868
12754 const item_val = try mod.enumValueFieldIndex(operand_ty, @intCast(i));
12869 const item_val = try pt.enumValueFieldIndex(operand_ty, @intCast(i));
1275512870 const item_ref = Air.internedToRef(item_val.toIntern());
1275612871
1275712872 case_block.instructions.shrinkRetainingCapacity(0);
......@@ -12793,7 +12908,7 @@ fn analyzeSwitchRuntimeBlock(
1279312908 .ErrorSet => {
1279412909 if (operand_ty.isAnyError(mod)) {
1279512910 return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12796 operand_ty.fmt(mod),
12911 operand_ty.fmt(pt),
1279712912 });
1279812913 }
1279912914 const error_names = operand_ty.errorSetNames(mod);
......@@ -12802,7 +12917,7 @@ fn analyzeSwitchRuntimeBlock(
1280212917 if (seen_errors.contains(error_name)) continue;
1280312918 cases_len += 1;
1280412919
12805 const item_val = try mod.intern(.{ .err = .{
12920 const item_val = try pt.intern(.{ .err = .{
1280612921 .ty = operand_ty.toIntern(),
1280712922 .name = error_name,
1280812923 } });
......@@ -12930,7 +13045,7 @@ fn analyzeSwitchRuntimeBlock(
1293013045 }
1293113046 },
1293213047 else => return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12933 operand_ty.fmt(mod),
13048 operand_ty.fmt(pt),
1293413049 }),
1293513050 };
1293613051
......@@ -13051,7 +13166,7 @@ fn resolveSwitchComptime(
1305113166
1305213167 const item = case_vals.items[scalar_i];
1305313168 const item_val = sema.resolveConstDefinedValue(child_block, LazySrcLoc.unneeded, item, undefined) catch unreachable;
13054 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
13169 if (operand_val.eql(item_val, operand_ty, sema.pt.zcu)) {
1305513170 if (err_set) try sema.maybeErrorUnwrapComptime(child_block, body, cond_operand);
1305613171 return spa.resolveProngComptime(
1305713172 child_block,
......@@ -13088,7 +13203,7 @@ fn resolveSwitchComptime(
1308813203 for (items) |item| {
1308913204 // Validation above ensured these will succeed.
1309013205 const item_val = sema.resolveConstDefinedValue(child_block, LazySrcLoc.unneeded, item, undefined) catch unreachable;
13091 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
13206 if (operand_val.eql(item_val, operand_ty, sema.pt.zcu)) {
1309213207 if (err_set) try sema.maybeErrorUnwrapComptime(child_block, body, cond_operand);
1309313208 return spa.resolveProngComptime(
1309413209 child_block,
......@@ -13162,7 +13277,7 @@ fn resolveSwitchComptime(
1316213277}
1316313278
1316413279const RangeSetUnhandledIterator = struct {
13165 mod: *Module,
13280 pt: Zcu.PerThread,
1316613281 cur: ?InternPool.Index,
1316713282 max: InternPool.Index,
1316813283 range_i: usize,
......@@ -13172,13 +13287,13 @@ const RangeSetUnhandledIterator = struct {
1317213287 const preallocated_limbs = math.big.int.calcTwosCompLimbCount(128);
1317313288
1317413289 fn init(sema: *Sema, ty: Type, range_set: RangeSet) !RangeSetUnhandledIterator {
13175 const mod = sema.mod;
13176 const int_type = mod.intern_pool.indexToKey(ty.toIntern()).int_type;
13290 const pt = sema.pt;
13291 const int_type = pt.zcu.intern_pool.indexToKey(ty.toIntern()).int_type;
1317713292 const needed_limbs = math.big.int.calcTwosCompLimbCount(int_type.bits);
1317813293 return .{
13179 .mod = mod,
13180 .cur = (try ty.minInt(mod, ty)).toIntern(),
13181 .max = (try ty.maxInt(mod, ty)).toIntern(),
13294 .pt = pt,
13295 .cur = (try ty.minInt(pt, ty)).toIntern(),
13296 .max = (try ty.maxInt(pt, ty)).toIntern(),
1318213297 .range_i = 0,
1318313298 .ranges = range_set.ranges.items,
1318413299 .limbs = if (needed_limbs > preallocated_limbs)
......@@ -13190,13 +13305,13 @@ const RangeSetUnhandledIterator = struct {
1319013305
1319113306 fn addOne(it: *const RangeSetUnhandledIterator, val: InternPool.Index) !?InternPool.Index {
1319213307 if (val == it.max) return null;
13193 const int = it.mod.intern_pool.indexToKey(val).int;
13308 const int = it.pt.zcu.intern_pool.indexToKey(val).int;
1319413309
1319513310 switch (int.storage) {
1319613311 inline .u64, .i64 => |val_int| {
1319713312 const next_int = @addWithOverflow(val_int, 1);
1319813313 if (next_int[1] == 0)
13199 return (try it.mod.intValue(Type.fromInterned(int.ty), next_int[0])).toIntern();
13314 return (try it.pt.intValue(Type.fromInterned(int.ty), next_int[0])).toIntern();
1320013315 },
1320113316 .big_int => {},
1320213317 .lazy_align, .lazy_size => unreachable,
......@@ -13212,7 +13327,7 @@ const RangeSetUnhandledIterator = struct {
1321213327 );
1321313328
1321413329 result_bigint.addScalar(val_bigint, 1);
13215 return (try it.mod.intValue_big(Type.fromInterned(int.ty), result_bigint.toConst())).toIntern();
13330 return (try it.pt.intValue_big(Type.fromInterned(int.ty), result_bigint.toConst())).toIntern();
1321613331 }
1321713332
1321813333 fn next(it: *RangeSetUnhandledIterator) !?InternPool.Index {
......@@ -13274,7 +13389,8 @@ fn validateErrSetSwitch(
1327413389 has_else: bool,
1327513390) CompileError!?Type {
1327613391 const gpa = sema.gpa;
13277 const mod = sema.mod;
13392 const pt = sema.pt;
13393 const mod = pt.zcu;
1327813394 const ip = &mod.intern_pool;
1327913395
1328013396 const src_node_offset = inst_data.src_node;
......@@ -13426,7 +13542,7 @@ fn validateErrSetSwitch(
1342613542 }
1342713543 // No need to keep the hash map metadata correct; here we
1342813544 // extract the (sorted) keys only.
13429 return try mod.errorSetFromUnsortedNames(names.keys());
13545 return try pt.errorSetFromUnsortedNames(names.keys());
1343013546 },
1343113547 }
1343213548 return null;
......@@ -13441,7 +13557,6 @@ fn validateSwitchRange(
1344113557 operand_ty: Type,
1344213558 item_src: LazySrcLoc,
1344313559) CompileError![2]Air.Inst.Ref {
13444 const mod = sema.mod;
1344513560 const first_src: LazySrcLoc = .{
1344613561 .base_node_inst = item_src.base_node_inst,
1344713562 .offset = .{ .switch_case_item_range_first = item_src.offset.switch_case_item },
......@@ -13452,7 +13567,7 @@ fn validateSwitchRange(
1345213567 };
1345313568 const first = try sema.resolveSwitchItemVal(block, first_ref, operand_ty, first_src);
1345413569 const last = try sema.resolveSwitchItemVal(block, last_ref, operand_ty, last_src);
13455 if (try Value.fromInterned(first.val).compareAll(.gt, Value.fromInterned(last.val), operand_ty, mod)) {
13570 if (try Value.fromInterned(first.val).compareAll(.gt, Value.fromInterned(last.val), operand_ty, sema.pt)) {
1345613571 return sema.fail(block, item_src, "range start value is greater than the end value", .{});
1345713572 }
1345813573 const maybe_prev_src = try range_set.add(first.val, last.val, item_src);
......@@ -13483,7 +13598,7 @@ fn validateSwitchItemEnum(
1348313598 operand_ty: Type,
1348413599 item_src: LazySrcLoc,
1348513600) CompileError!Air.Inst.Ref {
13486 const ip = &sema.mod.intern_pool;
13601 const ip = &sema.pt.zcu.intern_pool;
1348713602 const item = try sema.resolveSwitchItemVal(block, item_ref, operand_ty, item_src);
1348813603 const int = ip.indexToKey(item.val).enum_tag.int;
1348913604 const field_index = ip.loadEnumType(ip.typeOf(item.val)).tagValueIndex(ip, int) orelse {
......@@ -13505,9 +13620,8 @@ fn validateSwitchItemError(
1350513620 operand_ty: Type,
1350613621 item_src: LazySrcLoc,
1350713622) CompileError!Air.Inst.Ref {
13508 const ip = &sema.mod.intern_pool;
1350913623 const item = try sema.resolveSwitchItemVal(block, item_ref, operand_ty, item_src);
13510 const error_name = ip.indexToKey(item.val).err.name;
13624 const error_name = sema.pt.zcu.intern_pool.indexToKey(item.val).err.name;
1351113625 const maybe_prev_src = if (try seen_errors.fetchPut(error_name, item_src)) |prev|
1351213626 prev.value
1351313627 else
......@@ -13593,7 +13707,7 @@ fn validateSwitchNoRange(
1359313707 const msg = try sema.errMsg(
1359413708 operand_src,
1359513709 "ranges not allowed when switching on type '{}'",
13596 .{operand_ty.fmt(sema.mod)},
13710 .{operand_ty.fmt(sema.pt)},
1359713711 );
1359813712 errdefer msg.destroy(sema.gpa);
1359913713 try sema.errNote(
......@@ -13615,7 +13729,8 @@ fn maybeErrorUnwrap(
1361513729 operand_src: LazySrcLoc,
1361613730 allow_err_code_inst: bool,
1361713731) !bool {
13618 const mod = sema.mod;
13732 const pt = sema.pt;
13733 const mod = pt.zcu;
1361913734 if (!mod.backendSupportsFeature(.panic_unwrap_error)) return false;
1362013735
1362113736 const tags = sema.code.instructions.items(.tag);
......@@ -13654,7 +13769,7 @@ fn maybeErrorUnwrap(
1365413769 return true;
1365513770 }
1365613771
13657 const panic_fn = try mod.getBuiltin("panicUnwrapError");
13772 const panic_fn = try pt.getBuiltin("panicUnwrapError");
1365813773 const err_return_trace = try sema.getErrorReturnTrace(block);
1365913774 const args: [2]Air.Inst.Ref = .{ err_return_trace, operand };
1366013775 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
......@@ -13664,7 +13779,7 @@ fn maybeErrorUnwrap(
1366413779 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1366513780 const msg_inst = try sema.resolveInst(inst_data.operand);
1366613781
13667 const panic_fn = try mod.getBuiltin("panic");
13782 const panic_fn = try pt.getBuiltin("panic");
1366813783 const err_return_trace = try sema.getErrorReturnTrace(block);
1366913784 const args: [3]Air.Inst.Ref = .{ msg_inst, err_return_trace, .null_value };
1367013785 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
......@@ -13680,7 +13795,8 @@ fn maybeErrorUnwrap(
1368013795}
1368113796
1368213797fn maybeErrorUnwrapCondbr(sema: *Sema, block: *Block, body: []const Zir.Inst.Index, cond: Zir.Inst.Ref, cond_src: LazySrcLoc) !void {
13683 const mod = sema.mod;
13798 const pt = sema.pt;
13799 const mod = pt.zcu;
1368413800 const index = cond.toIndex() orelse return;
1368513801 if (sema.code.instructions.items(.tag)[@intFromEnum(index)] != .is_non_err) return;
1368613802
......@@ -13713,14 +13829,15 @@ fn maybeErrorUnwrapComptime(sema: *Sema, block: *Block, body: []const Zir.Inst.I
1371313829 const src = block.nodeOffset(inst_data.src_node);
1371413830
1371513831 if (try sema.resolveDefinedValue(block, src, operand)) |val| {
13716 if (val.getErrorName(sema.mod).unwrap()) |name| {
13832 if (val.getErrorName(sema.pt.zcu).unwrap()) |name| {
1371713833 return sema.failWithComptimeErrorRetTrace(block, src, name);
1371813834 }
1371913835 }
1372013836}
1372113837
1372213838fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13723 const mod = sema.mod;
13839 const pt = sema.pt;
13840 const mod = pt.zcu;
1372413841 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1372513842 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1372613843 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -13729,7 +13846,7 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1372913846 const field_name = try sema.resolveConstStringIntern(block, name_src, extra.rhs, .{
1373013847 .needed_comptime_reason = "field name must be comptime-known",
1373113848 });
13732 try ty.resolveFields(mod);
13849 try ty.resolveFields(pt);
1373313850 const ip = &mod.intern_pool;
1373413851
1373513852 const has_field = hf: {
......@@ -13764,14 +13881,15 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1376413881 else => {},
1376513882 }
1376613883 return sema.fail(block, ty_src, "type '{}' does not support '@hasField'", .{
13767 ty.fmt(mod),
13884 ty.fmt(pt),
1376813885 });
1376913886 };
1377013887 return if (has_field) .bool_true else .bool_false;
1377113888}
1377213889
1377313890fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13774 const mod = sema.mod;
13891 const pt = sema.pt;
13892 const mod = pt.zcu;
1377513893 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1377613894 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1377713895 const src = block.nodeOffset(inst_data.src_node);
......@@ -13804,7 +13922,8 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1380413922 const tracy = trace(@src());
1380513923 defer tracy.end();
1380613924
13807 const zcu = sema.mod;
13925 const pt = sema.pt;
13926 const zcu = pt.zcu;
1380813927 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1380913928 const operand_src = block.tokenOffset(inst_data.src_tok);
1381013929 const operand = inst_data.get(sema.code);
......@@ -13824,7 +13943,7 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1382413943 return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
1382513944 },
1382613945 };
13827 try zcu.ensureFileAnalyzed(result.file_index);
13946 try pt.ensureFileAnalyzed(result.file_index);
1382813947 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
1382913948 return sema.analyzeDeclVal(block, operand_src, file_root_decl_index);
1383013949}
......@@ -13833,7 +13952,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1383313952 const tracy = trace(@src());
1383413953 defer tracy.end();
1383513954
13836 const mod = sema.mod;
13955 const pt = sema.pt;
1383713956 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1383813957 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1383913958 const name = try sema.resolveConstString(block, operand_src, inst_data.operand, .{
......@@ -13844,7 +13963,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1384413963 return sema.fail(block, operand_src, "file path name cannot be empty", .{});
1384513964 }
1384613965
13847 const val = mod.embedFile(block.getFileScope(mod), name, operand_src) catch |err| switch (err) {
13966 const val = pt.embedFile(block.getFileScope(pt.zcu), name, operand_src) catch |err| switch (err) {
1384813967 error.ImportOutsideModulePath => {
1384913968 return sema.fail(block, operand_src, "embed of file outside package path: '{s}'", .{name});
1385013969 },
......@@ -13859,7 +13978,8 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1385913978}
1386013979
1386113980fn zirRetErrValueCode(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13862 const mod = sema.mod;
13981 const pt = sema.pt;
13982 const mod = pt.zcu;
1386313983 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1386413984 const name = try mod.intern_pool.getOrPutString(
1386513985 sema.gpa,
......@@ -13867,8 +13987,8 @@ fn zirRetErrValueCode(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.R
1386713987 .no_embedded_nulls,
1386813988 );
1386913989 _ = try mod.getErrorValue(name);
13870 const error_set_type = try mod.singleErrorSetType(name);
13871 return Air.internedToRef((try mod.intern(.{ .err = .{
13990 const error_set_type = try pt.singleErrorSetType(name);
13991 return Air.internedToRef((try pt.intern(.{ .err = .{
1387213992 .ty = error_set_type.toIntern(),
1387313993 .name = name,
1387413994 } })));
......@@ -13883,7 +14003,8 @@ fn zirShl(
1388314003 const tracy = trace(@src());
1388414004 defer tracy.end();
1388514005
13886 const mod = sema.mod;
14006 const pt = sema.pt;
14007 const mod = pt.zcu;
1388714008 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1388814009 const src = block.nodeOffset(inst_data.src_node);
1388914010 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -13906,53 +14027,53 @@ fn zirShl(
1390614027
1390714028 if (maybe_rhs_val) |rhs_val| {
1390814029 if (rhs_val.isUndef(mod)) {
13909 return mod.undefRef(sema.typeOf(lhs));
14030 return pt.undefRef(sema.typeOf(lhs));
1391014031 }
1391114032 // If rhs is 0, return lhs without doing any calculations.
13912 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
14033 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1391314034 return lhs;
1391414035 }
1391514036 if (scalar_ty.zigTypeTag(mod) != .ComptimeInt and air_tag != .shl_sat) {
13916 const bit_value = try mod.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
14037 const bit_value = try pt.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
1391714038 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1391814039 var i: usize = 0;
1391914040 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
13920 const rhs_elem = try rhs_val.elemValue(mod, i);
13921 if (rhs_elem.compareHetero(.gte, bit_value, mod)) {
14041 const rhs_elem = try rhs_val.elemValue(pt, i);
14042 if (rhs_elem.compareHetero(.gte, bit_value, pt)) {
1392214043 return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
13923 rhs_elem.fmtValue(mod, sema),
14044 rhs_elem.fmtValue(pt, sema),
1392414045 i,
13925 scalar_ty.fmt(mod),
14046 scalar_ty.fmt(pt),
1392614047 });
1392714048 }
1392814049 }
13929 } else if (rhs_val.compareHetero(.gte, bit_value, mod)) {
14050 } else if (rhs_val.compareHetero(.gte, bit_value, pt)) {
1393014051 return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
13931 rhs_val.fmtValue(mod, sema),
13932 scalar_ty.fmt(mod),
14052 rhs_val.fmtValue(pt, sema),
14053 scalar_ty.fmt(pt),
1393314054 });
1393414055 }
1393514056 }
1393614057 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1393714058 var i: usize = 0;
1393814059 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
13939 const rhs_elem = try rhs_val.elemValue(mod, i);
13940 if (rhs_elem.compareHetero(.lt, try mod.intValue(scalar_rhs_ty, 0), mod)) {
14060 const rhs_elem = try rhs_val.elemValue(pt, i);
14061 if (rhs_elem.compareHetero(.lt, try pt.intValue(scalar_rhs_ty, 0), pt)) {
1394114062 return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
13942 rhs_elem.fmtValue(mod, sema),
14063 rhs_elem.fmtValue(pt, sema),
1394314064 i,
1394414065 });
1394514066 }
1394614067 }
13947 } else if (rhs_val.compareHetero(.lt, try mod.intValue(rhs_ty, 0), mod)) {
14068 } else if (rhs_val.compareHetero(.lt, try pt.intValue(rhs_ty, 0), pt)) {
1394814069 return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
13949 rhs_val.fmtValue(mod, sema),
14070 rhs_val.fmtValue(pt, sema),
1395014071 });
1395114072 }
1395214073 }
1395314074
1395414075 const runtime_src = if (maybe_lhs_val) |lhs_val| rs: {
13955 if (lhs_val.isUndef(mod)) return mod.undefRef(lhs_ty);
14076 if (lhs_val.isUndef(mod)) return pt.undefRef(lhs_ty);
1395614077 const rhs_val = maybe_rhs_val orelse {
1395714078 if (scalar_ty.zigTypeTag(mod) == .ComptimeInt) {
1395814079 return sema.fail(block, src, "LHS of shift must be a fixed-width integer type, or RHS must be comptime-known", .{});
......@@ -13960,17 +14081,17 @@ fn zirShl(
1396014081 break :rs rhs_src;
1396114082 };
1396214083 const val = if (scalar_ty.zigTypeTag(mod) == .ComptimeInt)
13963 try lhs_val.shl(rhs_val, lhs_ty, sema.arena, mod)
14084 try lhs_val.shl(rhs_val, lhs_ty, sema.arena, pt)
1396414085 else switch (air_tag) {
1396514086 .shl_exact => val: {
13966 const shifted = try lhs_val.shlWithOverflow(rhs_val, lhs_ty, sema.arena, mod);
13967 if (shifted.overflow_bit.compareAllWithZero(.eq, mod)) {
14087 const shifted = try lhs_val.shlWithOverflow(rhs_val, lhs_ty, sema.arena, pt);
14088 if (shifted.overflow_bit.compareAllWithZero(.eq, pt)) {
1396814089 break :val shifted.wrapped_result;
1396914090 }
1397014091 return sema.fail(block, src, "operation caused overflow", .{});
1397114092 },
13972 .shl_sat => try lhs_val.shlSat(rhs_val, lhs_ty, sema.arena, mod),
13973 .shl => try lhs_val.shlTrunc(rhs_val, lhs_ty, sema.arena, mod),
14093 .shl_sat => try lhs_val.shlSat(rhs_val, lhs_ty, sema.arena, pt),
14094 .shl => try lhs_val.shlTrunc(rhs_val, lhs_ty, sema.arena, pt),
1397414095 else => unreachable,
1397514096 };
1397614097 return Air.internedToRef(val.toIntern());
......@@ -13981,7 +14102,7 @@ fn zirShl(
1398114102 if (rhs_is_comptime_int or
1398214103 scalar_rhs_ty.intInfo(mod).bits > scalar_ty.intInfo(mod).bits)
1398314104 {
13984 const max_int = Air.internedToRef((try lhs_ty.maxInt(mod, lhs_ty)).toIntern());
14105 const max_int = Air.internedToRef((try lhs_ty.maxInt(pt, lhs_ty)).toIntern());
1398514106 const rhs_limited = try sema.analyzeMinMax(block, rhs_src, .min, &.{ rhs, max_int }, &.{ rhs_src, rhs_src });
1398614107 break :rhs try sema.intCast(block, src, lhs_ty, rhs_src, rhs_limited, rhs_src, false);
1398714108 } else {
......@@ -13993,7 +14114,7 @@ fn zirShl(
1399314114 if (block.wantSafety()) {
1399414115 const bit_count = scalar_ty.intInfo(mod).bits;
1399514116 if (!std.math.isPowerOfTwo(bit_count)) {
13996 const bit_count_val = try mod.intValue(scalar_rhs_ty, bit_count);
14117 const bit_count_val = try pt.intValue(scalar_rhs_ty, bit_count);
1399714118 const ok = if (rhs_ty.zigTypeTag(mod) == .Vector) ok: {
1399814119 const bit_count_inst = Air.internedToRef((try sema.splat(rhs_ty, bit_count_val)).toIntern());
1399914120 const lt = try block.addCmpVector(rhs, bit_count_inst, .lt);
......@@ -14034,7 +14155,7 @@ fn zirShl(
1403414155 })
1403514156 else
1403614157 ov_bit;
14037 const zero_ov = Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
14158 const zero_ov = Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
1403814159 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1403914160
1404014161 try sema.addSafetyCheck(block, src, no_ov, .shl_overflow);
......@@ -14053,7 +14174,8 @@ fn zirShr(
1405314174 const tracy = trace(@src());
1405414175 defer tracy.end();
1405514176
14056 const mod = sema.mod;
14177 const pt = sema.pt;
14178 const mod = pt.zcu;
1405714179 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1405814180 const src = block.nodeOffset(inst_data.src_node);
1405914181 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -14071,61 +14193,61 @@ fn zirShr(
1407114193
1407214194 const runtime_src = if (maybe_rhs_val) |rhs_val| rs: {
1407314195 if (rhs_val.isUndef(mod)) {
14074 return mod.undefRef(lhs_ty);
14196 return pt.undefRef(lhs_ty);
1407514197 }
1407614198 // If rhs is 0, return lhs without doing any calculations.
14077 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
14199 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1407814200 return lhs;
1407914201 }
1408014202 if (scalar_ty.zigTypeTag(mod) != .ComptimeInt) {
14081 const bit_value = try mod.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
14203 const bit_value = try pt.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
1408214204 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1408314205 var i: usize = 0;
1408414206 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
14085 const rhs_elem = try rhs_val.elemValue(mod, i);
14086 if (rhs_elem.compareHetero(.gte, bit_value, mod)) {
14207 const rhs_elem = try rhs_val.elemValue(pt, i);
14208 if (rhs_elem.compareHetero(.gte, bit_value, pt)) {
1408714209 return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
14088 rhs_elem.fmtValue(mod, sema),
14210 rhs_elem.fmtValue(pt, sema),
1408914211 i,
14090 scalar_ty.fmt(mod),
14212 scalar_ty.fmt(pt),
1409114213 });
1409214214 }
1409314215 }
14094 } else if (rhs_val.compareHetero(.gte, bit_value, mod)) {
14216 } else if (rhs_val.compareHetero(.gte, bit_value, pt)) {
1409514217 return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
14096 rhs_val.fmtValue(mod, sema),
14097 scalar_ty.fmt(mod),
14218 rhs_val.fmtValue(pt, sema),
14219 scalar_ty.fmt(pt),
1409814220 });
1409914221 }
1410014222 }
1410114223 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1410214224 var i: usize = 0;
1410314225 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
14104 const rhs_elem = try rhs_val.elemValue(mod, i);
14105 if (rhs_elem.compareHetero(.lt, try mod.intValue(rhs_ty.childType(mod), 0), mod)) {
14226 const rhs_elem = try rhs_val.elemValue(pt, i);
14227 if (rhs_elem.compareHetero(.lt, try pt.intValue(rhs_ty.childType(mod), 0), pt)) {
1410614228 return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
14107 rhs_elem.fmtValue(mod, sema),
14229 rhs_elem.fmtValue(pt, sema),
1410814230 i,
1410914231 });
1411014232 }
1411114233 }
14112 } else if (rhs_val.compareHetero(.lt, try mod.intValue(rhs_ty, 0), mod)) {
14234 } else if (rhs_val.compareHetero(.lt, try pt.intValue(rhs_ty, 0), pt)) {
1411314235 return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
14114 rhs_val.fmtValue(mod, sema),
14236 rhs_val.fmtValue(pt, sema),
1411514237 });
1411614238 }
1411714239 if (maybe_lhs_val) |lhs_val| {
1411814240 if (lhs_val.isUndef(mod)) {
14119 return mod.undefRef(lhs_ty);
14241 return pt.undefRef(lhs_ty);
1412014242 }
1412114243 if (air_tag == .shr_exact) {
1412214244 // Detect if any ones would be shifted out.
14123 const truncated = try lhs_val.intTruncBitsAsValue(lhs_ty, sema.arena, .unsigned, rhs_val, mod);
14124 if (!(try truncated.compareAllWithZeroSema(.eq, mod))) {
14245 const truncated = try lhs_val.intTruncBitsAsValue(lhs_ty, sema.arena, .unsigned, rhs_val, pt);
14246 if (!(try truncated.compareAllWithZeroSema(.eq, pt))) {
1412514247 return sema.fail(block, src, "exact shift shifted out 1 bits", .{});
1412614248 }
1412714249 }
14128 const val = try lhs_val.shr(rhs_val, lhs_ty, sema.arena, mod);
14250 const val = try lhs_val.shr(rhs_val, lhs_ty, sema.arena, pt);
1412914251 return Air.internedToRef(val.toIntern());
1413014252 } else {
1413114253 break :rs lhs_src;
......@@ -14141,7 +14263,7 @@ fn zirShr(
1414114263 if (block.wantSafety()) {
1414214264 const bit_count = scalar_ty.intInfo(mod).bits;
1414314265 if (!std.math.isPowerOfTwo(bit_count)) {
14144 const bit_count_val = try mod.intValue(rhs_ty.scalarType(mod), bit_count);
14266 const bit_count_val = try pt.intValue(rhs_ty.scalarType(mod), bit_count);
1414514267
1414614268 const ok = if (rhs_ty.zigTypeTag(mod) == .Vector) ok: {
1414714269 const bit_count_inst = Air.internedToRef((try sema.splat(rhs_ty, bit_count_val)).toIntern());
......@@ -14188,7 +14310,8 @@ fn zirBitwise(
1418814310 const tracy = trace(@src());
1418914311 defer tracy.end();
1419014312
14191 const mod = sema.mod;
14313 const pt = sema.pt;
14314 const mod = pt.zcu;
1419214315 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1419314316 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1419414317 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -14220,9 +14343,9 @@ fn zirBitwise(
1422014343 if (try sema.resolveValueIntable(casted_lhs)) |lhs_val| {
1422114344 if (try sema.resolveValueIntable(casted_rhs)) |rhs_val| {
1422214345 const result_val = switch (air_tag) {
14223 .bit_and => try lhs_val.bitwiseAnd(rhs_val, resolved_type, sema.arena, mod),
14224 .bit_or => try lhs_val.bitwiseOr(rhs_val, resolved_type, sema.arena, mod),
14225 .xor => try lhs_val.bitwiseXor(rhs_val, resolved_type, sema.arena, mod),
14346 .bit_and => try lhs_val.bitwiseAnd(rhs_val, resolved_type, sema.arena, pt),
14347 .bit_or => try lhs_val.bitwiseOr(rhs_val, resolved_type, sema.arena, pt),
14348 .xor => try lhs_val.bitwiseXor(rhs_val, resolved_type, sema.arena, pt),
1422614349 else => unreachable,
1422714350 };
1422814351 return Air.internedToRef(result_val.toIntern());
......@@ -14242,7 +14365,8 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1424214365 const tracy = trace(@src());
1424314366 defer tracy.end();
1424414367
14245 const mod = sema.mod;
14368 const pt = sema.pt;
14369 const mod = pt.zcu;
1424614370 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1424714371 const src = block.nodeOffset(inst_data.src_node);
1424814372 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
......@@ -14253,26 +14377,26 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1425314377
1425414378 if (scalar_type.zigTypeTag(mod) != .Int) {
1425514379 return sema.fail(block, src, "unable to perform binary not operation on type '{}'", .{
14256 operand_type.fmt(mod),
14380 operand_type.fmt(pt),
1425714381 });
1425814382 }
1425914383
1426014384 if (try sema.resolveValue(operand)) |val| {
1426114385 if (val.isUndef(mod)) {
14262 return mod.undefRef(operand_type);
14386 return pt.undefRef(operand_type);
1426314387 } else if (operand_type.zigTypeTag(mod) == .Vector) {
1426414388 const vec_len = try sema.usizeCast(block, operand_src, operand_type.vectorLen(mod));
1426514389 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
1426614390 for (elems, 0..) |*elem, i| {
14267 const elem_val = try val.elemValue(mod, i);
14268 elem.* = (try elem_val.bitwiseNot(scalar_type, sema.arena, mod)).toIntern();
14391 const elem_val = try val.elemValue(pt, i);
14392 elem.* = (try elem_val.bitwiseNot(scalar_type, sema.arena, pt)).toIntern();
1426914393 }
14270 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
14394 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1427114395 .ty = operand_type.toIntern(),
1427214396 .storage = .{ .elems = elems },
1427314397 } })));
1427414398 } else {
14275 const result_val = try val.bitwiseNot(operand_type, sema.arena, mod);
14399 const result_val = try val.bitwiseNot(operand_type, sema.arena, pt);
1427614400 return Air.internedToRef(result_val.toIntern());
1427714401 }
1427814402 }
......@@ -14288,7 +14412,8 @@ fn analyzeTupleCat(
1428814412 lhs: Air.Inst.Ref,
1428914413 rhs: Air.Inst.Ref,
1429014414) CompileError!Air.Inst.Ref {
14291 const mod = sema.mod;
14415 const pt = sema.pt;
14416 const mod = pt.zcu;
1429214417 const lhs_ty = sema.typeOf(lhs);
1429314418 const rhs_ty = sema.typeOf(rhs);
1429414419 const src = block.nodeOffset(src_node);
......@@ -14344,14 +14469,14 @@ fn analyzeTupleCat(
1434414469 break :rs runtime_src;
1434514470 };
1434614471
14347 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, .{
14472 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, pt.tid, .{
1434814473 .types = types,
1434914474 .values = values,
1435014475 .names = &.{},
1435114476 });
1435214477
1435314478 const runtime_src = opt_runtime_src orelse {
14354 const tuple_val = try mod.intern(.{ .aggregate = .{
14479 const tuple_val = try pt.intern(.{ .aggregate = .{
1435514480 .ty = tuple_ty,
1435614481 .storage = .{ .elems = values },
1435714482 } });
......@@ -14386,7 +14511,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1438614511 const tracy = trace(@src());
1438714512 defer tracy.end();
1438814513
14389 const mod = sema.mod;
14514 const pt = sema.pt;
14515 const mod = pt.zcu;
1439014516 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1439114517 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1439214518 const lhs = try sema.resolveInst(extra.lhs);
......@@ -14406,11 +14532,11 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1440614532
1440714533 const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, rhs_ty) orelse lhs_info: {
1440814534 if (lhs_is_tuple) break :lhs_info @as(Type.ArrayInfo, undefined);
14409 return sema.fail(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(mod)});
14535 return sema.fail(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(pt)});
1441014536 };
1441114537 const rhs_info = try sema.getArrayCatInfo(block, rhs_src, rhs, lhs_ty) orelse {
1441214538 assert(!rhs_is_tuple);
14413 return sema.fail(block, rhs_src, "expected indexable; found '{}'", .{rhs_ty.fmt(mod)});
14539 return sema.fail(block, rhs_src, "expected indexable; found '{}'", .{rhs_ty.fmt(pt)});
1441414540 };
1441514541
1441614542 const resolved_elem_ty = t: {
......@@ -14472,7 +14598,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1447214598 ),
1447314599 };
1447414600
14475 const result_ty = try mod.arrayType(.{
14601 const result_ty = try pt.arrayType(.{
1447614602 .len = result_len,
1447714603 .sentinel = if (res_sent_val) |v| v.toIntern() else .none,
1447814604 .child = resolved_elem_ty.toIntern(),
......@@ -14512,7 +14638,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1451214638 while (elem_i < lhs_len) : (elem_i += 1) {
1451314639 const lhs_elem_i = elem_i;
1451414640 const elem_default_val = if (lhs_is_tuple) lhs_ty.structFieldDefaultValue(lhs_elem_i, mod) else Value.@"unreachable";
14515 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try lhs_sub_val.elemValue(mod, lhs_elem_i) else elem_default_val;
14641 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try lhs_sub_val.elemValue(pt, lhs_elem_i) else elem_default_val;
1451614642 const elem_val_inst = Air.internedToRef(elem_val.toIntern());
1451714643 const operand_src = block.src(.{ .array_cat_lhs = .{
1451814644 .array_cat_offset = inst_data.src_node,
......@@ -14525,7 +14651,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1452514651 while (elem_i < result_len) : (elem_i += 1) {
1452614652 const rhs_elem_i = elem_i - lhs_len;
1452714653 const elem_default_val = if (rhs_is_tuple) rhs_ty.structFieldDefaultValue(rhs_elem_i, mod) else Value.@"unreachable";
14528 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try rhs_sub_val.elemValue(mod, rhs_elem_i) else elem_default_val;
14654 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try rhs_sub_val.elemValue(pt, rhs_elem_i) else elem_default_val;
1452914655 const elem_val_inst = Air.internedToRef(elem_val.toIntern());
1453014656 const operand_src = block.src(.{ .array_cat_rhs = .{
1453114657 .array_cat_offset = inst_data.src_node,
......@@ -14535,7 +14661,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1453514661 const coerced_elem_val = try sema.resolveConstValue(block, operand_src, coerced_elem_val_inst, undefined);
1453614662 element_vals[elem_i] = coerced_elem_val.toIntern();
1453714663 }
14538 return sema.addConstantMaybeRef(try mod.intern(.{ .aggregate = .{
14664 return sema.addConstantMaybeRef(try pt.intern(.{ .aggregate = .{
1453914665 .ty = result_ty.toIntern(),
1454014666 .storage = .{ .elems = element_vals },
1454114667 } }), ptr_addrspace != null);
......@@ -14545,19 +14671,19 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1454514671 try sema.requireRuntimeBlock(block, src, runtime_src);
1454614672
1454714673 if (ptr_addrspace) |ptr_as| {
14548 const alloc_ty = try mod.ptrTypeSema(.{
14674 const alloc_ty = try pt.ptrTypeSema(.{
1454914675 .child = result_ty.toIntern(),
1455014676 .flags = .{ .address_space = ptr_as },
1455114677 });
1455214678 const alloc = try block.addTy(.alloc, alloc_ty);
14553 const elem_ptr_ty = try mod.ptrTypeSema(.{
14679 const elem_ptr_ty = try pt.ptrTypeSema(.{
1455414680 .child = resolved_elem_ty.toIntern(),
1455514681 .flags = .{ .address_space = ptr_as },
1455614682 });
1455714683
1455814684 var elem_i: u32 = 0;
1455914685 while (elem_i < lhs_len) : (elem_i += 1) {
14560 const elem_index = try mod.intRef(Type.usize, elem_i);
14686 const elem_index = try pt.intRef(Type.usize, elem_i);
1456114687 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1456214688 const operand_src = block.src(.{ .array_cat_lhs = .{
1456314689 .array_cat_offset = inst_data.src_node,
......@@ -14568,8 +14694,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1456814694 }
1456914695 while (elem_i < result_len) : (elem_i += 1) {
1457014696 const rhs_elem_i = elem_i - lhs_len;
14571 const elem_index = try mod.intRef(Type.usize, elem_i);
14572 const rhs_index = try mod.intRef(Type.usize, rhs_elem_i);
14697 const elem_index = try pt.intRef(Type.usize, elem_i);
14698 const rhs_index = try pt.intRef(Type.usize, rhs_elem_i);
1457314699 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1457414700 const operand_src = block.src(.{ .array_cat_rhs = .{
1457514701 .array_cat_offset = inst_data.src_node,
......@@ -14579,9 +14705,9 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1457914705 try sema.storePtr2(block, src, elem_ptr, src, init, operand_src, .store);
1458014706 }
1458114707 if (res_sent_val) |sent_val| {
14582 const elem_index = try mod.intRef(Type.usize, result_len);
14708 const elem_index = try pt.intRef(Type.usize, result_len);
1458314709 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
14584 const init = Air.internedToRef((try mod.getCoerced(sent_val, lhs_info.elem_type)).toIntern());
14710 const init = Air.internedToRef((try pt.getCoerced(sent_val, lhs_info.elem_type)).toIntern());
1458514711 try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
1458614712 }
1458714713
......@@ -14592,7 +14718,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1459214718 {
1459314719 var elem_i: u32 = 0;
1459414720 while (elem_i < lhs_len) : (elem_i += 1) {
14595 const index = try mod.intRef(Type.usize, elem_i);
14721 const index = try pt.intRef(Type.usize, elem_i);
1459614722 const operand_src = block.src(.{ .array_cat_lhs = .{
1459714723 .array_cat_offset = inst_data.src_node,
1459814724 .elem_index = elem_i,
......@@ -14602,7 +14728,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1460214728 }
1460314729 while (elem_i < result_len) : (elem_i += 1) {
1460414730 const rhs_elem_i = elem_i - lhs_len;
14605 const index = try mod.intRef(Type.usize, rhs_elem_i);
14731 const index = try pt.intRef(Type.usize, rhs_elem_i);
1460614732 const operand_src = block.src(.{ .array_cat_rhs = .{
1460714733 .array_cat_offset = inst_data.src_node,
1460814734 .elem_index = @intCast(rhs_elem_i),
......@@ -14616,7 +14742,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1461614742}
1461714743
1461814744fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref, peer_ty: Type) !?Type.ArrayInfo {
14619 const mod = sema.mod;
14745 const pt = sema.pt;
14746 const mod = pt.zcu;
1462014747 const operand_ty = sema.typeOf(operand);
1462114748 switch (operand_ty.zigTypeTag(mod)) {
1462214749 .Array => return operand_ty.arrayInfo(mod),
......@@ -14633,7 +14760,7 @@ fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Ins
1463314760 .none => null,
1463414761 else => Value.fromInterned(ptr_info.sentinel),
1463514762 },
14636 .len = try val.sliceLen(mod),
14763 .len = try val.sliceLen(pt),
1463714764 };
1463814765 },
1463914766 .One => {
......@@ -14666,7 +14793,8 @@ fn analyzeTupleMul(
1466614793 operand: Air.Inst.Ref,
1466714794 factor: usize,
1466814795) CompileError!Air.Inst.Ref {
14669 const mod = sema.mod;
14796 const pt = sema.pt;
14797 const mod = pt.zcu;
1467014798 const operand_ty = sema.typeOf(operand);
1467114799 const src = block.nodeOffset(src_node);
1467214800 const len_src = block.src(.{ .node_offset_bin_rhs = src_node });
......@@ -14702,14 +14830,14 @@ fn analyzeTupleMul(
1470214830 break :rs runtime_src;
1470314831 };
1470414832
14705 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, .{
14833 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, pt.tid, .{
1470614834 .types = types,
1470714835 .values = values,
1470814836 .names = &.{},
1470914837 });
1471014838
1471114839 const runtime_src = opt_runtime_src orelse {
14712 const tuple_val = try mod.intern(.{ .aggregate = .{
14840 const tuple_val = try pt.intern(.{ .aggregate = .{
1471314841 .ty = tuple_ty,
1471414842 .storage = .{ .elems = values },
1471514843 } });
......@@ -14739,7 +14867,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1473914867 const tracy = trace(@src());
1474014868 defer tracy.end();
1474114869
14742 const mod = sema.mod;
14870 const pt = sema.pt;
14871 const mod = pt.zcu;
1474314872 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1474414873 const extra = sema.code.extraData(Zir.Inst.ArrayMul, inst_data.payload_index).data;
1474514874 const uncoerced_lhs = try sema.resolveInst(extra.lhs);
......@@ -14762,12 +14891,12 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1476214891 const lhs_len = uncoerced_lhs_ty.structFieldCount(mod);
1476314892 const lhs_dest_ty = switch (res_ty.zigTypeTag(mod)) {
1476414893 else => break :no_coerce,
14765 .Array => try mod.arrayType(.{
14894 .Array => try pt.arrayType(.{
1476614895 .child = res_ty.childType(mod).toIntern(),
1476714896 .len = lhs_len,
1476814897 .sentinel = if (res_ty.sentinel(mod)) |s| s.toIntern() else .none,
1476914898 }),
14770 .Vector => try mod.vectorType(.{
14899 .Vector => try pt.vectorType(.{
1477114900 .child = res_ty.childType(mod).toIntern(),
1477214901 .len = lhs_len,
1477314902 }),
......@@ -14796,7 +14925,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1479614925 // Analyze the lhs first, to catch the case that someone tried to do exponentiation
1479714926 const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, lhs_ty) orelse {
1479814927 const msg = msg: {
14799 const msg = try sema.errMsg(lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(mod)});
14928 const msg = try sema.errMsg(lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(pt)});
1480014929 errdefer msg.destroy(sema.gpa);
1480114930 switch (lhs_ty.zigTypeTag(mod)) {
1480214931 .Int, .Float, .ComptimeFloat, .ComptimeInt, .Vector => {
......@@ -14818,7 +14947,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1481814947 return sema.fail(block, rhs_src, "operation results in overflow", .{});
1481914948 const result_len = try sema.usizeCast(block, src, result_len_u64);
1482014949
14821 const result_ty = try mod.arrayType(.{
14950 const result_ty = try pt.arrayType(.{
1482214951 .len = result_len,
1482314952 .sentinel = if (lhs_info.sentinel) |s| s.toIntern() else .none,
1482414953 .child = lhs_info.elem_type.toIntern(),
......@@ -14839,8 +14968,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1483914968 // Optimization for the common pattern of a single element repeated N times, such
1484014969 // as zero-filling a byte array.
1484114970 if (lhs_len == 1 and lhs_info.sentinel == null) {
14842 const elem_val = try lhs_sub_val.elemValue(mod, 0);
14843 break :v try mod.intern(.{ .aggregate = .{
14971 const elem_val = try lhs_sub_val.elemValue(pt, 0);
14972 break :v try pt.intern(.{ .aggregate = .{
1484414973 .ty = result_ty.toIntern(),
1484514974 .storage = .{ .repeated_elem = elem_val.toIntern() },
1484614975 } });
......@@ -14851,12 +14980,12 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1485114980 while (elem_i < result_len) {
1485214981 var lhs_i: usize = 0;
1485314982 while (lhs_i < lhs_len) : (lhs_i += 1) {
14854 const elem_val = try lhs_sub_val.elemValue(mod, lhs_i);
14983 const elem_val = try lhs_sub_val.elemValue(pt, lhs_i);
1485514984 element_vals[elem_i] = elem_val.toIntern();
1485614985 elem_i += 1;
1485714986 }
1485814987 }
14859 break :v try mod.intern(.{ .aggregate = .{
14988 break :v try pt.intern(.{ .aggregate = .{
1486014989 .ty = result_ty.toIntern(),
1486114990 .storage = .{ .elems = element_vals },
1486214991 } });
......@@ -14870,17 +14999,17 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1487014999 // to get the same elem values.
1487115000 const lhs_vals = try sema.arena.alloc(Air.Inst.Ref, lhs_len);
1487215001 for (lhs_vals, 0..) |*lhs_val, idx| {
14873 const idx_ref = try mod.intRef(Type.usize, idx);
15002 const idx_ref = try pt.intRef(Type.usize, idx);
1487415003 lhs_val.* = try sema.elemVal(block, lhs_src, lhs, idx_ref, src, false);
1487515004 }
1487615005
1487715006 if (ptr_addrspace) |ptr_as| {
14878 const alloc_ty = try mod.ptrTypeSema(.{
15007 const alloc_ty = try pt.ptrTypeSema(.{
1487915008 .child = result_ty.toIntern(),
1488015009 .flags = .{ .address_space = ptr_as },
1488115010 });
1488215011 const alloc = try block.addTy(.alloc, alloc_ty);
14883 const elem_ptr_ty = try mod.ptrTypeSema(.{
15012 const elem_ptr_ty = try pt.ptrTypeSema(.{
1488415013 .child = lhs_info.elem_type.toIntern(),
1488515014 .flags = .{ .address_space = ptr_as },
1488615015 });
......@@ -14888,14 +15017,14 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1488815017 var elem_i: usize = 0;
1488915018 while (elem_i < result_len) {
1489015019 for (lhs_vals) |lhs_val| {
14891 const elem_index = try mod.intRef(Type.usize, elem_i);
15020 const elem_index = try pt.intRef(Type.usize, elem_i);
1489215021 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1489315022 try sema.storePtr2(block, src, elem_ptr, src, lhs_val, lhs_src, .store);
1489415023 elem_i += 1;
1489515024 }
1489615025 }
1489715026 if (lhs_info.sentinel) |sent_val| {
14898 const elem_index = try mod.intRef(Type.usize, result_len);
15027 const elem_index = try pt.intRef(Type.usize, result_len);
1489915028 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1490015029 const init = Air.internedToRef(sent_val.toIntern());
1490115030 try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
......@@ -14912,7 +15041,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1491215041}
1491315042
1491415043fn zirNegate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14915 const mod = sema.mod;
15044 const pt = sema.pt;
15045 const mod = pt.zcu;
1491615046 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1491715047 const src = block.nodeOffset(inst_data.src_node);
1491815048 const lhs_src = src;
......@@ -14926,25 +15056,26 @@ fn zirNegate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1492615056 .Int, .ComptimeInt, .Float, .ComptimeFloat => false,
1492715057 else => true,
1492815058 }) {
14929 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(mod)});
15059 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(pt)});
1493015060 }
1493115061
1493215062 if (rhs_scalar_ty.isAnyFloat()) {
1493315063 // We handle float negation here to ensure negative zero is represented in the bits.
1493415064 if (try sema.resolveValue(rhs)) |rhs_val| {
14935 if (rhs_val.isUndef(mod)) return mod.undefRef(rhs_ty);
14936 return Air.internedToRef((try rhs_val.floatNeg(rhs_ty, sema.arena, mod)).toIntern());
15065 if (rhs_val.isUndef(mod)) return pt.undefRef(rhs_ty);
15066 return Air.internedToRef((try rhs_val.floatNeg(rhs_ty, sema.arena, pt)).toIntern());
1493715067 }
1493815068 try sema.requireRuntimeBlock(block, src, null);
1493915069 return block.addUnOp(if (block.float_mode == .optimized) .neg_optimized else .neg, rhs);
1494015070 }
1494115071
14942 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try mod.intValue(rhs_scalar_ty, 0))).toIntern());
15072 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try pt.intValue(rhs_scalar_ty, 0))).toIntern());
1494315073 return sema.analyzeArithmetic(block, .sub, lhs, rhs, src, lhs_src, rhs_src, true);
1494415074}
1494515075
1494615076fn zirNegateWrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14947 const mod = sema.mod;
15077 const pt = sema.pt;
15078 const mod = pt.zcu;
1494815079 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1494915080 const src = block.nodeOffset(inst_data.src_node);
1495015081 const lhs_src = src;
......@@ -14956,10 +15087,10 @@ fn zirNegateWrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1495615087
1495715088 switch (rhs_scalar_ty.zigTypeTag(mod)) {
1495815089 .Int, .ComptimeInt, .Float, .ComptimeFloat => {},
14959 else => return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(mod)}),
15090 else => return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(pt)}),
1496015091 }
1496115092
14962 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try mod.intValue(rhs_scalar_ty, 0))).toIntern());
15093 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try pt.intValue(rhs_scalar_ty, 0))).toIntern());
1496315094 return sema.analyzeArithmetic(block, .subwrap, lhs, rhs, src, lhs_src, rhs_src, true);
1496415095}
1496515096
......@@ -14985,7 +15116,8 @@ fn zirArithmetic(
1498515116}
1498615117
1498715118fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14988 const mod = sema.mod;
15119 const pt = sema.pt;
15120 const mod = pt.zcu;
1498915121 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1499015122 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1499115123 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15026,13 +15158,13 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1502615158 // If lhs % rhs is 0, it doesn't matter.
1502715159 const lhs_val = maybe_lhs_val orelse unreachable;
1502815160 const rhs_val = maybe_rhs_val orelse unreachable;
15029 const rem = lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod) catch unreachable;
15030 if (!rem.compareAllWithZero(.eq, mod)) {
15161 const rem = lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt) catch unreachable;
15162 if (!rem.compareAllWithZero(.eq, pt)) {
1503115163 return sema.fail(
1503215164 block,
1503315165 src,
1503415166 "ambiguous coercion of division operands '{}' and '{}'; non-zero remainder '{}'",
15035 .{ lhs_ty.fmt(mod), rhs_ty.fmt(mod), rem.fmtValue(mod, sema) },
15167 .{ lhs_ty.fmt(pt), rhs_ty.fmt(pt), rem.fmtValue(pt, sema) },
1503615168 );
1503715169 }
1503815170 }
......@@ -15068,10 +15200,10 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1506815200 .Int, .ComptimeInt, .ComptimeFloat => {
1506915201 if (maybe_lhs_val) |lhs_val| {
1507015202 if (!lhs_val.isUndef(mod)) {
15071 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15203 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1507215204 const scalar_zero = switch (scalar_tag) {
15073 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15074 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15205 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15206 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1507515207 else => unreachable,
1507615208 };
1507715209 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15083,7 +15215,7 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1508315215 if (rhs_val.isUndef(mod)) {
1508415216 return sema.failWithUseOfUndef(block, rhs_src);
1508515217 }
15086 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15218 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1508715219 return sema.failWithDivideByZero(block, rhs_src);
1508815220 }
1508915221 // TODO: if the RHS is one, return the LHS directly
......@@ -15097,25 +15229,25 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1509715229 if (lhs_val.isUndef(mod)) {
1509815230 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1509915231 if (maybe_rhs_val) |rhs_val| {
15100 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15101 return mod.undefRef(resolved_type);
15232 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15233 return pt.undefRef(resolved_type);
1510215234 }
1510315235 }
1510415236 return sema.failWithUseOfUndef(block, rhs_src);
1510515237 }
15106 return mod.undefRef(resolved_type);
15238 return pt.undefRef(resolved_type);
1510715239 }
1510815240
1510915241 if (maybe_rhs_val) |rhs_val| {
1511015242 if (is_int) {
1511115243 var overflow_idx: ?usize = null;
15112 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15244 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1511315245 if (overflow_idx) |vec_idx| {
1511415246 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1511515247 }
1511615248 return Air.internedToRef(res.toIntern());
1511715249 } else {
15118 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15250 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1511915251 }
1512015252 } else {
1512115253 break :rs rhs_src;
......@@ -15138,7 +15270,7 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1513815270 block,
1513915271 src,
1514015272 "division with '{}' and '{}': signed integers must use @divTrunc, @divFloor, or @divExact",
15141 .{ lhs_ty.fmt(mod), rhs_ty.fmt(mod) },
15273 .{ lhs_ty.fmt(pt), rhs_ty.fmt(pt) },
1514215274 );
1514315275 }
1514415276 break :blk Air.Inst.Tag.div_trunc;
......@@ -15150,7 +15282,8 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1515015282}
1515115283
1515215284fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15153 const mod = sema.mod;
15285 const pt = sema.pt;
15286 const mod = pt.zcu;
1515415287 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1515515288 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1515615289 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15204,10 +15337,10 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1520415337 if (lhs_val.isUndef(mod)) {
1520515338 return sema.failWithUseOfUndef(block, rhs_src);
1520615339 } else {
15207 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15340 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1520815341 const scalar_zero = switch (scalar_tag) {
15209 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15210 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15342 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15343 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1521115344 else => unreachable,
1521215345 };
1521315346 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15219,7 +15352,7 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1521915352 if (rhs_val.isUndef(mod)) {
1522015353 return sema.failWithUseOfUndef(block, rhs_src);
1522115354 }
15222 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15355 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1522315356 return sema.failWithDivideByZero(block, rhs_src);
1522415357 }
1522515358 // TODO: if the RHS is one, return the LHS directly
......@@ -15227,22 +15360,22 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1522715360 if (maybe_lhs_val) |lhs_val| {
1522815361 if (maybe_rhs_val) |rhs_val| {
1522915362 if (is_int) {
15230 const modulus_val = try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod);
15231 if (!(modulus_val.compareAllWithZero(.eq, mod))) {
15363 const modulus_val = try lhs_val.intMod(rhs_val, resolved_type, sema.arena, pt);
15364 if (!(modulus_val.compareAllWithZero(.eq, pt))) {
1523215365 return sema.fail(block, src, "exact division produced remainder", .{});
1523315366 }
1523415367 var overflow_idx: ?usize = null;
15235 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15368 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1523615369 if (overflow_idx) |vec_idx| {
1523715370 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1523815371 }
1523915372 return Air.internedToRef(res.toIntern());
1524015373 } else {
15241 const modulus_val = try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod);
15242 if (!(modulus_val.compareAllWithZero(.eq, mod))) {
15374 const modulus_val = try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, pt);
15375 if (!(modulus_val.compareAllWithZero(.eq, pt))) {
1524315376 return sema.fail(block, src, "exact division produced remainder", .{});
1524415377 }
15245 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15378 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1524615379 }
1524715380 } else break :rs rhs_src;
1524815381 } else break :rs lhs_src;
......@@ -15286,8 +15419,8 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1528615419 const remainder = try block.addBinOp(.rem, casted_lhs, casted_rhs);
1528715420
1528815421 const scalar_zero = switch (scalar_tag) {
15289 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15290 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15422 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15423 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1529115424 else => unreachable,
1529215425 };
1529315426 if (resolved_type.zigTypeTag(mod) == .Vector) {
......@@ -15315,7 +15448,8 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1531515448}
1531615449
1531715450fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15318 const mod = sema.mod;
15451 const pt = sema.pt;
15452 const mod = pt.zcu;
1531915453 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1532015454 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1532115455 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15371,10 +15505,10 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1537115505 // If the lhs is undefined, result is undefined.
1537215506 if (maybe_lhs_val) |lhs_val| {
1537315507 if (!lhs_val.isUndef(mod)) {
15374 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15508 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1537515509 const scalar_zero = switch (scalar_tag) {
15376 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15377 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15510 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15511 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1537815512 else => unreachable,
1537915513 };
1538015514 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15386,7 +15520,7 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1538615520 if (rhs_val.isUndef(mod)) {
1538715521 return sema.failWithUseOfUndef(block, rhs_src);
1538815522 }
15389 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15523 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1539015524 return sema.failWithDivideByZero(block, rhs_src);
1539115525 }
1539215526 // TODO: if the RHS is one, return the LHS directly
......@@ -15395,20 +15529,20 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1539515529 if (lhs_val.isUndef(mod)) {
1539615530 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1539715531 if (maybe_rhs_val) |rhs_val| {
15398 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15399 return mod.undefRef(resolved_type);
15532 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15533 return pt.undefRef(resolved_type);
1540015534 }
1540115535 }
1540215536 return sema.failWithUseOfUndef(block, rhs_src);
1540315537 }
15404 return mod.undefRef(resolved_type);
15538 return pt.undefRef(resolved_type);
1540515539 }
1540615540
1540715541 if (maybe_rhs_val) |rhs_val| {
1540815542 if (is_int) {
15409 return Air.internedToRef((try lhs_val.intDivFloor(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15543 return Air.internedToRef((try lhs_val.intDivFloor(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1541015544 } else {
15411 return Air.internedToRef((try lhs_val.floatDivFloor(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15545 return Air.internedToRef((try lhs_val.floatDivFloor(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1541215546 }
1541315547 } else break :rs rhs_src;
1541415548 } else break :rs lhs_src;
......@@ -15425,7 +15559,8 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1542515559}
1542615560
1542715561fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15428 const mod = sema.mod;
15562 const pt = sema.pt;
15563 const mod = pt.zcu;
1542915564 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1543015565 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1543115566 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15481,10 +15616,10 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1548115616 // If the lhs is undefined, result is undefined.
1548215617 if (maybe_lhs_val) |lhs_val| {
1548315618 if (!lhs_val.isUndef(mod)) {
15484 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15619 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1548515620 const scalar_zero = switch (scalar_tag) {
15486 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15487 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15621 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15622 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1548815623 else => unreachable,
1548915624 };
1549015625 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15496,7 +15631,7 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1549615631 if (rhs_val.isUndef(mod)) {
1549715632 return sema.failWithUseOfUndef(block, rhs_src);
1549815633 }
15499 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15634 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1550015635 return sema.failWithDivideByZero(block, rhs_src);
1550115636 }
1550215637 }
......@@ -15504,25 +15639,25 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1550415639 if (lhs_val.isUndef(mod)) {
1550515640 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1550615641 if (maybe_rhs_val) |rhs_val| {
15507 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15508 return mod.undefRef(resolved_type);
15642 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15643 return pt.undefRef(resolved_type);
1550915644 }
1551015645 }
1551115646 return sema.failWithUseOfUndef(block, rhs_src);
1551215647 }
15513 return mod.undefRef(resolved_type);
15648 return pt.undefRef(resolved_type);
1551415649 }
1551515650
1551615651 if (maybe_rhs_val) |rhs_val| {
1551715652 if (is_int) {
1551815653 var overflow_idx: ?usize = null;
15519 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15654 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1552015655 if (overflow_idx) |vec_idx| {
1552115656 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1552215657 }
1552315658 return Air.internedToRef(res.toIntern());
1552415659 } else {
15525 return Air.internedToRef((try lhs_val.floatDivTrunc(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15660 return Air.internedToRef((try lhs_val.floatDivTrunc(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1552615661 }
1552715662 } else break :rs rhs_src;
1552815663 } else break :rs lhs_src;
......@@ -15550,7 +15685,8 @@ fn addDivIntOverflowSafety(
1555015685 casted_rhs: Air.Inst.Ref,
1555115686 is_int: bool,
1555215687) CompileError!void {
15553 const mod = sema.mod;
15688 const pt = sema.pt;
15689 const mod = pt.zcu;
1555415690 if (!is_int) return;
1555515691
1555615692 // If the LHS is unsigned, it cannot cause overflow.
......@@ -15561,19 +15697,19 @@ fn addDivIntOverflowSafety(
1556115697 return;
1556215698 }
1556315699
15564 const min_int = try resolved_type.minInt(mod, resolved_type);
15565 const neg_one_scalar = try mod.intValue(lhs_scalar_ty, -1);
15700 const min_int = try resolved_type.minInt(pt, resolved_type);
15701 const neg_one_scalar = try pt.intValue(lhs_scalar_ty, -1);
1556615702 const neg_one = try sema.splat(resolved_type, neg_one_scalar);
1556715703
1556815704 // If the LHS is comptime-known to be not equal to the min int,
1556915705 // no overflow is possible.
1557015706 if (maybe_lhs_val) |lhs_val| {
15571 if (try lhs_val.compareAll(.neq, min_int, resolved_type, mod)) return;
15707 if (try lhs_val.compareAll(.neq, min_int, resolved_type, pt)) return;
1557215708 }
1557315709
1557415710 // If the RHS is comptime-known to not be equal to -1, no overflow is possible.
1557515711 if (maybe_rhs_val) |rhs_val| {
15576 if (try rhs_val.compareAll(.neq, neg_one, resolved_type, mod)) return;
15712 if (try rhs_val.compareAll(.neq, neg_one, resolved_type, pt)) return;
1557715713 }
1557815714
1557915715 var ok: Air.Inst.Ref = .none;
......@@ -15634,11 +15770,12 @@ fn addDivByZeroSafety(
1563415770 // emitted above.
1563515771 if (maybe_rhs_val != null) return;
1563615772
15637 const mod = sema.mod;
15773 const pt = sema.pt;
15774 const mod = pt.zcu;
1563815775 const scalar_zero = if (is_int)
15639 try mod.intValue(resolved_type.scalarType(mod), 0)
15776 try pt.intValue(resolved_type.scalarType(mod), 0)
1564015777 else
15641 try mod.floatValue(resolved_type.scalarType(mod), 0.0);
15778 try pt.floatValue(resolved_type.scalarType(mod), 0.0);
1564215779 const ok = if (resolved_type.zigTypeTag(mod) == .Vector) ok: {
1564315780 const zero_val = try sema.splat(resolved_type, scalar_zero);
1564415781 const zero = Air.internedToRef(zero_val.toIntern());
......@@ -15666,7 +15803,8 @@ fn airTag(block: *Block, is_int: bool, normal: Air.Inst.Tag, optimized: Air.Inst
1566615803}
1566715804
1566815805fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15669 const mod = sema.mod;
15806 const pt = sema.pt;
15807 const mod = pt.zcu;
1567015808 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1567115809 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1567215810 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15721,16 +15859,16 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1572115859 if (lhs_val.isUndef(mod)) {
1572215860 return sema.failWithUseOfUndef(block, lhs_src);
1572315861 }
15724 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15862 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1572515863 const scalar_zero = switch (scalar_tag) {
15726 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15727 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15864 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15865 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1572815866 else => unreachable,
1572915867 };
15730 const zero_val = if (is_vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
15868 const zero_val = if (is_vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
1573115869 .ty = resolved_type.toIntern(),
1573215870 .storage = .{ .repeated_elem = scalar_zero.toIntern() },
15733 } }))) else scalar_zero;
15871 } })) else scalar_zero;
1573415872 return Air.internedToRef(zero_val.toIntern());
1573515873 }
1573615874 } else if (lhs_scalar_ty.isSignedInt(mod)) {
......@@ -15740,18 +15878,18 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1574015878 if (rhs_val.isUndef(mod)) {
1574115879 return sema.failWithUseOfUndef(block, rhs_src);
1574215880 }
15743 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15881 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1574415882 return sema.failWithDivideByZero(block, rhs_src);
1574515883 }
15746 if (!(try rhs_val.compareAllWithZeroSema(.gte, mod))) {
15884 if (!(try rhs_val.compareAllWithZeroSema(.gte, pt))) {
1574715885 return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
1574815886 }
1574915887 if (maybe_lhs_val) |lhs_val| {
1575015888 const rem_result = try sema.intRem(resolved_type, lhs_val, rhs_val);
1575115889 // If this answer could possibly be different by doing `intMod`,
1575215890 // we must emit a compile error. Otherwise, it's OK.
15753 if (!(try lhs_val.compareAllWithZeroSema(.gte, mod)) and
15754 !(try rem_result.compareAllWithZeroSema(.eq, mod)))
15891 if (!(try lhs_val.compareAllWithZeroSema(.gte, pt)) and
15892 !(try rem_result.compareAllWithZeroSema(.eq, pt)))
1575515893 {
1575615894 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1575715895 }
......@@ -15769,17 +15907,17 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1576915907 if (rhs_val.isUndef(mod)) {
1577015908 return sema.failWithUseOfUndef(block, rhs_src);
1577115909 }
15772 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15910 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1577315911 return sema.failWithDivideByZero(block, rhs_src);
1577415912 }
15775 if (!(try rhs_val.compareAllWithZeroSema(.gte, mod))) {
15913 if (!(try rhs_val.compareAllWithZeroSema(.gte, pt))) {
1577615914 return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
1577715915 }
1577815916 if (maybe_lhs_val) |lhs_val| {
15779 if (lhs_val.isUndef(mod) or !(try lhs_val.compareAllWithZeroSema(.gte, mod))) {
15917 if (lhs_val.isUndef(mod) or !(try lhs_val.compareAllWithZeroSema(.gte, pt))) {
1578015918 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1578115919 }
15782 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15920 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1578315921 } else {
1578415922 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1578515923 }
......@@ -15804,31 +15942,32 @@ fn intRem(
1580415942 lhs: Value,
1580515943 rhs: Value,
1580615944) CompileError!Value {
15807 const mod = sema.mod;
15945 const pt = sema.pt;
15946 const mod = pt.zcu;
1580815947 if (ty.zigTypeTag(mod) == .Vector) {
1580915948 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
1581015949 const scalar_ty = ty.scalarType(mod);
1581115950 for (result_data, 0..) |*scalar, i| {
15812 const lhs_elem = try lhs.elemValue(mod, i);
15813 const rhs_elem = try rhs.elemValue(mod, i);
15951 const lhs_elem = try lhs.elemValue(pt, i);
15952 const rhs_elem = try rhs.elemValue(pt, i);
1581415953 scalar.* = (try sema.intRemScalar(lhs_elem, rhs_elem, scalar_ty)).toIntern();
1581515954 }
15816 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
15955 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
1581715956 .ty = ty.toIntern(),
1581815957 .storage = .{ .elems = result_data },
15819 } })));
15958 } }));
1582015959 }
1582115960 return sema.intRemScalar(lhs, rhs, ty);
1582215961}
1582315962
1582415963fn intRemScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) CompileError!Value {
15825 const mod = sema.mod;
15964 const pt = sema.pt;
1582615965 // TODO is this a performance issue? maybe we should try the operation without
1582715966 // resorting to BigInt first.
1582815967 var lhs_space: Value.BigIntSpace = undefined;
1582915968 var rhs_space: Value.BigIntSpace = undefined;
15830 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
15831 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
15969 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
15970 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
1583215971 const limbs_q = try sema.arena.alloc(
1583315972 math.big.Limb,
1583415973 lhs_bigint.limbs.len,
......@@ -15846,11 +15985,12 @@ fn intRemScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) CompileErr
1584615985 var result_q = math.big.int.Mutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
1584715986 var result_r = math.big.int.Mutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
1584815987 result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
15849 return mod.intValue_big(scalar_ty, result_r.toConst());
15988 return pt.intValue_big(scalar_ty, result_r.toConst());
1585015989}
1585115990
1585215991fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15853 const mod = sema.mod;
15992 const pt = sema.pt;
15993 const mod = pt.zcu;
1585415994 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1585515995 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1585615996 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15904,11 +16044,11 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1590416044 if (rhs_val.isUndef(mod)) {
1590516045 return sema.failWithUseOfUndef(block, rhs_src);
1590616046 }
15907 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16047 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1590816048 return sema.failWithDivideByZero(block, rhs_src);
1590916049 }
1591016050 if (maybe_lhs_val) |lhs_val| {
15911 return Air.internedToRef((try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16051 return Air.internedToRef((try lhs_val.intMod(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1591216052 }
1591316053 break :rs lhs_src;
1591416054 } else {
......@@ -15920,16 +16060,16 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1592016060 if (rhs_val.isUndef(mod)) {
1592116061 return sema.failWithUseOfUndef(block, rhs_src);
1592216062 }
15923 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16063 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1592416064 return sema.failWithDivideByZero(block, rhs_src);
1592516065 }
1592616066 }
1592716067 if (maybe_lhs_val) |lhs_val| {
1592816068 if (lhs_val.isUndef(mod)) {
15929 return mod.undefRef(resolved_type);
16069 return pt.undefRef(resolved_type);
1593016070 }
1593116071 if (maybe_rhs_val) |rhs_val| {
15932 return Air.internedToRef((try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16072 return Air.internedToRef((try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1593316073 } else break :rs rhs_src;
1593416074 } else break :rs lhs_src;
1593516075 };
......@@ -15945,7 +16085,8 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1594516085}
1594616086
1594716087fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15948 const mod = sema.mod;
16088 const pt = sema.pt;
16089 const mod = pt.zcu;
1594916090 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1595016091 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1595116092 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15999,7 +16140,7 @@ fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1599916140 if (rhs_val.isUndef(mod)) {
1600016141 return sema.failWithUseOfUndef(block, rhs_src);
1600116142 }
16002 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16143 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1600316144 return sema.failWithDivideByZero(block, rhs_src);
1600416145 }
1600516146 if (maybe_lhs_val) |lhs_val| {
......@@ -16015,16 +16156,16 @@ fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1601516156 if (rhs_val.isUndef(mod)) {
1601616157 return sema.failWithUseOfUndef(block, rhs_src);
1601716158 }
16018 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16159 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1601916160 return sema.failWithDivideByZero(block, rhs_src);
1602016161 }
1602116162 }
1602216163 if (maybe_lhs_val) |lhs_val| {
1602316164 if (lhs_val.isUndef(mod)) {
16024 return mod.undefRef(resolved_type);
16165 return pt.undefRef(resolved_type);
1602516166 }
1602616167 if (maybe_rhs_val) |rhs_val| {
16027 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16168 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1602816169 } else break :rs rhs_src;
1602916170 } else break :rs lhs_src;
1603016171 };
......@@ -16059,7 +16200,8 @@ fn zirOverflowArithmetic(
1605916200
1606016201 const lhs_ty = sema.typeOf(uncasted_lhs);
1606116202 const rhs_ty = sema.typeOf(uncasted_rhs);
16062 const mod = sema.mod;
16203 const pt = sema.pt;
16204 const mod = pt.zcu;
1606316205 const ip = &mod.intern_pool;
1606416206
1606516207 try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
......@@ -16081,7 +16223,7 @@ fn zirOverflowArithmetic(
1608116223 const rhs = try sema.coerce(block, rhs_dest_ty, uncasted_rhs, rhs_src);
1608216224
1608316225 if (dest_ty.scalarType(mod).zigTypeTag(mod) != .Int) {
16084 return sema.fail(block, src, "expected vector of integers or integer tag type, found '{}'", .{dest_ty.fmt(mod)});
16226 return sema.fail(block, src, "expected vector of integers or integer tag type, found '{}'", .{dest_ty.fmt(pt)});
1608516227 }
1608616228
1608716229 const maybe_lhs_val = try sema.resolveValue(lhs);
......@@ -16095,19 +16237,19 @@ fn zirOverflowArithmetic(
1609516237 wrapped: Value = Value.@"unreachable",
1609616238 overflow_bit: Value,
1609716239 } = result: {
16098 const zero_bit = try mod.intValue(Type.u1, 0);
16240 const zero_bit = try pt.intValue(Type.u1, 0);
1609916241 switch (zir_tag) {
1610016242 .add_with_overflow => {
1610116243 // If either of the arguments is zero, `false` is returned and the other is stored
1610216244 // to the result, even if it is undefined..
1610316245 // Otherwise, if either of the argument is undefined, undefined is returned.
1610416246 if (maybe_lhs_val) |lhs_val| {
16105 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16247 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1610616248 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
1610716249 }
1610816250 }
1610916251 if (maybe_rhs_val) |rhs_val| {
16110 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, mod))) {
16252 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, pt))) {
1611116253 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1611216254 }
1611316255 }
......@@ -16128,7 +16270,7 @@ fn zirOverflowArithmetic(
1612816270 if (maybe_rhs_val) |rhs_val| {
1612916271 if (rhs_val.isUndef(mod)) {
1613016272 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
16131 } else if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16273 } else if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1613216274 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1613316275 } else if (maybe_lhs_val) |lhs_val| {
1613416276 if (lhs_val.isUndef(mod)) {
......@@ -16144,10 +16286,10 @@ fn zirOverflowArithmetic(
1614416286 // If either of the arguments is zero, the result is zero and no overflow occured.
1614516287 // If either of the arguments is one, the result is the other and no overflow occured.
1614616288 // Otherwise, if either of the arguments is undefined, both results are undefined.
16147 const scalar_one = try mod.intValue(dest_ty.scalarType(mod), 1);
16289 const scalar_one = try pt.intValue(dest_ty.scalarType(mod), 1);
1614816290 if (maybe_lhs_val) |lhs_val| {
1614916291 if (!lhs_val.isUndef(mod)) {
16150 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16292 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1615116293 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1615216294 } else if (try sema.compareAll(lhs_val, .eq, try sema.splat(dest_ty, scalar_one), dest_ty)) {
1615316295 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
......@@ -16157,7 +16299,7 @@ fn zirOverflowArithmetic(
1615716299
1615816300 if (maybe_rhs_val) |rhs_val| {
1615916301 if (!rhs_val.isUndef(mod)) {
16160 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16302 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1616116303 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
1616216304 } else if (try sema.compareAll(rhs_val, .eq, try sema.splat(dest_ty, scalar_one), dest_ty)) {
1616316305 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
......@@ -16171,7 +16313,7 @@ fn zirOverflowArithmetic(
1617116313 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
1617216314 }
1617316315
16174 const result = try lhs_val.intMulWithOverflow(rhs_val, dest_ty, sema.arena, mod);
16316 const result = try lhs_val.intMulWithOverflow(rhs_val, dest_ty, sema.arena, pt);
1617516317 break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
1617616318 }
1617716319 }
......@@ -16181,12 +16323,12 @@ fn zirOverflowArithmetic(
1618116323 // If rhs is zero, the result is lhs (even if undefined) and no overflow occurred.
1618216324 // Oterhwise if either of the arguments is undefined, both results are undefined.
1618316325 if (maybe_lhs_val) |lhs_val| {
16184 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16326 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1618516327 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1618616328 }
1618716329 }
1618816330 if (maybe_rhs_val) |rhs_val| {
16189 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, mod))) {
16331 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, pt))) {
1619016332 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1619116333 }
1619216334 }
......@@ -16196,7 +16338,7 @@ fn zirOverflowArithmetic(
1619616338 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
1619716339 }
1619816340
16199 const result = try lhs_val.shlWithOverflow(rhs_val, dest_ty, sema.arena, mod);
16341 const result = try lhs_val.shlWithOverflow(rhs_val, dest_ty, sema.arena, pt);
1620016342 break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
1620116343 }
1620216344 }
......@@ -16235,7 +16377,7 @@ fn zirOverflowArithmetic(
1623516377 }
1623616378
1623716379 if (result.inst == .none) {
16238 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
16380 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1623916381 .ty = tuple_ty.toIntern(),
1624016382 .storage = .{ .elems = &.{
1624116383 result.wrapped.toIntern(),
......@@ -16251,9 +16393,10 @@ fn zirOverflowArithmetic(
1625116393}
1625216394
1625316395fn splat(sema: *Sema, ty: Type, val: Value) !Value {
16254 const mod = sema.mod;
16396 const pt = sema.pt;
16397 const mod = pt.zcu;
1625516398 if (ty.zigTypeTag(mod) != .Vector) return val;
16256 const repeated = try mod.intern(.{ .aggregate = .{
16399 const repeated = try pt.intern(.{ .aggregate = .{
1625716400 .ty = ty.toIntern(),
1625816401 .storage = .{ .repeated_elem = val.toIntern() },
1625916402 } });
......@@ -16261,16 +16404,17 @@ fn splat(sema: *Sema, ty: Type, val: Value) !Value {
1626116404}
1626216405
1626316406fn overflowArithmeticTupleType(sema: *Sema, ty: Type) !Type {
16264 const mod = sema.mod;
16407 const pt = sema.pt;
16408 const mod = pt.zcu;
1626516409 const ip = &mod.intern_pool;
16266 const ov_ty = if (ty.zigTypeTag(mod) == .Vector) try mod.vectorType(.{
16410 const ov_ty = if (ty.zigTypeTag(mod) == .Vector) try pt.vectorType(.{
1626716411 .len = ty.vectorLen(mod),
1626816412 .child = .u1_type,
1626916413 }) else Type.u1;
1627016414
1627116415 const types = [2]InternPool.Index{ ty.toIntern(), ov_ty.toIntern() };
1627216416 const values = [2]InternPool.Index{ .none, .none };
16273 const tuple_ty = try ip.getAnonStructType(mod.gpa, .{
16417 const tuple_ty = try ip.getAnonStructType(mod.gpa, pt.tid, .{
1627416418 .types = &types,
1627516419 .values = &values,
1627616420 .names = &.{},
......@@ -16290,7 +16434,8 @@ fn analyzeArithmetic(
1629016434 rhs_src: LazySrcLoc,
1629116435 want_safety: bool,
1629216436) CompileError!Air.Inst.Ref {
16293 const mod = sema.mod;
16437 const pt = sema.pt;
16438 const mod = pt.zcu;
1629416439 const lhs_ty = sema.typeOf(lhs);
1629516440 const rhs_ty = sema.typeOf(rhs);
1629616441 const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison(mod);
......@@ -16337,7 +16482,7 @@ fn analyzeArithmetic(
1633716482 // overflow (max_int), causing illegal behavior.
1633816483 // For floats: either operand being undef makes the result undef.
1633916484 if (maybe_lhs_val) |lhs_val| {
16340 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16485 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1634116486 return casted_rhs;
1634216487 }
1634316488 }
......@@ -16346,10 +16491,10 @@ fn analyzeArithmetic(
1634616491 if (is_int) {
1634716492 return sema.failWithUseOfUndef(block, rhs_src);
1634816493 } else {
16349 return mod.undefRef(resolved_type);
16494 return pt.undefRef(resolved_type);
1635016495 }
1635116496 }
16352 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16497 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1635316498 return casted_lhs;
1635416499 }
1635516500 }
......@@ -16359,7 +16504,7 @@ fn analyzeArithmetic(
1635916504 if (is_int) {
1636016505 return sema.failWithUseOfUndef(block, lhs_src);
1636116506 } else {
16362 return mod.undefRef(resolved_type);
16507 return pt.undefRef(resolved_type);
1636316508 }
1636416509 }
1636516510 if (maybe_rhs_val) |rhs_val| {
......@@ -16371,7 +16516,7 @@ fn analyzeArithmetic(
1637116516 }
1637216517 return Air.internedToRef(sum.toIntern());
1637316518 } else {
16374 return Air.internedToRef((try Value.floatAdd(lhs_val, rhs_val, resolved_type, sema.arena, mod)).toIntern());
16519 return Air.internedToRef((try Value.floatAdd(lhs_val, rhs_val, resolved_type, sema.arena, pt)).toIntern());
1637516520 }
1637616521 } else break :rs .{ rhs_src, air_tag, .add_safe };
1637716522 } else break :rs .{ lhs_src, air_tag, .add_safe };
......@@ -16381,15 +16526,15 @@ fn analyzeArithmetic(
1638116526 // If either of the operands are zero, the other operand is returned.
1638216527 // If either of the operands are undefined, the result is undefined.
1638316528 if (maybe_lhs_val) |lhs_val| {
16384 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16529 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1638516530 return casted_rhs;
1638616531 }
1638716532 }
1638816533 if (maybe_rhs_val) |rhs_val| {
1638916534 if (rhs_val.isUndef(mod)) {
16390 return mod.undefRef(resolved_type);
16535 return pt.undefRef(resolved_type);
1639116536 }
16392 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16537 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1639316538 return casted_lhs;
1639416539 }
1639516540 if (maybe_lhs_val) |lhs_val| {
......@@ -16402,26 +16547,26 @@ fn analyzeArithmetic(
1640216547 // If either of the operands are zero, then the other operand is returned.
1640316548 // If either of the operands are undefined, the result is undefined.
1640416549 if (maybe_lhs_val) |lhs_val| {
16405 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16550 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1640616551 return casted_rhs;
1640716552 }
1640816553 }
1640916554 if (maybe_rhs_val) |rhs_val| {
1641016555 if (rhs_val.isUndef(mod)) {
16411 return mod.undefRef(resolved_type);
16556 return pt.undefRef(resolved_type);
1641216557 }
16413 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16558 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1641416559 return casted_lhs;
1641516560 }
1641616561 if (maybe_lhs_val) |lhs_val| {
1641716562 if (lhs_val.isUndef(mod)) {
16418 return mod.undefRef(resolved_type);
16563 return pt.undefRef(resolved_type);
1641916564 }
1642016565
1642116566 const val = if (scalar_tag == .ComptimeInt)
1642216567 try sema.intAdd(lhs_val, rhs_val, resolved_type, undefined)
1642316568 else
16424 try lhs_val.intAddSat(rhs_val, resolved_type, sema.arena, mod);
16569 try lhs_val.intAddSat(rhs_val, resolved_type, sema.arena, pt);
1642516570
1642616571 return Air.internedToRef(val.toIntern());
1642716572 } else break :rs .{
......@@ -16448,10 +16593,10 @@ fn analyzeArithmetic(
1644816593 if (is_int) {
1644916594 return sema.failWithUseOfUndef(block, rhs_src);
1645016595 } else {
16451 return mod.undefRef(resolved_type);
16596 return pt.undefRef(resolved_type);
1645216597 }
1645316598 }
16454 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16599 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1645516600 return casted_lhs;
1645616601 }
1645716602 }
......@@ -16461,7 +16606,7 @@ fn analyzeArithmetic(
1646116606 if (is_int) {
1646216607 return sema.failWithUseOfUndef(block, lhs_src);
1646316608 } else {
16464 return mod.undefRef(resolved_type);
16609 return pt.undefRef(resolved_type);
1646516610 }
1646616611 }
1646716612 if (maybe_rhs_val) |rhs_val| {
......@@ -16473,7 +16618,7 @@ fn analyzeArithmetic(
1647316618 }
1647416619 return Air.internedToRef(diff.toIntern());
1647516620 } else {
16476 return Air.internedToRef((try Value.floatSub(lhs_val, rhs_val, resolved_type, sema.arena, mod)).toIntern());
16621 return Air.internedToRef((try Value.floatSub(lhs_val, rhs_val, resolved_type, sema.arena, pt)).toIntern());
1647716622 }
1647816623 } else break :rs .{ rhs_src, air_tag, .sub_safe };
1647916624 } else break :rs .{ lhs_src, air_tag, .sub_safe };
......@@ -16484,15 +16629,15 @@ fn analyzeArithmetic(
1648416629 // If either of the operands are undefined, the result is undefined.
1648516630 if (maybe_rhs_val) |rhs_val| {
1648616631 if (rhs_val.isUndef(mod)) {
16487 return mod.undefRef(resolved_type);
16632 return pt.undefRef(resolved_type);
1648816633 }
16489 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16634 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1649016635 return casted_lhs;
1649116636 }
1649216637 }
1649316638 if (maybe_lhs_val) |lhs_val| {
1649416639 if (lhs_val.isUndef(mod)) {
16495 return mod.undefRef(resolved_type);
16640 return pt.undefRef(resolved_type);
1649616641 }
1649716642 if (maybe_rhs_val) |rhs_val| {
1649816643 return Air.internedToRef((try sema.numberSubWrapScalar(lhs_val, rhs_val, resolved_type)).toIntern());
......@@ -16505,21 +16650,21 @@ fn analyzeArithmetic(
1650516650 // If either of the operands are undefined, the result is undefined.
1650616651 if (maybe_rhs_val) |rhs_val| {
1650716652 if (rhs_val.isUndef(mod)) {
16508 return mod.undefRef(resolved_type);
16653 return pt.undefRef(resolved_type);
1650916654 }
16510 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16655 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1651116656 return casted_lhs;
1651216657 }
1651316658 }
1651416659 if (maybe_lhs_val) |lhs_val| {
1651516660 if (lhs_val.isUndef(mod)) {
16516 return mod.undefRef(resolved_type);
16661 return pt.undefRef(resolved_type);
1651716662 }
1651816663 if (maybe_rhs_val) |rhs_val| {
1651916664 const val = if (scalar_tag == .ComptimeInt)
1652016665 try sema.intSub(lhs_val, rhs_val, resolved_type, undefined)
1652116666 else
16522 try lhs_val.intSubSat(rhs_val, resolved_type, sema.arena, mod);
16667 try lhs_val.intSubSat(rhs_val, resolved_type, sema.arena, pt);
1652316668
1652416669 return Air.internedToRef(val.toIntern());
1652516670 } else break :rs .{ rhs_src, .sub_sat, .sub_sat };
......@@ -16540,13 +16685,13 @@ fn analyzeArithmetic(
1654016685 // the result is nan.
1654116686 // If either of the operands are nan, the result is nan.
1654216687 const scalar_zero = switch (scalar_tag) {
16543 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16544 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16688 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16689 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1654516690 else => unreachable,
1654616691 };
1654716692 const scalar_one = switch (scalar_tag) {
16548 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16549 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16693 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16694 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1655016695 else => unreachable,
1655116696 };
1655216697 if (maybe_lhs_val) |lhs_val| {
......@@ -16554,13 +16699,13 @@ fn analyzeArithmetic(
1655416699 if (lhs_val.isNan(mod)) {
1655516700 return Air.internedToRef(lhs_val.toIntern());
1655616701 }
16557 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) lz: {
16702 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) lz: {
1655816703 if (maybe_rhs_val) |rhs_val| {
1655916704 if (rhs_val.isNan(mod)) {
1656016705 return Air.internedToRef(rhs_val.toIntern());
1656116706 }
1656216707 if (rhs_val.isInf(mod)) {
16563 return Air.internedToRef((try mod.floatValue(resolved_type, std.math.nan(f128))).toIntern());
16708 return Air.internedToRef((try pt.floatValue(resolved_type, std.math.nan(f128))).toIntern());
1656416709 }
1656516710 } else if (resolved_type.isAnyFloat()) {
1656616711 break :lz;
......@@ -16579,16 +16724,16 @@ fn analyzeArithmetic(
1657916724 if (is_int) {
1658016725 return sema.failWithUseOfUndef(block, rhs_src);
1658116726 } else {
16582 return mod.undefRef(resolved_type);
16727 return pt.undefRef(resolved_type);
1658316728 }
1658416729 }
1658516730 if (rhs_val.isNan(mod)) {
1658616731 return Air.internedToRef(rhs_val.toIntern());
1658716732 }
16588 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) rz: {
16733 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) rz: {
1658916734 if (maybe_lhs_val) |lhs_val| {
1659016735 if (lhs_val.isInf(mod)) {
16591 return Air.internedToRef((try mod.floatValue(resolved_type, std.math.nan(f128))).toIntern());
16736 return Air.internedToRef((try pt.floatValue(resolved_type, std.math.nan(f128))).toIntern());
1659216737 }
1659316738 } else if (resolved_type.isAnyFloat()) {
1659416739 break :rz;
......@@ -16604,18 +16749,18 @@ fn analyzeArithmetic(
1660416749 if (is_int) {
1660516750 return sema.failWithUseOfUndef(block, lhs_src);
1660616751 } else {
16607 return mod.undefRef(resolved_type);
16752 return pt.undefRef(resolved_type);
1660816753 }
1660916754 }
1661016755 if (is_int) {
1661116756 var overflow_idx: ?usize = null;
16612 const product = try lhs_val.intMul(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
16757 const product = try lhs_val.intMul(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1661316758 if (overflow_idx) |vec_idx| {
1661416759 return sema.failWithIntegerOverflow(block, src, resolved_type, product, vec_idx);
1661516760 }
1661616761 return Air.internedToRef(product.toIntern());
1661716762 } else {
16618 return Air.internedToRef((try lhs_val.floatMul(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16763 return Air.internedToRef((try lhs_val.floatMul(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1661916764 }
1662016765 } else break :rs .{ lhs_src, air_tag, .mul_safe };
1662116766 } else break :rs .{ rhs_src, air_tag, .mul_safe };
......@@ -16626,18 +16771,18 @@ fn analyzeArithmetic(
1662616771 // If either of the operands are one, result is the other operand.
1662716772 // If either of the operands are undefined, result is undefined.
1662816773 const scalar_zero = switch (scalar_tag) {
16629 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16630 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16774 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16775 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1663116776 else => unreachable,
1663216777 };
1663316778 const scalar_one = switch (scalar_tag) {
16634 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16635 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16779 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16780 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1663616781 else => unreachable,
1663716782 };
1663816783 if (maybe_lhs_val) |lhs_val| {
1663916784 if (!lhs_val.isUndef(mod)) {
16640 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16785 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1664116786 const zero_val = try sema.splat(resolved_type, scalar_zero);
1664216787 return Air.internedToRef(zero_val.toIntern());
1664316788 }
......@@ -16648,9 +16793,9 @@ fn analyzeArithmetic(
1664816793 }
1664916794 if (maybe_rhs_val) |rhs_val| {
1665016795 if (rhs_val.isUndef(mod)) {
16651 return mod.undefRef(resolved_type);
16796 return pt.undefRef(resolved_type);
1665216797 }
16653 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16798 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1665416799 const zero_val = try sema.splat(resolved_type, scalar_zero);
1665516800 return Air.internedToRef(zero_val.toIntern());
1665616801 }
......@@ -16659,9 +16804,9 @@ fn analyzeArithmetic(
1665916804 }
1666016805 if (maybe_lhs_val) |lhs_val| {
1666116806 if (lhs_val.isUndef(mod)) {
16662 return mod.undefRef(resolved_type);
16807 return pt.undefRef(resolved_type);
1666316808 }
16664 return Air.internedToRef((try lhs_val.numberMulWrap(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16809 return Air.internedToRef((try lhs_val.numberMulWrap(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1666516810 } else break :rs .{ lhs_src, .mul_wrap, .mul_wrap };
1666616811 } else break :rs .{ rhs_src, .mul_wrap, .mul_wrap };
1666716812 },
......@@ -16671,18 +16816,18 @@ fn analyzeArithmetic(
1667116816 // If either of the operands are one, result is the other operand.
1667216817 // If either of the operands are undefined, result is undefined.
1667316818 const scalar_zero = switch (scalar_tag) {
16674 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16675 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16819 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16820 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1667616821 else => unreachable,
1667716822 };
1667816823 const scalar_one = switch (scalar_tag) {
16679 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16680 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16824 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16825 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1668116826 else => unreachable,
1668216827 };
1668316828 if (maybe_lhs_val) |lhs_val| {
1668416829 if (!lhs_val.isUndef(mod)) {
16685 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16830 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1668616831 const zero_val = try sema.splat(resolved_type, scalar_zero);
1668716832 return Air.internedToRef(zero_val.toIntern());
1668816833 }
......@@ -16693,9 +16838,9 @@ fn analyzeArithmetic(
1669316838 }
1669416839 if (maybe_rhs_val) |rhs_val| {
1669516840 if (rhs_val.isUndef(mod)) {
16696 return mod.undefRef(resolved_type);
16841 return pt.undefRef(resolved_type);
1669716842 }
16698 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16843 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1669916844 const zero_val = try sema.splat(resolved_type, scalar_zero);
1670016845 return Air.internedToRef(zero_val.toIntern());
1670116846 }
......@@ -16704,13 +16849,13 @@ fn analyzeArithmetic(
1670416849 }
1670516850 if (maybe_lhs_val) |lhs_val| {
1670616851 if (lhs_val.isUndef(mod)) {
16707 return mod.undefRef(resolved_type);
16852 return pt.undefRef(resolved_type);
1670816853 }
1670916854
1671016855 const val = if (scalar_tag == .ComptimeInt)
16711 try lhs_val.intMul(rhs_val, resolved_type, undefined, sema.arena, mod)
16856 try lhs_val.intMul(rhs_val, resolved_type, undefined, sema.arena, pt)
1671216857 else
16713 try lhs_val.intMulSat(rhs_val, resolved_type, sema.arena, mod);
16858 try lhs_val.intMulSat(rhs_val, resolved_type, sema.arena, pt);
1671416859
1671516860 return Air.internedToRef(val.toIntern());
1671616861 } else break :rs .{ lhs_src, .mul_sat, .mul_sat };
......@@ -16758,7 +16903,7 @@ fn analyzeArithmetic(
1675816903 })
1675916904 else
1676016905 ov_bit;
16761 const zero_ov = Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
16906 const zero_ov = Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
1676216907 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1676316908
1676416909 try sema.addSafetyCheck(block, src, no_ov, .integer_overflow);
......@@ -16782,7 +16927,8 @@ fn analyzePtrArithmetic(
1678216927 // TODO if the operand is comptime-known to be negative, or is a negative int,
1678316928 // coerce to isize instead of usize.
1678416929 const offset = try sema.coerce(block, Type.usize, uncasted_offset, offset_src);
16785 const mod = sema.mod;
16930 const pt = sema.pt;
16931 const mod = pt.zcu;
1678616932 const opt_ptr_val = try sema.resolveValue(ptr);
1678716933 const opt_off_val = try sema.resolveDefinedValue(block, offset_src, offset);
1678816934 const ptr_ty = sema.typeOf(ptr);
......@@ -16800,7 +16946,7 @@ fn analyzePtrArithmetic(
1680016946 // it being a multiple of the type size.
1680116947 const elem_size = try sema.typeAbiSize(Type.fromInterned(ptr_info.child));
1680216948 const addend = if (opt_off_val) |off_val| a: {
16803 const off_int = try sema.usizeCast(block, offset_src, try off_val.toUnsignedIntSema(mod));
16949 const off_int = try sema.usizeCast(block, offset_src, try off_val.toUnsignedIntSema(pt));
1680416950 break :a elem_size * off_int;
1680516951 } else elem_size;
1680616952
......@@ -16813,7 +16959,7 @@ fn analyzePtrArithmetic(
1681316959 ));
1681416960 assert(new_align != .none);
1681516961
16816 break :t try mod.ptrTypeSema(.{
16962 break :t try pt.ptrTypeSema(.{
1681716963 .child = ptr_info.child,
1681816964 .sentinel = ptr_info.sentinel,
1681916965 .flags = .{
......@@ -16830,16 +16976,16 @@ fn analyzePtrArithmetic(
1683016976 const runtime_src = rs: {
1683116977 if (opt_ptr_val) |ptr_val| {
1683216978 if (opt_off_val) |offset_val| {
16833 if (ptr_val.isUndef(mod)) return mod.undefRef(new_ptr_ty);
16979 if (ptr_val.isUndef(mod)) return pt.undefRef(new_ptr_ty);
1683416980
16835 const offset_int = try sema.usizeCast(block, offset_src, try offset_val.toUnsignedIntSema(mod));
16981 const offset_int = try sema.usizeCast(block, offset_src, try offset_val.toUnsignedIntSema(pt));
1683616982 if (offset_int == 0) return ptr;
1683716983 if (air_tag == .ptr_sub) {
1683816984 const elem_size = try sema.typeAbiSize(Type.fromInterned(ptr_info.child));
1683916985 const new_ptr_val = try sema.ptrSubtract(block, op_src, ptr_val, offset_int * elem_size, new_ptr_ty);
1684016986 return Air.internedToRef(new_ptr_val.toIntern());
1684116987 } else {
16842 const new_ptr_val = try mod.getCoerced(try ptr_val.ptrElem(offset_int, mod), new_ptr_ty);
16988 const new_ptr_val = try pt.getCoerced(try ptr_val.ptrElem(offset_int, pt), new_ptr_ty);
1684316989 return Air.internedToRef(new_ptr_val.toIntern());
1684416990 }
1684516991 } else break :rs offset_src;
......@@ -16879,6 +17025,8 @@ fn zirAsm(
1687917025 const tracy = trace(@src());
1688017026 defer tracy.end();
1688117027
17028 const pt = sema.pt;
17029 const mod = pt.zcu;
1688217030 const extra = sema.code.extraData(Zir.Inst.Asm, extended.operand);
1688317031 const src = block.nodeOffset(extra.data.src_node);
1688417032 const ret_ty_src = block.src(.{ .node_offset_asm_ret_ty = extra.data.src_node });
......@@ -16910,7 +17058,7 @@ fn zirAsm(
1691017058 if (is_volatile) {
1691117059 return sema.fail(block, src, "volatile keyword is redundant on module-level assembly", .{});
1691217060 }
16913 try sema.mod.addGlobalAssembly(sema.owner_decl_index, asm_source);
17061 try mod.addGlobalAssembly(sema.owner_decl_index, asm_source);
1691417062 return .void_value;
1691517063 }
1691617064
......@@ -16959,7 +17107,6 @@ fn zirAsm(
1695917107
1696017108 const args = try sema.arena.alloc(Air.Inst.Ref, inputs_len);
1696117109 const inputs = try sema.arena.alloc(ConstraintName, inputs_len);
16962 const mod = sema.mod;
1696317110
1696417111 for (args, 0..) |*arg, arg_i| {
1696517112 const input = sema.code.extraData(Zir.Inst.Asm.Input, extra_i);
......@@ -17049,7 +17196,8 @@ fn zirCmpEq(
1704917196 const tracy = trace(@src());
1705017197 defer tracy.end();
1705117198
17052 const mod = sema.mod;
17199 const pt = sema.pt;
17200 const mod = pt.zcu;
1705317201 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1705417202 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1705517203 const src: LazySrcLoc = block.nodeOffset(inst_data.src_node);
......@@ -17077,7 +17225,7 @@ fn zirCmpEq(
1707717225
1707817226 if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
1707917227 const non_null_type = if (lhs_ty_tag == .Null) rhs_ty else lhs_ty;
17080 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(mod)});
17228 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(pt)});
1708117229 }
1708217230
1708317231 if (lhs_ty_tag == .Union and (rhs_ty_tag == .EnumLiteral or rhs_ty_tag == .Enum)) {
......@@ -17092,7 +17240,7 @@ fn zirCmpEq(
1709217240 if (try sema.resolveValue(lhs)) |lval| {
1709317241 if (try sema.resolveValue(rhs)) |rval| {
1709417242 if (lval.isUndef(mod) or rval.isUndef(mod)) {
17095 return mod.undefRef(Type.bool);
17243 return pt.undefRef(Type.bool);
1709617244 }
1709717245 const lkey = mod.intern_pool.indexToKey(lval.toIntern());
1709817246 const rkey = mod.intern_pool.indexToKey(rval.toIntern());
......@@ -17128,14 +17276,15 @@ fn analyzeCmpUnionTag(
1712817276 tag_src: LazySrcLoc,
1712917277 op: std.math.CompareOperator,
1713017278) CompileError!Air.Inst.Ref {
17131 const mod = sema.mod;
17279 const pt = sema.pt;
17280 const mod = pt.zcu;
1713217281 const union_ty = sema.typeOf(un);
17133 try union_ty.resolveFields(mod);
17282 try union_ty.resolveFields(pt);
1713417283 const union_tag_ty = union_ty.unionTagType(mod) orelse {
1713517284 const msg = msg: {
1713617285 const msg = try sema.errMsg(un_src, "comparison of union and enum literal is only valid for tagged union types", .{});
1713717286 errdefer msg.destroy(sema.gpa);
17138 try sema.errNote(union_ty.srcLoc(mod), msg, "union '{}' is not a tagged union", .{union_ty.fmt(mod)});
17287 try sema.errNote(union_ty.srcLoc(mod), msg, "union '{}' is not a tagged union", .{union_ty.fmt(pt)});
1713917288 break :msg msg;
1714017289 };
1714117290 return sema.failWithOwnedErrorMsg(block, msg);
......@@ -17146,7 +17295,7 @@ fn analyzeCmpUnionTag(
1714617295 const coerced_union = try sema.coerce(block, union_tag_ty, un, un_src);
1714717296
1714817297 if (try sema.resolveValue(coerced_tag)) |enum_val| {
17149 if (enum_val.isUndef(mod)) return mod.undefRef(Type.bool);
17298 if (enum_val.isUndef(mod)) return pt.undefRef(Type.bool);
1715017299 const field_ty = union_ty.unionFieldType(enum_val, mod).?;
1715117300 if (field_ty.zigTypeTag(mod) == .NoReturn) {
1715217301 return .bool_false;
......@@ -17187,7 +17336,8 @@ fn analyzeCmp(
1718717336 rhs_src: LazySrcLoc,
1718817337 is_equality_cmp: bool,
1718917338) CompileError!Air.Inst.Ref {
17190 const mod = sema.mod;
17339 const pt = sema.pt;
17340 const mod = pt.zcu;
1719117341 const lhs_ty = sema.typeOf(lhs);
1719217342 const rhs_ty = sema.typeOf(rhs);
1719317343 if (lhs_ty.zigTypeTag(mod) != .Optional and rhs_ty.zigTypeTag(mod) != .Optional) {
......@@ -17215,7 +17365,7 @@ fn analyzeCmp(
1721517365 const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{ .override = &[_]?LazySrcLoc{ lhs_src, rhs_src } });
1721617366 if (!resolved_type.isSelfComparable(mod, is_equality_cmp)) {
1721717367 return sema.fail(block, src, "operator {s} not allowed for type '{}'", .{
17218 compareOperatorName(op), resolved_type.fmt(mod),
17368 compareOperatorName(op), resolved_type.fmt(pt),
1721917369 });
1722017370 }
1722117371 const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
......@@ -17244,13 +17394,14 @@ fn cmpSelf(
1724417394 lhs_src: LazySrcLoc,
1724517395 rhs_src: LazySrcLoc,
1724617396) CompileError!Air.Inst.Ref {
17247 const mod = sema.mod;
17397 const pt = sema.pt;
17398 const mod = pt.zcu;
1724817399 const resolved_type = sema.typeOf(casted_lhs);
1724917400 const runtime_src: LazySrcLoc = src: {
1725017401 if (try sema.resolveValue(casted_lhs)) |lhs_val| {
17251 if (lhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17402 if (lhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1725217403 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
17253 if (rhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17404 if (rhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1725417405
1725517406 if (resolved_type.zigTypeTag(mod) == .Vector) {
1725617407 const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, resolved_type);
......@@ -17273,7 +17424,7 @@ fn cmpSelf(
1727317424 // bool eq/neq more efficiently.
1727417425 if (resolved_type.zigTypeTag(mod) == .Bool) {
1727517426 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
17276 if (rhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17427 if (rhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1727717428 return sema.runtimeBoolCmp(block, src, op, casted_lhs, rhs_val.toBool(), lhs_src);
1727817429 }
1727917430 }
......@@ -17310,24 +17461,24 @@ fn runtimeBoolCmp(
1731017461}
1731117462
1731217463fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17313 const mod = sema.mod;
17464 const pt = sema.pt;
1731417465 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1731517466 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1731617467 const ty = try sema.resolveType(block, operand_src, inst_data.operand);
17317 switch (ty.zigTypeTag(mod)) {
17468 switch (ty.zigTypeTag(pt.zcu)) {
1731817469 .Fn,
1731917470 .NoReturn,
1732017471 .Undefined,
1732117472 .Null,
1732217473 .Opaque,
17323 => return sema.fail(block, operand_src, "no size available for type '{}'", .{ty.fmt(mod)}),
17474 => return sema.fail(block, operand_src, "no size available for type '{}'", .{ty.fmt(pt)}),
1732417475
1732517476 .Type,
1732617477 .EnumLiteral,
1732717478 .ComptimeFloat,
1732817479 .ComptimeInt,
1732917480 .Void,
17330 => return mod.intRef(Type.comptime_int, 0),
17481 => return pt.intRef(Type.comptime_int, 0),
1733117482
1733217483 .Bool,
1733317484 .Int,
......@@ -17345,12 +17496,13 @@ fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1734517496 .AnyFrame,
1734617497 => {},
1734717498 }
17348 const val = try ty.lazyAbiSize(mod);
17499 const val = try ty.lazyAbiSize(pt);
1734917500 return Air.internedToRef(val.toIntern());
1735017501}
1735117502
1735217503fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17353 const mod = sema.mod;
17504 const pt = sema.pt;
17505 const mod = pt.zcu;
1735417506 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1735517507 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1735617508 const operand_ty = try sema.resolveType(block, operand_src, inst_data.operand);
......@@ -17360,14 +17512,14 @@ fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1736017512 .Undefined,
1736117513 .Null,
1736217514 .Opaque,
17363 => return sema.fail(block, operand_src, "no size available for type '{}'", .{operand_ty.fmt(mod)}),
17515 => return sema.fail(block, operand_src, "no size available for type '{}'", .{operand_ty.fmt(pt)}),
1736417516
1736517517 .Type,
1736617518 .EnumLiteral,
1736717519 .ComptimeFloat,
1736817520 .ComptimeInt,
1736917521 .Void,
17370 => return mod.intRef(Type.comptime_int, 0),
17522 => return pt.intRef(Type.comptime_int, 0),
1737117523
1737217524 .Bool,
1737317525 .Int,
......@@ -17385,8 +17537,8 @@ fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1738517537 .AnyFrame,
1738617538 => {},
1738717539 }
17388 const bit_size = try operand_ty.bitSizeAdvanced(mod, .sema);
17389 return mod.intRef(Type.comptime_int, bit_size);
17540 const bit_size = try operand_ty.bitSizeAdvanced(pt, .sema);
17541 return pt.intRef(Type.comptime_int, bit_size);
1739017542}
1739117543
1739217544fn zirThis(
......@@ -17394,14 +17546,16 @@ fn zirThis(
1739417546 block: *Block,
1739517547 extended: Zir.Inst.Extended.InstData,
1739617548) CompileError!Air.Inst.Ref {
17397 const mod = sema.mod;
17549 const pt = sema.pt;
17550 const mod = pt.zcu;
1739817551 const this_decl_index = mod.namespacePtr(block.namespace).decl_index;
1739917552 const src = block.nodeOffset(@bitCast(extended.operand));
1740017553 return sema.analyzeDeclVal(block, src, this_decl_index);
1740117554}
1740217555
1740317556fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
17404 const mod = sema.mod;
17557 const pt = sema.pt;
17558 const mod = pt.zcu;
1740517559 const ip = &mod.intern_pool;
1740617560 const captures = mod.namespacePtr(block.namespace).getType(mod).getCaptures(mod);
1740717561
......@@ -17489,7 +17643,7 @@ fn zirRetAddr(
1748917643 _ = extended;
1749017644 if (block.is_comptime) {
1749117645 // TODO: we could give a meaningful lazy value here. #14938
17492 return sema.mod.intRef(Type.usize, 0);
17646 return sema.pt.intRef(Type.usize, 0);
1749317647 } else {
1749417648 return block.addNoOp(.ret_addr);
1749517649 }
......@@ -17514,7 +17668,8 @@ fn zirBuiltinSrc(
1751417668 const tracy = trace(@src());
1751517669 defer tracy.end();
1751617670
17517 const mod = sema.mod;
17671 const pt = sema.pt;
17672 const mod = pt.zcu;
1751817673 const extra = sema.code.extraData(Zir.Inst.Src, extended.operand).data;
1751917674 const fn_owner_decl = mod.funcOwnerDeclPtr(sema.func_index);
1752017675 const ip = &mod.intern_pool;
......@@ -17522,43 +17677,43 @@ fn zirBuiltinSrc(
1752217677
1752317678 const func_name_val = v: {
1752417679 const func_name_len = fn_owner_decl.name.length(ip);
17525 const array_ty = try ip.get(gpa, .{ .array_type = .{
17680 const array_ty = try pt.intern(.{ .array_type = .{
1752617681 .len = func_name_len,
1752717682 .sentinel = .zero_u8,
1752817683 .child = .u8_type,
1752917684 } });
17530 break :v try ip.get(gpa, .{ .slice = .{
17685 break :v try pt.intern(.{ .slice = .{
1753117686 .ty = .slice_const_u8_sentinel_0_type,
17532 .ptr = try ip.get(gpa, .{ .ptr = .{
17687 .ptr = try pt.intern(.{ .ptr = .{
1753317688 .ty = .manyptr_const_u8_sentinel_0_type,
1753417689 .base_addr = .{ .anon_decl = .{
1753517690 .orig_ty = .slice_const_u8_sentinel_0_type,
17536 .val = try ip.get(gpa, .{ .aggregate = .{
17691 .val = try pt.intern(.{ .aggregate = .{
1753717692 .ty = array_ty,
1753817693 .storage = .{ .bytes = fn_owner_decl.name.toString() },
1753917694 } }),
1754017695 } },
1754117696 .byte_offset = 0,
1754217697 } }),
17543 .len = (try mod.intValue(Type.usize, func_name_len)).toIntern(),
17698 .len = (try pt.intValue(Type.usize, func_name_len)).toIntern(),
1754417699 } });
1754517700 };
1754617701
1754717702 const file_name_val = v: {
1754817703 // The compiler must not call realpath anywhere.
1754917704 const file_name = try fn_owner_decl.getFileScope(mod).fullPath(sema.arena);
17550 const array_ty = try ip.get(gpa, .{ .array_type = .{
17705 const array_ty = try pt.intern(.{ .array_type = .{
1755117706 .len = file_name.len,
1755217707 .sentinel = .zero_u8,
1755317708 .child = .u8_type,
1755417709 } });
17555 break :v try ip.get(gpa, .{ .slice = .{
17710 break :v try pt.intern(.{ .slice = .{
1755617711 .ty = .slice_const_u8_sentinel_0_type,
17557 .ptr = try ip.get(gpa, .{ .ptr = .{
17712 .ptr = try pt.intern(.{ .ptr = .{
1755817713 .ty = .manyptr_const_u8_sentinel_0_type,
1755917714 .base_addr = .{ .anon_decl = .{
1756017715 .orig_ty = .slice_const_u8_sentinel_0_type,
17561 .val = try ip.get(gpa, .{ .aggregate = .{
17716 .val = try pt.intern(.{ .aggregate = .{
1756217717 .ty = array_ty,
1756317718 .storage = .{
1756417719 .bytes = try ip.getOrPutString(gpa, file_name, .maybe_embedded_nulls),
......@@ -17567,35 +17722,36 @@ fn zirBuiltinSrc(
1756717722 } },
1756817723 .byte_offset = 0,
1756917724 } }),
17570 .len = (try mod.intValue(Type.usize, file_name.len)).toIntern(),
17725 .len = (try pt.intValue(Type.usize, file_name.len)).toIntern(),
1757117726 } });
1757217727 };
1757317728
17574 const src_loc_ty = try mod.getBuiltinType("SourceLocation");
17729 const src_loc_ty = try pt.getBuiltinType("SourceLocation");
1757517730 const fields = .{
1757617731 // file: [:0]const u8,
1757717732 file_name_val,
1757817733 // fn_name: [:0]const u8,
1757917734 func_name_val,
1758017735 // line: u32,
17581 (try mod.intValue(Type.u32, extra.line + 1)).toIntern(),
17736 (try pt.intValue(Type.u32, extra.line + 1)).toIntern(),
1758217737 // column: u32,
17583 (try mod.intValue(Type.u32, extra.column + 1)).toIntern(),
17738 (try pt.intValue(Type.u32, extra.column + 1)).toIntern(),
1758417739 };
17585 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
17740 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1758617741 .ty = src_loc_ty.toIntern(),
1758717742 .storage = .{ .elems = &fields },
1758817743 } })));
1758917744}
1759017745
1759117746fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17592 const mod = sema.mod;
17747 const pt = sema.pt;
17748 const mod = pt.zcu;
1759317749 const gpa = sema.gpa;
1759417750 const ip = &mod.intern_pool;
1759517751 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1759617752 const src = block.nodeOffset(inst_data.src_node);
1759717753 const ty = try sema.resolveType(block, src, inst_data.operand);
17598 const type_info_ty = try mod.getBuiltinType("Type");
17754 const type_info_ty = try pt.getBuiltinType("Type");
1759917755 const type_info_tag_ty = type_info_ty.unionTagType(mod).?;
1760017756
1760117757 if (ty.typeDeclInst(mod)) |type_decl_inst| {
......@@ -17612,9 +17768,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1761217768 .Undefined,
1761317769 .Null,
1761417770 .EnumLiteral,
17615 => |type_info_tag| return Air.internedToRef((try mod.intern(.{ .un = .{
17771 => |type_info_tag| return Air.internedToRef((try pt.intern(.{ .un = .{
1761617772 .ty = type_info_ty.toIntern(),
17617 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
17773 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
1761817774 .val = .void_value,
1761917775 } }))),
1762017776 .Fn => {
......@@ -17643,8 +17799,8 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1764317799 for (param_vals, 0..) |*param_val, i| {
1764417800 const param_ty = func_ty_info.param_types.get(ip)[i];
1764517801 const is_generic = param_ty == .generic_poison_type;
17646 const param_ty_val = try ip.get(gpa, .{ .opt = .{
17647 .ty = try ip.get(gpa, .{ .opt_type = .type_type }),
17802 const param_ty_val = try pt.intern(.{ .opt = .{
17803 .ty = try pt.intern(.{ .opt_type = .type_type }),
1764817804 .val = if (is_generic) .none else param_ty,
1764917805 } });
1765017806
......@@ -17661,22 +17817,22 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1766117817 // type: ?type,
1766217818 param_ty_val,
1766317819 };
17664 param_val.* = try mod.intern(.{ .aggregate = .{
17820 param_val.* = try pt.intern(.{ .aggregate = .{
1766517821 .ty = param_info_ty.toIntern(),
1766617822 .storage = .{ .elems = &param_fields },
1766717823 } });
1766817824 }
1766917825
1767017826 const args_val = v: {
17671 const new_decl_ty = try mod.arrayType(.{
17827 const new_decl_ty = try pt.arrayType(.{
1767217828 .len = param_vals.len,
1767317829 .child = param_info_ty.toIntern(),
1767417830 });
17675 const new_decl_val = try mod.intern(.{ .aggregate = .{
17831 const new_decl_val = try pt.intern(.{ .aggregate = .{
1767617832 .ty = new_decl_ty.toIntern(),
1767717833 .storage = .{ .elems = param_vals },
1767817834 } });
17679 const slice_ty = (try mod.ptrTypeSema(.{
17835 const slice_ty = (try pt.ptrTypeSema(.{
1768017836 .child = param_info_ty.toIntern(),
1768117837 .flags = .{
1768217838 .size = .Slice,
......@@ -17684,9 +17840,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1768417840 },
1768517841 })).toIntern();
1768617842 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
17687 break :v try mod.intern(.{ .slice = .{
17843 break :v try pt.intern(.{ .slice = .{
1768817844 .ty = slice_ty,
17689 .ptr = try mod.intern(.{ .ptr = .{
17845 .ptr = try pt.intern(.{ .ptr = .{
1769017846 .ty = manyptr_ty,
1769117847 .base_addr = .{ .anon_decl = .{
1769217848 .orig_ty = manyptr_ty,
......@@ -17694,23 +17850,23 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1769417850 } },
1769517851 .byte_offset = 0,
1769617852 } }),
17697 .len = (try mod.intValue(Type.usize, param_vals.len)).toIntern(),
17853 .len = (try pt.intValue(Type.usize, param_vals.len)).toIntern(),
1769817854 } });
1769917855 };
1770017856
17701 const ret_ty_opt = try mod.intern(.{ .opt = .{
17702 .ty = try ip.get(gpa, .{ .opt_type = .type_type }),
17857 const ret_ty_opt = try pt.intern(.{ .opt = .{
17858 .ty = try pt.intern(.{ .opt_type = .type_type }),
1770317859 .val = if (func_ty_info.return_type == .generic_poison_type)
1770417860 .none
1770517861 else
1770617862 func_ty_info.return_type,
1770717863 } });
1770817864
17709 const callconv_ty = try mod.getBuiltinType("CallingConvention");
17865 const callconv_ty = try pt.getBuiltinType("CallingConvention");
1771017866
1771117867 const field_values = .{
1771217868 // calling_convention: CallingConvention,
17713 (try mod.enumValueFieldIndex(callconv_ty, @intFromEnum(func_ty_info.cc))).toIntern(),
17869 (try pt.enumValueFieldIndex(callconv_ty, @intFromEnum(func_ty_info.cc))).toIntern(),
1771417870 // is_generic: bool,
1771517871 Value.makeBool(func_ty_info.is_generic).toIntern(),
1771617872 // is_var_args: bool,
......@@ -17720,10 +17876,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1772017876 // args: []const Fn.Param,
1772117877 args_val,
1772217878 };
17723 return Air.internedToRef((try mod.intern(.{ .un = .{
17879 return Air.internedToRef((try pt.intern(.{ .un = .{
1772417880 .ty = type_info_ty.toIntern(),
17725 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Fn))).toIntern(),
17726 .val = try mod.intern(.{ .aggregate = .{
17881 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Fn))).toIntern(),
17882 .val = try pt.intern(.{ .aggregate = .{
1772717883 .ty = fn_info_ty.toIntern(),
1772817884 .storage = .{ .elems = &field_values },
1772917885 } }),
......@@ -17740,18 +17896,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1774017896 const int_info_decl = mod.declPtr(int_info_decl_index);
1774117897 const int_info_ty = int_info_decl.val.toType();
1774217898
17743 const signedness_ty = try mod.getBuiltinType("Signedness");
17899 const signedness_ty = try pt.getBuiltinType("Signedness");
1774417900 const info = ty.intInfo(mod);
1774517901 const field_values = .{
1774617902 // signedness: Signedness,
17747 (try mod.enumValueFieldIndex(signedness_ty, @intFromEnum(info.signedness))).toIntern(),
17903 (try pt.enumValueFieldIndex(signedness_ty, @intFromEnum(info.signedness))).toIntern(),
1774817904 // bits: u16,
17749 (try mod.intValue(Type.u16, info.bits)).toIntern(),
17905 (try pt.intValue(Type.u16, info.bits)).toIntern(),
1775017906 };
17751 return Air.internedToRef((try mod.intern(.{ .un = .{
17907 return Air.internedToRef((try pt.intern(.{ .un = .{
1775217908 .ty = type_info_ty.toIntern(),
17753 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Int))).toIntern(),
17754 .val = try mod.intern(.{ .aggregate = .{
17909 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Int))).toIntern(),
17910 .val = try pt.intern(.{ .aggregate = .{
1775517911 .ty = int_info_ty.toIntern(),
1775617912 .storage = .{ .elems = &field_values },
1775717913 } }),
......@@ -17770,12 +17926,12 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1777017926
1777117927 const field_vals = .{
1777217928 // bits: u16,
17773 (try mod.intValue(Type.u16, ty.bitSize(mod))).toIntern(),
17929 (try pt.intValue(Type.u16, ty.bitSize(pt))).toIntern(),
1777417930 };
17775 return Air.internedToRef((try mod.intern(.{ .un = .{
17931 return Air.internedToRef((try pt.intern(.{ .un = .{
1777617932 .ty = type_info_ty.toIntern(),
17777 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Float))).toIntern(),
17778 .val = try mod.intern(.{ .aggregate = .{
17933 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Float))).toIntern(),
17934 .val = try pt.intern(.{ .aggregate = .{
1777917935 .ty = float_info_ty.toIntern(),
1778017936 .storage = .{ .elems = &field_vals },
1778117937 } }),
......@@ -17784,16 +17940,16 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1778417940 .Pointer => {
1778517941 const info = ty.ptrInfo(mod);
1778617942 const alignment = if (info.flags.alignment.toByteUnits()) |alignment|
17787 try mod.intValue(Type.comptime_int, alignment)
17943 try pt.intValue(Type.comptime_int, alignment)
1778817944 else
17789 try Type.fromInterned(info.child).lazyAbiAlignment(mod);
17945 try Type.fromInterned(info.child).lazyAbiAlignment(pt);
1779017946
17791 const addrspace_ty = try mod.getBuiltinType("AddressSpace");
17947 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
1779217948 const pointer_ty = t: {
1779317949 const decl_index = (try sema.namespaceLookup(
1779417950 block,
1779517951 src,
17796 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
17952 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
1779717953 try ip.getOrPutString(gpa, "Pointer", .no_embedded_nulls),
1779817954 )).?;
1779917955 try sema.ensureDeclAnalyzed(decl_index);
......@@ -17814,7 +17970,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1781417970
1781517971 const field_values = .{
1781617972 // size: Size,
17817 (try mod.enumValueFieldIndex(ptr_size_ty, @intFromEnum(info.flags.size))).toIntern(),
17973 (try pt.enumValueFieldIndex(ptr_size_ty, @intFromEnum(info.flags.size))).toIntern(),
1781817974 // is_const: bool,
1781917975 Value.makeBool(info.flags.is_const).toIntern(),
1782017976 // is_volatile: bool,
......@@ -17822,7 +17978,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1782217978 // alignment: comptime_int,
1782317979 alignment.toIntern(),
1782417980 // address_space: AddressSpace
17825 (try mod.enumValueFieldIndex(addrspace_ty, @intFromEnum(info.flags.address_space))).toIntern(),
17981 (try pt.enumValueFieldIndex(addrspace_ty, @intFromEnum(info.flags.address_space))).toIntern(),
1782617982 // child: type,
1782717983 info.child,
1782817984 // is_allowzero: bool,
......@@ -17833,10 +17989,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1783317989 else => Value.fromInterned(info.sentinel),
1783417990 })).toIntern(),
1783517991 };
17836 return Air.internedToRef((try mod.intern(.{ .un = .{
17992 return Air.internedToRef((try pt.intern(.{ .un = .{
1783717993 .ty = type_info_ty.toIntern(),
17838 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Pointer))).toIntern(),
17839 .val = try mod.intern(.{ .aggregate = .{
17994 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Pointer))).toIntern(),
17995 .val = try pt.intern(.{ .aggregate = .{
1784017996 .ty = pointer_ty.toIntern(),
1784117997 .storage = .{ .elems = &field_values },
1784217998 } }),
......@@ -17858,16 +18014,16 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1785818014 const info = ty.arrayInfo(mod);
1785918015 const field_values = .{
1786018016 // len: comptime_int,
17861 (try mod.intValue(Type.comptime_int, info.len)).toIntern(),
18017 (try pt.intValue(Type.comptime_int, info.len)).toIntern(),
1786218018 // child: type,
1786318019 info.elem_type.toIntern(),
1786418020 // sentinel: ?*const anyopaque,
1786518021 (try sema.optRefValue(info.sentinel)).toIntern(),
1786618022 };
17867 return Air.internedToRef((try mod.intern(.{ .un = .{
18023 return Air.internedToRef((try pt.intern(.{ .un = .{
1786818024 .ty = type_info_ty.toIntern(),
17869 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Array))).toIntern(),
17870 .val = try mod.intern(.{ .aggregate = .{
18025 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Array))).toIntern(),
18026 .val = try pt.intern(.{ .aggregate = .{
1787118027 .ty = array_field_ty.toIntern(),
1787218028 .storage = .{ .elems = &field_values },
1787318029 } }),
......@@ -17889,14 +18045,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1788918045 const info = ty.arrayInfo(mod);
1789018046 const field_values = .{
1789118047 // len: comptime_int,
17892 (try mod.intValue(Type.comptime_int, info.len)).toIntern(),
18048 (try pt.intValue(Type.comptime_int, info.len)).toIntern(),
1789318049 // child: type,
1789418050 info.elem_type.toIntern(),
1789518051 };
17896 return Air.internedToRef((try mod.intern(.{ .un = .{
18052 return Air.internedToRef((try pt.intern(.{ .un = .{
1789718053 .ty = type_info_ty.toIntern(),
17898 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Vector))).toIntern(),
17899 .val = try mod.intern(.{ .aggregate = .{
18054 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Vector))).toIntern(),
18055 .val = try pt.intern(.{ .aggregate = .{
1790018056 .ty = vector_field_ty.toIntern(),
1790118057 .storage = .{ .elems = &field_values },
1790218058 } }),
......@@ -17919,10 +18075,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1791918075 // child: type,
1792018076 ty.optionalChild(mod).toIntern(),
1792118077 };
17922 return Air.internedToRef((try mod.intern(.{ .un = .{
18078 return Air.internedToRef((try pt.intern(.{ .un = .{
1792318079 .ty = type_info_ty.toIntern(),
17924 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Optional))).toIntern(),
17925 .val = try mod.intern(.{ .aggregate = .{
18080 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Optional))).toIntern(),
18081 .val = try pt.intern(.{ .aggregate = .{
1792618082 .ty = optional_field_ty.toIntern(),
1792718083 .storage = .{ .elems = &field_values },
1792818084 } }),
......@@ -17954,18 +18110,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1795418110 const error_name = names.get(ip)[error_index];
1795518111 const error_name_len = error_name.length(ip);
1795618112 const error_name_val = v: {
17957 const new_decl_ty = try mod.arrayType(.{
18113 const new_decl_ty = try pt.arrayType(.{
1795818114 .len = error_name_len,
1795918115 .sentinel = .zero_u8,
1796018116 .child = .u8_type,
1796118117 });
17962 const new_decl_val = try mod.intern(.{ .aggregate = .{
18118 const new_decl_val = try pt.intern(.{ .aggregate = .{
1796318119 .ty = new_decl_ty.toIntern(),
1796418120 .storage = .{ .bytes = error_name.toString() },
1796518121 } });
17966 break :v try mod.intern(.{ .slice = .{
18122 break :v try pt.intern(.{ .slice = .{
1796718123 .ty = .slice_const_u8_sentinel_0_type,
17968 .ptr = try mod.intern(.{ .ptr = .{
18124 .ptr = try pt.intern(.{ .ptr = .{
1796918125 .ty = .manyptr_const_u8_sentinel_0_type,
1797018126 .base_addr = .{ .anon_decl = .{
1797118127 .val = new_decl_val,
......@@ -17973,7 +18129,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1797318129 } },
1797418130 .byte_offset = 0,
1797518131 } }),
17976 .len = (try mod.intValue(Type.usize, error_name_len)).toIntern(),
18132 .len = (try pt.intValue(Type.usize, error_name_len)).toIntern(),
1797718133 } });
1797818134 };
1797918135
......@@ -17981,7 +18137,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1798118137 // name: [:0]const u8,
1798218138 error_name_val,
1798318139 };
17984 field_val.* = try mod.intern(.{ .aggregate = .{
18140 field_val.* = try pt.intern(.{ .aggregate = .{
1798518141 .ty = error_field_ty.toIntern(),
1798618142 .storage = .{ .elems = &error_field_fields },
1798718143 } });
......@@ -17992,27 +18148,27 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1799218148 };
1799318149
1799418150 // Build our ?[]const Error value
17995 const slice_errors_ty = try mod.ptrTypeSema(.{
18151 const slice_errors_ty = try pt.ptrTypeSema(.{
1799618152 .child = error_field_ty.toIntern(),
1799718153 .flags = .{
1799818154 .size = .Slice,
1799918155 .is_const = true,
1800018156 },
1800118157 });
18002 const opt_slice_errors_ty = try mod.optionalType(slice_errors_ty.toIntern());
18158 const opt_slice_errors_ty = try pt.optionalType(slice_errors_ty.toIntern());
1800318159 const errors_payload_val: InternPool.Index = if (error_field_vals) |vals| v: {
18004 const array_errors_ty = try mod.arrayType(.{
18160 const array_errors_ty = try pt.arrayType(.{
1800518161 .len = vals.len,
1800618162 .child = error_field_ty.toIntern(),
1800718163 });
18008 const new_decl_val = try mod.intern(.{ .aggregate = .{
18164 const new_decl_val = try pt.intern(.{ .aggregate = .{
1800918165 .ty = array_errors_ty.toIntern(),
1801018166 .storage = .{ .elems = vals },
1801118167 } });
1801218168 const manyptr_errors_ty = slice_errors_ty.slicePtrFieldType(mod).toIntern();
18013 break :v try mod.intern(.{ .slice = .{
18169 break :v try pt.intern(.{ .slice = .{
1801418170 .ty = slice_errors_ty.toIntern(),
18015 .ptr = try mod.intern(.{ .ptr = .{
18171 .ptr = try pt.intern(.{ .ptr = .{
1801618172 .ty = manyptr_errors_ty,
1801718173 .base_addr = .{ .anon_decl = .{
1801818174 .orig_ty = manyptr_errors_ty,
......@@ -18020,18 +18176,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1802018176 } },
1802118177 .byte_offset = 0,
1802218178 } }),
18023 .len = (try mod.intValue(Type.usize, vals.len)).toIntern(),
18179 .len = (try pt.intValue(Type.usize, vals.len)).toIntern(),
1802418180 } });
1802518181 } else .none;
18026 const errors_val = try mod.intern(.{ .opt = .{
18182 const errors_val = try pt.intern(.{ .opt = .{
1802718183 .ty = opt_slice_errors_ty.toIntern(),
1802818184 .val = errors_payload_val,
1802918185 } });
1803018186
1803118187 // Construct Type{ .ErrorSet = errors_val }
18032 return Air.internedToRef((try mod.intern(.{ .un = .{
18188 return Air.internedToRef((try pt.intern(.{ .un = .{
1803318189 .ty = type_info_ty.toIntern(),
18034 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorSet))).toIntern(),
18190 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorSet))).toIntern(),
1803518191 .val = errors_val,
1803618192 } })));
1803718193 },
......@@ -18054,10 +18210,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1805418210 // payload: type,
1805518211 ty.errorUnionPayload(mod).toIntern(),
1805618212 };
18057 return Air.internedToRef((try mod.intern(.{ .un = .{
18213 return Air.internedToRef((try pt.intern(.{ .un = .{
1805818214 .ty = type_info_ty.toIntern(),
18059 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorUnion))).toIntern(),
18060 .val = try mod.intern(.{ .aggregate = .{
18215 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorUnion))).toIntern(),
18216 .val = try pt.intern(.{ .aggregate = .{
1806118217 .ty = error_union_field_ty.toIntern(),
1806218218 .storage = .{ .elems = &field_values },
1806318219 } }),
......@@ -18082,30 +18238,31 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1808218238 for (enum_field_vals, 0..) |*field_val, tag_index| {
1808318239 const enum_type = ip.loadEnumType(ty.toIntern());
1808418240 const value_val = if (enum_type.values.len > 0)
18085 try mod.intern_pool.getCoercedInts(
18241 try ip.getCoercedInts(
1808618242 mod.gpa,
18087 mod.intern_pool.indexToKey(enum_type.values.get(ip)[tag_index]).int,
18243 pt.tid,
18244 ip.indexToKey(enum_type.values.get(ip)[tag_index]).int,
1808818245 .comptime_int_type,
1808918246 )
1809018247 else
18091 (try mod.intValue(Type.comptime_int, tag_index)).toIntern();
18248 (try pt.intValue(Type.comptime_int, tag_index)).toIntern();
1809218249
1809318250 // TODO: write something like getCoercedInts to avoid needing to dupe
1809418251 const name_val = v: {
1809518252 const tag_name = enum_type.names.get(ip)[tag_index];
1809618253 const tag_name_len = tag_name.length(ip);
18097 const new_decl_ty = try mod.arrayType(.{
18254 const new_decl_ty = try pt.arrayType(.{
1809818255 .len = tag_name_len,
1809918256 .sentinel = .zero_u8,
1810018257 .child = .u8_type,
1810118258 });
18102 const new_decl_val = try mod.intern(.{ .aggregate = .{
18259 const new_decl_val = try pt.intern(.{ .aggregate = .{
1810318260 .ty = new_decl_ty.toIntern(),
1810418261 .storage = .{ .bytes = tag_name.toString() },
1810518262 } });
18106 break :v try mod.intern(.{ .slice = .{
18263 break :v try pt.intern(.{ .slice = .{
1810718264 .ty = .slice_const_u8_sentinel_0_type,
18108 .ptr = try mod.intern(.{ .ptr = .{
18265 .ptr = try pt.intern(.{ .ptr = .{
1810918266 .ty = .manyptr_const_u8_sentinel_0_type,
1811018267 .base_addr = .{ .anon_decl = .{
1811118268 .val = new_decl_val,
......@@ -18113,7 +18270,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1811318270 } },
1811418271 .byte_offset = 0,
1811518272 } }),
18116 .len = (try mod.intValue(Type.usize, tag_name_len)).toIntern(),
18273 .len = (try pt.intValue(Type.usize, tag_name_len)).toIntern(),
1811718274 } });
1811818275 };
1811918276
......@@ -18123,22 +18280,22 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1812318280 // value: comptime_int,
1812418281 value_val,
1812518282 };
18126 field_val.* = try mod.intern(.{ .aggregate = .{
18283 field_val.* = try pt.intern(.{ .aggregate = .{
1812718284 .ty = enum_field_ty.toIntern(),
1812818285 .storage = .{ .elems = &enum_field_fields },
1812918286 } });
1813018287 }
1813118288
1813218289 const fields_val = v: {
18133 const fields_array_ty = try mod.arrayType(.{
18290 const fields_array_ty = try pt.arrayType(.{
1813418291 .len = enum_field_vals.len,
1813518292 .child = enum_field_ty.toIntern(),
1813618293 });
18137 const new_decl_val = try mod.intern(.{ .aggregate = .{
18294 const new_decl_val = try pt.intern(.{ .aggregate = .{
1813818295 .ty = fields_array_ty.toIntern(),
1813918296 .storage = .{ .elems = enum_field_vals },
1814018297 } });
18141 const slice_ty = (try mod.ptrTypeSema(.{
18298 const slice_ty = (try pt.ptrTypeSema(.{
1814218299 .child = enum_field_ty.toIntern(),
1814318300 .flags = .{
1814418301 .size = .Slice,
......@@ -18146,9 +18303,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1814618303 },
1814718304 })).toIntern();
1814818305 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18149 break :v try mod.intern(.{ .slice = .{
18306 break :v try pt.intern(.{ .slice = .{
1815018307 .ty = slice_ty,
18151 .ptr = try mod.intern(.{ .ptr = .{
18308 .ptr = try pt.intern(.{ .ptr = .{
1815218309 .ty = manyptr_ty,
1815318310 .base_addr = .{ .anon_decl = .{
1815418311 .val = new_decl_val,
......@@ -18156,7 +18313,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1815618313 } },
1815718314 .byte_offset = 0,
1815818315 } }),
18159 .len = (try mod.intValue(Type.usize, enum_field_vals.len)).toIntern(),
18316 .len = (try pt.intValue(Type.usize, enum_field_vals.len)).toIntern(),
1816018317 } });
1816118318 };
1816218319
......@@ -18184,10 +18341,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1818418341 // is_exhaustive: bool,
1818518342 is_exhaustive.toIntern(),
1818618343 };
18187 return Air.internedToRef((try mod.intern(.{ .un = .{
18344 return Air.internedToRef((try pt.intern(.{ .un = .{
1818818345 .ty = type_info_ty.toIntern(),
18189 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Enum))).toIntern(),
18190 .val = try mod.intern(.{ .aggregate = .{
18346 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Enum))).toIntern(),
18347 .val = try pt.intern(.{ .aggregate = .{
1819118348 .ty = type_enum_ty.toIntern(),
1819218349 .storage = .{ .elems = &field_values },
1819318350 } }),
......@@ -18218,7 +18375,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1821818375 break :t union_field_ty_decl.val.toType();
1821918376 };
1822018377
18221 try ty.resolveLayout(mod); // Getting alignment requires type layout
18378 try ty.resolveLayout(pt); // Getting alignment requires type layout
1822218379 const union_obj = mod.typeToUnion(ty).?;
1822318380 const tag_type = union_obj.loadTagType(ip);
1822418381 const layout = union_obj.getLayout(ip);
......@@ -18230,18 +18387,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1823018387 const name_val = v: {
1823118388 const field_name = tag_type.names.get(ip)[field_index];
1823218389 const field_name_len = field_name.length(ip);
18233 const new_decl_ty = try mod.arrayType(.{
18390 const new_decl_ty = try pt.arrayType(.{
1823418391 .len = field_name_len,
1823518392 .sentinel = .zero_u8,
1823618393 .child = .u8_type,
1823718394 });
18238 const new_decl_val = try mod.intern(.{ .aggregate = .{
18395 const new_decl_val = try pt.intern(.{ .aggregate = .{
1823918396 .ty = new_decl_ty.toIntern(),
1824018397 .storage = .{ .bytes = field_name.toString() },
1824118398 } });
18242 break :v try mod.intern(.{ .slice = .{
18399 break :v try pt.intern(.{ .slice = .{
1824318400 .ty = .slice_const_u8_sentinel_0_type,
18244 .ptr = try mod.intern(.{ .ptr = .{
18401 .ptr = try pt.intern(.{ .ptr = .{
1824518402 .ty = .manyptr_const_u8_sentinel_0_type,
1824618403 .base_addr = .{ .anon_decl = .{
1824718404 .val = new_decl_val,
......@@ -18249,12 +18406,12 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1824918406 } },
1825018407 .byte_offset = 0,
1825118408 } }),
18252 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18409 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1825318410 } });
1825418411 };
1825518412
1825618413 const alignment = switch (layout) {
18257 .auto, .@"extern" => try mod.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(field_index), .sema),
18414 .auto, .@"extern" => try pt.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(field_index), .sema),
1825818415 .@"packed" => .none,
1825918416 };
1826018417
......@@ -18265,24 +18422,24 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1826518422 // type: type,
1826618423 field_ty,
1826718424 // alignment: comptime_int,
18268 (try mod.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
18425 (try pt.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
1826918426 };
18270 field_val.* = try mod.intern(.{ .aggregate = .{
18427 field_val.* = try pt.intern(.{ .aggregate = .{
1827118428 .ty = union_field_ty.toIntern(),
1827218429 .storage = .{ .elems = &union_field_fields },
1827318430 } });
1827418431 }
1827518432
1827618433 const fields_val = v: {
18277 const array_fields_ty = try mod.arrayType(.{
18434 const array_fields_ty = try pt.arrayType(.{
1827818435 .len = union_field_vals.len,
1827918436 .child = union_field_ty.toIntern(),
1828018437 });
18281 const new_decl_val = try mod.intern(.{ .aggregate = .{
18438 const new_decl_val = try pt.intern(.{ .aggregate = .{
1828218439 .ty = array_fields_ty.toIntern(),
1828318440 .storage = .{ .elems = union_field_vals },
1828418441 } });
18285 const slice_ty = (try mod.ptrTypeSema(.{
18442 const slice_ty = (try pt.ptrTypeSema(.{
1828618443 .child = union_field_ty.toIntern(),
1828718444 .flags = .{
1828818445 .size = .Slice,
......@@ -18290,9 +18447,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1829018447 },
1829118448 })).toIntern();
1829218449 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18293 break :v try mod.intern(.{ .slice = .{
18450 break :v try pt.intern(.{ .slice = .{
1829418451 .ty = slice_ty,
18295 .ptr = try mod.intern(.{ .ptr = .{
18452 .ptr = try pt.intern(.{ .ptr = .{
1829618453 .ty = manyptr_ty,
1829718454 .base_addr = .{ .anon_decl = .{
1829818455 .orig_ty = manyptr_ty,
......@@ -18300,14 +18457,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1830018457 } },
1830118458 .byte_offset = 0,
1830218459 } }),
18303 .len = (try mod.intValue(Type.usize, union_field_vals.len)).toIntern(),
18460 .len = (try pt.intValue(Type.usize, union_field_vals.len)).toIntern(),
1830418461 } });
1830518462 };
1830618463
1830718464 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1830818465
18309 const enum_tag_ty_val = try mod.intern(.{ .opt = .{
18310 .ty = (try mod.optionalType(.type_type)).toIntern(),
18466 const enum_tag_ty_val = try pt.intern(.{ .opt = .{
18467 .ty = (try pt.optionalType(.type_type)).toIntern(),
1831118468 .val = if (ty.unionTagType(mod)) |tag_ty| tag_ty.toIntern() else .none,
1831218469 } });
1831318470
......@@ -18315,7 +18472,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1831518472 const decl_index = (try sema.namespaceLookup(
1831618473 block,
1831718474 src,
18318 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
18475 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
1831918476 try ip.getOrPutString(gpa, "ContainerLayout", .no_embedded_nulls),
1832018477 )).?;
1832118478 try sema.ensureDeclAnalyzed(decl_index);
......@@ -18325,7 +18482,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1832518482
1832618483 const field_values = .{
1832718484 // layout: ContainerLayout,
18328 (try mod.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
18485 (try pt.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
1832918486
1833018487 // tag_type: ?type,
1833118488 enum_tag_ty_val,
......@@ -18334,10 +18491,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1833418491 // decls: []const Declaration,
1833518492 decls_val,
1833618493 };
18337 return Air.internedToRef((try mod.intern(.{ .un = .{
18494 return Air.internedToRef((try pt.intern(.{ .un = .{
1833818495 .ty = type_info_ty.toIntern(),
18339 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Union))).toIntern(),
18340 .val = try mod.intern(.{ .aggregate = .{
18496 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Union))).toIntern(),
18497 .val = try pt.intern(.{ .aggregate = .{
1834118498 .ty = type_union_ty.toIntern(),
1834218499 .storage = .{ .elems = &field_values },
1834318500 } }),
......@@ -18368,7 +18525,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1836818525 break :t struct_field_ty_decl.val.toType();
1836918526 };
1837018527
18371 try ty.resolveLayout(mod); // Getting alignment requires type layout
18528 try ty.resolveLayout(pt); // Getting alignment requires type layout
1837218529
1837318530 var struct_field_vals: []InternPool.Index = &.{};
1837418531 defer gpa.free(struct_field_vals);
......@@ -18385,18 +18542,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1838518542 else
1838618543 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
1838718544 const field_name_len = field_name.length(ip);
18388 const new_decl_ty = try mod.arrayType(.{
18545 const new_decl_ty = try pt.arrayType(.{
1838918546 .len = field_name_len,
1839018547 .sentinel = .zero_u8,
1839118548 .child = .u8_type,
1839218549 });
18393 const new_decl_val = try mod.intern(.{ .aggregate = .{
18550 const new_decl_val = try pt.intern(.{ .aggregate = .{
1839418551 .ty = new_decl_ty.toIntern(),
1839518552 .storage = .{ .bytes = field_name.toString() },
1839618553 } });
18397 break :v try mod.intern(.{ .slice = .{
18554 break :v try pt.intern(.{ .slice = .{
1839818555 .ty = .slice_const_u8_sentinel_0_type,
18399 .ptr = try mod.intern(.{ .ptr = .{
18556 .ptr = try pt.intern(.{ .ptr = .{
1840018557 .ty = .manyptr_const_u8_sentinel_0_type,
1840118558 .base_addr = .{ .anon_decl = .{
1840218559 .val = new_decl_val,
......@@ -18404,11 +18561,11 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1840418561 } },
1840518562 .byte_offset = 0,
1840618563 } }),
18407 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18564 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1840818565 } });
1840918566 };
1841018567
18411 try Type.fromInterned(field_ty).resolveLayout(mod);
18568 try Type.fromInterned(field_ty).resolveLayout(pt);
1841218569
1841318570 const is_comptime = field_val != .none;
1841418571 const opt_default_val = if (is_comptime) Value.fromInterned(field_val) else null;
......@@ -18423,9 +18580,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1842318580 // is_comptime: bool,
1842418581 Value.makeBool(is_comptime).toIntern(),
1842518582 // alignment: comptime_int,
18426 (try mod.intValue(Type.comptime_int, Type.fromInterned(field_ty).abiAlignment(mod).toByteUnits() orelse 0)).toIntern(),
18583 (try pt.intValue(Type.comptime_int, Type.fromInterned(field_ty).abiAlignment(pt).toByteUnits() orelse 0)).toIntern(),
1842718584 };
18428 struct_field_val.* = try mod.intern(.{ .aggregate = .{
18585 struct_field_val.* = try pt.intern(.{ .aggregate = .{
1842918586 .ty = struct_field_ty.toIntern(),
1843018587 .storage = .{ .elems = &struct_field_fields },
1843118588 } });
......@@ -18437,7 +18594,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1843718594 };
1843818595 struct_field_vals = try gpa.alloc(InternPool.Index, struct_type.field_types.len);
1843918596
18440 try ty.resolveStructFieldInits(mod);
18597 try ty.resolveStructFieldInits(pt);
1844118598
1844218599 for (struct_field_vals, 0..) |*field_val, field_index| {
1844318600 const field_name = if (struct_type.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -18449,18 +18606,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1844918606 const field_init = struct_type.fieldInit(ip, field_index);
1845018607 const field_is_comptime = struct_type.fieldIsComptime(ip, field_index);
1845118608 const name_val = v: {
18452 const new_decl_ty = try mod.arrayType(.{
18609 const new_decl_ty = try pt.arrayType(.{
1845318610 .len = field_name_len,
1845418611 .sentinel = .zero_u8,
1845518612 .child = .u8_type,
1845618613 });
18457 const new_decl_val = try mod.intern(.{ .aggregate = .{
18614 const new_decl_val = try pt.intern(.{ .aggregate = .{
1845818615 .ty = new_decl_ty.toIntern(),
1845918616 .storage = .{ .bytes = field_name.toString() },
1846018617 } });
18461 break :v try mod.intern(.{ .slice = .{
18618 break :v try pt.intern(.{ .slice = .{
1846218619 .ty = .slice_const_u8_sentinel_0_type,
18463 .ptr = try mod.intern(.{ .ptr = .{
18620 .ptr = try pt.intern(.{ .ptr = .{
1846418621 .ty = .manyptr_const_u8_sentinel_0_type,
1846518622 .base_addr = .{ .anon_decl = .{
1846618623 .val = new_decl_val,
......@@ -18468,7 +18625,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1846818625 } },
1846918626 .byte_offset = 0,
1847018627 } }),
18471 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18628 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1847218629 } });
1847318630 };
1847418631
......@@ -18476,7 +18633,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1847618633 const default_val_ptr = try sema.optRefValue(opt_default_val);
1847718634 const alignment = switch (struct_type.layout) {
1847818635 .@"packed" => .none,
18479 else => try mod.structFieldAlignmentAdvanced(
18636 else => try pt.structFieldAlignmentAdvanced(
1848018637 struct_type.fieldAlign(ip, field_index),
1848118638 field_ty,
1848218639 struct_type.layout,
......@@ -18494,9 +18651,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1849418651 // is_comptime: bool,
1849518652 Value.makeBool(field_is_comptime).toIntern(),
1849618653 // alignment: comptime_int,
18497 (try mod.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
18654 (try pt.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
1849818655 };
18499 field_val.* = try mod.intern(.{ .aggregate = .{
18656 field_val.* = try pt.intern(.{ .aggregate = .{
1850018657 .ty = struct_field_ty.toIntern(),
1850118658 .storage = .{ .elems = &struct_field_fields },
1850218659 } });
......@@ -18504,15 +18661,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1850418661 }
1850518662
1850618663 const fields_val = v: {
18507 const array_fields_ty = try mod.arrayType(.{
18664 const array_fields_ty = try pt.arrayType(.{
1850818665 .len = struct_field_vals.len,
1850918666 .child = struct_field_ty.toIntern(),
1851018667 });
18511 const new_decl_val = try mod.intern(.{ .aggregate = .{
18668 const new_decl_val = try pt.intern(.{ .aggregate = .{
1851218669 .ty = array_fields_ty.toIntern(),
1851318670 .storage = .{ .elems = struct_field_vals },
1851418671 } });
18515 const slice_ty = (try mod.ptrTypeSema(.{
18672 const slice_ty = (try pt.ptrTypeSema(.{
1851618673 .child = struct_field_ty.toIntern(),
1851718674 .flags = .{
1851818675 .size = .Slice,
......@@ -18520,9 +18677,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1852018677 },
1852118678 })).toIntern();
1852218679 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18523 break :v try mod.intern(.{ .slice = .{
18680 break :v try pt.intern(.{ .slice = .{
1852418681 .ty = slice_ty,
18525 .ptr = try mod.intern(.{ .ptr = .{
18682 .ptr = try pt.intern(.{ .ptr = .{
1852618683 .ty = manyptr_ty,
1852718684 .base_addr = .{ .anon_decl = .{
1852818685 .orig_ty = manyptr_ty,
......@@ -18530,14 +18687,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1853018687 } },
1853118688 .byte_offset = 0,
1853218689 } }),
18533 .len = (try mod.intValue(Type.usize, struct_field_vals.len)).toIntern(),
18690 .len = (try pt.intValue(Type.usize, struct_field_vals.len)).toIntern(),
1853418691 } });
1853518692 };
1853618693
1853718694 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1853818695
18539 const backing_integer_val = try mod.intern(.{ .opt = .{
18540 .ty = (try mod.optionalType(.type_type)).toIntern(),
18696 const backing_integer_val = try pt.intern(.{ .opt = .{
18697 .ty = (try pt.optionalType(.type_type)).toIntern(),
1854118698 .val = if (mod.typeToPackedStruct(ty)) |packed_struct| val: {
1854218699 assert(Type.fromInterned(packed_struct.backingIntType(ip).*).isInt(mod));
1854318700 break :val packed_struct.backingIntType(ip).*;
......@@ -18548,7 +18705,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1854818705 const decl_index = (try sema.namespaceLookup(
1854918706 block,
1855018707 src,
18551 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
18708 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
1855218709 try ip.getOrPutString(gpa, "ContainerLayout", .no_embedded_nulls),
1855318710 )).?;
1855418711 try sema.ensureDeclAnalyzed(decl_index);
......@@ -18560,7 +18717,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1856018717
1856118718 const field_values = [_]InternPool.Index{
1856218719 // layout: ContainerLayout,
18563 (try mod.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
18720 (try pt.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
1856418721 // backing_integer: ?type,
1856518722 backing_integer_val,
1856618723 // fields: []const StructField,
......@@ -18570,10 +18727,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1857018727 // is_tuple: bool,
1857118728 Value.makeBool(ty.isTuple(mod)).toIntern(),
1857218729 };
18573 return Air.internedToRef((try mod.intern(.{ .un = .{
18730 return Air.internedToRef((try pt.intern(.{ .un = .{
1857418731 .ty = type_info_ty.toIntern(),
18575 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Struct))).toIntern(),
18576 .val = try mod.intern(.{ .aggregate = .{
18732 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Struct))).toIntern(),
18733 .val = try pt.intern(.{ .aggregate = .{
1857718734 .ty = type_struct_ty.toIntern(),
1857818735 .storage = .{ .elems = &field_values },
1857918736 } }),
......@@ -18592,17 +18749,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1859218749 break :t type_opaque_ty_decl.val.toType();
1859318750 };
1859418751
18595 try ty.resolveFields(mod);
18752 try ty.resolveFields(pt);
1859618753 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1859718754
1859818755 const field_values = .{
1859918756 // decls: []const Declaration,
1860018757 decls_val,
1860118758 };
18602 return Air.internedToRef((try mod.intern(.{ .un = .{
18759 return Air.internedToRef((try pt.intern(.{ .un = .{
1860318760 .ty = type_info_ty.toIntern(),
18604 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Opaque))).toIntern(),
18605 .val = try mod.intern(.{ .aggregate = .{
18761 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Opaque))).toIntern(),
18762 .val = try pt.intern(.{ .aggregate = .{
1860618763 .ty = type_opaque_ty.toIntern(),
1860718764 .storage = .{ .elems = &field_values },
1860818765 } }),
......@@ -18620,7 +18777,8 @@ fn typeInfoDecls(
1862018777 type_info_ty: Type,
1862118778 opt_namespace: InternPool.OptionalNamespaceIndex,
1862218779) CompileError!InternPool.Index {
18623 const mod = sema.mod;
18780 const pt = sema.pt;
18781 const mod = pt.zcu;
1862418782 const gpa = sema.gpa;
1862518783
1862618784 const declaration_ty = t: {
......@@ -18643,15 +18801,15 @@ fn typeInfoDecls(
1864318801
1864418802 try sema.typeInfoNamespaceDecls(block, opt_namespace, declaration_ty, &decl_vals, &seen_namespaces);
1864518803
18646 const array_decl_ty = try mod.arrayType(.{
18804 const array_decl_ty = try pt.arrayType(.{
1864718805 .len = decl_vals.items.len,
1864818806 .child = declaration_ty.toIntern(),
1864918807 });
18650 const new_decl_val = try mod.intern(.{ .aggregate = .{
18808 const new_decl_val = try pt.intern(.{ .aggregate = .{
1865118809 .ty = array_decl_ty.toIntern(),
1865218810 .storage = .{ .elems = decl_vals.items },
1865318811 } });
18654 const slice_ty = (try mod.ptrTypeSema(.{
18812 const slice_ty = (try pt.ptrTypeSema(.{
1865518813 .child = declaration_ty.toIntern(),
1865618814 .flags = .{
1865718815 .size = .Slice,
......@@ -18659,9 +18817,9 @@ fn typeInfoDecls(
1865918817 },
1866018818 })).toIntern();
1866118819 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18662 return try mod.intern(.{ .slice = .{
18820 return try pt.intern(.{ .slice = .{
1866318821 .ty = slice_ty,
18664 .ptr = try mod.intern(.{ .ptr = .{
18822 .ptr = try pt.intern(.{ .ptr = .{
1866518823 .ty = manyptr_ty,
1866618824 .base_addr = .{ .anon_decl = .{
1866718825 .orig_ty = manyptr_ty,
......@@ -18669,7 +18827,7 @@ fn typeInfoDecls(
1866918827 } },
1867018828 .byte_offset = 0,
1867118829 } }),
18672 .len = (try mod.intValue(Type.usize, decl_vals.items.len)).toIntern(),
18830 .len = (try pt.intValue(Type.usize, decl_vals.items.len)).toIntern(),
1867318831 } });
1867418832}
1867518833
......@@ -18681,7 +18839,8 @@ fn typeInfoNamespaceDecls(
1868118839 decl_vals: *std.ArrayList(InternPool.Index),
1868218840 seen_namespaces: *std.AutoHashMap(*Namespace, void),
1868318841) !void {
18684 const mod = sema.mod;
18842 const pt = sema.pt;
18843 const mod = pt.zcu;
1868518844 const ip = &mod.intern_pool;
1868618845
1868718846 const namespace_index = opt_namespace_index.unwrap() orelse return;
......@@ -18703,18 +18862,18 @@ fn typeInfoNamespaceDecls(
1870318862 if (decl.kind != .named) continue;
1870418863 const name_val = v: {
1870518864 const decl_name_len = decl.name.length(ip);
18706 const new_decl_ty = try mod.arrayType(.{
18865 const new_decl_ty = try pt.arrayType(.{
1870718866 .len = decl_name_len,
1870818867 .sentinel = .zero_u8,
1870918868 .child = .u8_type,
1871018869 });
18711 const new_decl_val = try mod.intern(.{ .aggregate = .{
18870 const new_decl_val = try pt.intern(.{ .aggregate = .{
1871218871 .ty = new_decl_ty.toIntern(),
1871318872 .storage = .{ .bytes = decl.name.toString() },
1871418873 } });
18715 break :v try mod.intern(.{ .slice = .{
18874 break :v try pt.intern(.{ .slice = .{
1871618875 .ty = .slice_const_u8_sentinel_0_type,
18717 .ptr = try mod.intern(.{ .ptr = .{
18876 .ptr = try pt.intern(.{ .ptr = .{
1871818877 .ty = .manyptr_const_u8_sentinel_0_type,
1871918878 .base_addr = .{ .anon_decl = .{
1872018879 .orig_ty = .slice_const_u8_sentinel_0_type,
......@@ -18722,7 +18881,7 @@ fn typeInfoNamespaceDecls(
1872218881 } },
1872318882 .byte_offset = 0,
1872418883 } }),
18725 .len = (try mod.intValue(Type.usize, decl_name_len)).toIntern(),
18884 .len = (try pt.intValue(Type.usize, decl_name_len)).toIntern(),
1872618885 } });
1872718886 };
1872818887
......@@ -18730,7 +18889,7 @@ fn typeInfoNamespaceDecls(
1873018889 //name: [:0]const u8,
1873118890 name_val,
1873218891 };
18733 try decl_vals.append(try mod.intern(.{ .aggregate = .{
18892 try decl_vals.append(try pt.intern(.{ .aggregate = .{
1873418893 .ty = declaration_ty.toIntern(),
1873518894 .storage = .{ .elems = &fields },
1873618895 } }));
......@@ -18782,11 +18941,12 @@ fn zirTypeofLog2IntType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
1878218941}
1878318942
1878418943fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) CompileError!Type {
18785 const mod = sema.mod;
18944 const pt = sema.pt;
18945 const mod = pt.zcu;
1878618946 switch (operand.zigTypeTag(mod)) {
1878718947 .ComptimeInt => return Type.comptime_int,
1878818948 .Int => {
18789 const bits = operand.bitSize(mod);
18949 const bits = operand.bitSize(pt);
1879018950 const count = if (bits == 0)
1879118951 0
1879218952 else blk: {
......@@ -18797,12 +18957,12 @@ fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) Compi
1879718957 }
1879818958 break :blk count;
1879918959 };
18800 return mod.intType(.unsigned, count);
18960 return pt.intType(.unsigned, count);
1880118961 },
1880218962 .Vector => {
1880318963 const elem_ty = operand.elemType2(mod);
1880418964 const log2_elem_ty = try sema.log2IntType(block, elem_ty, src);
18805 return mod.vectorType(.{
18965 return pt.vectorType(.{
1880618966 .len = operand.vectorLen(mod),
1880718967 .child = log2_elem_ty.toIntern(),
1880818968 });
......@@ -18813,7 +18973,7 @@ fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) Compi
1881318973 block,
1881418974 src,
1881518975 "bit shifting operation expected integer type, found '{}'",
18816 .{operand.fmt(mod)},
18976 .{operand.fmt(pt)},
1881718977 );
1881818978}
1881918979
......@@ -18865,7 +19025,8 @@ fn zirBoolNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1886519025 const tracy = trace(@src());
1886619026 defer tracy.end();
1886719027
18868 const mod = sema.mod;
19028 const pt = sema.pt;
19029 const mod = pt.zcu;
1886919030 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1887019031 const src = block.nodeOffset(inst_data.src_node);
1887119032 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
......@@ -18874,7 +19035,7 @@ fn zirBoolNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1887419035 const operand = try sema.coerce(block, Type.bool, uncasted_operand, operand_src);
1887519036 if (try sema.resolveValue(operand)) |val| {
1887619037 return if (val.isUndef(mod))
18877 mod.undefRef(Type.bool)
19038 pt.undefRef(Type.bool)
1887819039 else if (val.toBool()) .bool_false else .bool_true;
1887919040 }
1888019041 try sema.requireRuntimeBlock(block, src, null);
......@@ -18890,7 +19051,8 @@ fn zirBoolBr(
1889019051 const tracy = trace(@src());
1889119052 defer tracy.end();
1889219053
18893 const mod = sema.mod;
19054 const pt = sema.pt;
19055 const mod = pt.zcu;
1889419056 const gpa = sema.gpa;
1889519057
1889619058 const datas = sema.code.instructions.items(.data);
......@@ -19006,7 +19168,8 @@ fn finishCondBr(
1900619168}
1900719169
1900819170fn checkNullableType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
19009 const mod = sema.mod;
19171 const pt = sema.pt;
19172 const mod = pt.zcu;
1901019173 switch (ty.zigTypeTag(mod)) {
1901119174 .Optional, .Null, .Undefined => return,
1901219175 .Pointer => if (ty.isPtrLikeOptional(mod)) return,
......@@ -19038,7 +19201,8 @@ fn zirIsNonNullPtr(
1903819201 const tracy = trace(@src());
1903919202 defer tracy.end();
1904019203
19041 const mod = sema.mod;
19204 const pt = sema.pt;
19205 const mod = pt.zcu;
1904219206 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1904319207 const src = block.nodeOffset(inst_data.src_node);
1904419208 const ptr = try sema.resolveInst(inst_data.operand);
......@@ -19051,11 +19215,12 @@ fn zirIsNonNullPtr(
1905119215}
1905219216
1905319217fn checkErrorType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
19054 const mod = sema.mod;
19218 const pt = sema.pt;
19219 const mod = pt.zcu;
1905519220 switch (ty.zigTypeTag(mod)) {
1905619221 .ErrorSet, .ErrorUnion, .Undefined => return,
1905719222 else => return sema.fail(block, src, "expected error union type, found '{}'", .{
19058 ty.fmt(mod),
19223 ty.fmt(pt),
1905919224 }),
1906019225 }
1906119226}
......@@ -19075,7 +19240,8 @@ fn zirIsNonErrPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
1907519240 const tracy = trace(@src());
1907619241 defer tracy.end();
1907719242
19078 const mod = sema.mod;
19243 const pt = sema.pt;
19244 const mod = pt.zcu;
1907919245 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1908019246 const src = block.nodeOffset(inst_data.src_node);
1908119247 const ptr = try sema.resolveInst(inst_data.operand);
......@@ -19102,7 +19268,8 @@ fn zirCondbr(
1910219268 const tracy = trace(@src());
1910319269 defer tracy.end();
1910419270
19105 const mod = sema.mod;
19271 const pt = sema.pt;
19272 const mod = pt.zcu;
1910619273 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1910719274 const cond_src = parent_block.src(.{ .node_offset_if_cond = inst_data.src_node });
1910819275 const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
......@@ -19177,10 +19344,11 @@ fn zirTry(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!
1917719344 const body = sema.code.bodySlice(extra.end, extra.data.body_len);
1917819345 const err_union = try sema.resolveInst(extra.data.operand);
1917919346 const err_union_ty = sema.typeOf(err_union);
19180 const mod = sema.mod;
19347 const pt = sema.pt;
19348 const mod = pt.zcu;
1918119349 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
1918219350 return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
19183 err_union_ty.fmt(mod),
19351 err_union_ty.fmt(pt),
1918419352 });
1918519353 }
1918619354 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
......@@ -19225,10 +19393,11 @@ fn zirTryPtr(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErr
1922519393 const operand = try sema.resolveInst(extra.data.operand);
1922619394 const err_union = try sema.analyzeLoad(parent_block, src, operand, operand_src);
1922719395 const err_union_ty = sema.typeOf(err_union);
19228 const mod = sema.mod;
19396 const pt = sema.pt;
19397 const mod = pt.zcu;
1922919398 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
1923019399 return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
19231 err_union_ty.fmt(mod),
19400 err_union_ty.fmt(pt),
1923219401 });
1923319402 }
1923419403 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
......@@ -19251,7 +19420,7 @@ fn zirTryPtr(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErr
1925119420
1925219421 const operand_ty = sema.typeOf(operand);
1925319422 const ptr_info = operand_ty.ptrInfo(mod);
19254 const res_ty = try mod.ptrTypeSema(.{
19423 const res_ty = try pt.ptrTypeSema(.{
1925519424 .child = err_union_ty.errorUnionPayload(mod).toIntern(),
1925619425 .flags = .{
1925719426 .is_const = ptr_info.flags.is_const,
......@@ -19366,7 +19535,8 @@ fn zirRetErrValue(
1936619535 block: *Block,
1936719536 inst: Zir.Inst.Index,
1936819537) CompileError!void {
19369 const mod = sema.mod;
19538 const pt = sema.pt;
19539 const mod = pt.zcu;
1937019540 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1937119541 const src = block.tokenOffset(inst_data.src_tok);
1937219542 const err_name = try mod.intern_pool.getOrPutString(
......@@ -19376,8 +19546,8 @@ fn zirRetErrValue(
1937619546 );
1937719547 _ = try mod.getErrorValue(err_name);
1937819548 // Return the error code from the function.
19379 const error_set_type = try mod.singleErrorSetType(err_name);
19380 const result_inst = Air.internedToRef((try mod.intern(.{ .err = .{
19549 const error_set_type = try pt.singleErrorSetType(err_name);
19550 const result_inst = Air.internedToRef((try pt.intern(.{ .err = .{
1938119551 .ty = error_set_type.toIntern(),
1938219552 .name = err_name,
1938319553 } })));
......@@ -19392,7 +19562,8 @@ fn zirRetImplicit(
1939219562 const tracy = trace(@src());
1939319563 defer tracy.end();
1939419564
19395 const mod = sema.mod;
19565 const pt = sema.pt;
19566 const mod = pt.zcu;
1939619567 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
1939719568 const r_brace_src = block.tokenOffset(inst_data.src_tok);
1939819569 if (block.inlining == null and sema.func_is_naked) {
......@@ -19412,7 +19583,7 @@ fn zirRetImplicit(
1941219583 if (base_tag == .NoReturn) {
1941319584 const msg = msg: {
1941419585 const msg = try sema.errMsg(ret_ty_src, "function declared '{}' implicitly returns", .{
19415 sema.fn_ret_ty.fmt(mod),
19586 sema.fn_ret_ty.fmt(pt),
1941619587 });
1941719588 errdefer msg.destroy(sema.gpa);
1941819589 try sema.errNote(r_brace_src, msg, "control flow reaches end of body here", .{});
......@@ -19422,7 +19593,7 @@ fn zirRetImplicit(
1942219593 } else if (base_tag != .Void) {
1942319594 const msg = msg: {
1942419595 const msg = try sema.errMsg(ret_ty_src, "function with non-void return type '{}' implicitly returns", .{
19425 sema.fn_ret_ty.fmt(mod),
19596 sema.fn_ret_ty.fmt(pt),
1942619597 });
1942719598 errdefer msg.destroy(sema.gpa);
1942819599 try sema.errNote(r_brace_src, msg, "control flow reaches end of body here", .{});
......@@ -19474,7 +19645,7 @@ fn retWithErrTracing(
1947419645 ret_tag: Air.Inst.Tag,
1947519646 operand: Air.Inst.Ref,
1947619647) CompileError!void {
19477 const mod = sema.mod;
19648 const pt = sema.pt;
1947819649 const need_check = switch (is_non_err) {
1947919650 .bool_true => {
1948019651 _ = try block.addUnOp(ret_tag, operand);
......@@ -19484,11 +19655,11 @@ fn retWithErrTracing(
1948419655 else => true,
1948519656 };
1948619657 const gpa = sema.gpa;
19487 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
19488 try stack_trace_ty.resolveFields(mod);
19489 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
19658 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
19659 try stack_trace_ty.resolveFields(pt);
19660 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
1949019661 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
19491 const return_err_fn = try mod.getBuiltin("returnError");
19662 const return_err_fn = try pt.getBuiltin("returnError");
1949219663 const args: [1]Air.Inst.Ref = .{err_return_trace};
1949319664
1949419665 if (!need_check) {
......@@ -19524,12 +19695,14 @@ fn retWithErrTracing(
1952419695}
1952519696
1952619697fn wantErrorReturnTracing(sema: *Sema, fn_ret_ty: Type) bool {
19527 const mod = sema.mod;
19698 const pt = sema.pt;
19699 const mod = pt.zcu;
1952819700 return fn_ret_ty.isError(mod) and mod.comp.config.any_error_tracing;
1952919701}
1953019702
1953119703fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
19532 const mod = sema.mod;
19704 const pt = sema.pt;
19705 const mod = pt.zcu;
1953319706 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].save_err_ret_index;
1953419707
1953519708 if (!block.ownerModule().error_tracing) return;
......@@ -19559,7 +19732,8 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1955919732 const tracy = trace(@src());
1956019733 defer tracy.end();
1956119734
19562 const mod = sema.mod;
19735 const pt = sema.pt;
19736 const mod = pt.zcu;
1956319737
1956419738 const saved_index = if (target_block.toIndexAllowNone()) |zir_block| b: {
1956519739 var block = start_block;
......@@ -19597,7 +19771,7 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1959719771 if (is_non_error) return;
1959819772
1959919773 const saved_index_val = try sema.resolveDefinedValue(start_block, src, saved_index);
19600 const saved_index_int = saved_index_val.?.toUnsignedInt(mod);
19774 const saved_index_int = saved_index_val.?.toUnsignedInt(pt);
1960119775 assert(saved_index_int <= sema.comptime_err_ret_trace.items.len);
1960219776 sema.comptime_err_ret_trace.items.len = @intCast(saved_index_int);
1960319777 return;
......@@ -19612,7 +19786,8 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1961219786}
1961319787
1961419788fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
19615 const mod = sema.mod;
19789 const pt = sema.pt;
19790 const mod = pt.zcu;
1961619791 const ip = &mod.intern_pool;
1961719792 assert(sema.fn_ret_ty.zigTypeTag(mod) == .ErrorUnion);
1961819793 const err_set_ty = sema.fn_ret_ty.errorUnionSet(mod).toIntern();
......@@ -19632,7 +19807,8 @@ fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
1963219807
1963319808fn addToInferredErrorSetPtr(sema: *Sema, ies: *InferredErrorSet, op_ty: Type) !void {
1963419809 const arena = sema.arena;
19635 const mod = sema.mod;
19810 const pt = sema.pt;
19811 const mod = pt.zcu;
1963619812 const ip = &mod.intern_pool;
1963719813 switch (op_ty.zigTypeTag(mod)) {
1963819814 .ErrorSet => try ies.addErrorSet(op_ty, ip, arena),
......@@ -19651,7 +19827,8 @@ fn analyzeRet(
1965119827 // Special case for returning an error to an inferred error set; we need to
1965219828 // add the error tag to the inferred error set of the in-scope function, so
1965319829 // that the coercion below works correctly.
19654 const mod = sema.mod;
19830 const pt = sema.pt;
19831 const mod = pt.zcu;
1965519832 if (sema.fn_ret_ty_ies != null and sema.fn_ret_ty.zigTypeTag(mod) == .ErrorUnion) {
1965619833 try sema.addToInferredErrorSet(uncasted_operand);
1965719834 }
......@@ -19691,7 +19868,7 @@ fn analyzeRet(
1969119868 return sema.failWithOwnedErrorMsg(block, msg);
1969219869 }
1969319870
19694 try sema.fn_ret_ty.resolveLayout(mod);
19871 try sema.fn_ret_ty.resolveLayout(pt);
1969519872
1969619873 try sema.validateRuntimeValue(block, operand_src, operand);
1969719874
......@@ -19718,7 +19895,8 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1971819895 const tracy = trace(@src());
1971919896 defer tracy.end();
1972019897
19721 const mod = sema.mod;
19898 const pt = sema.pt;
19899 const mod = pt.zcu;
1972219900 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].ptr_type;
1972319901 const extra = sema.code.extraData(Zir.Inst.PtrType, inst_data.payload_index);
1972419902 const elem_ty_src = block.src(.{ .node_offset_ptr_elem = extra.data.src_node });
......@@ -19773,7 +19951,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1977319951 },
1977419952 else => {},
1977519953 }
19776 const align_bytes = (try val.getUnsignedIntAdvanced(mod, .sema)).?;
19954 const align_bytes = (try val.getUnsignedIntAdvanced(pt, .sema)).?;
1977719955 break :blk try sema.validateAlignAllowZero(block, align_src, align_bytes);
1977819956 } else .none;
1977919957
......@@ -19804,13 +19982,13 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1980419982 if (host_size != 0) {
1980519983 if (bit_offset >= host_size * 8) {
1980619984 return sema.fail(block, bitoffset_src, "packed type '{}' at bit offset {} starts {} bits after the end of a {} byte host integer", .{
19807 elem_ty.fmt(mod), bit_offset, bit_offset - host_size * 8, host_size,
19985 elem_ty.fmt(pt), bit_offset, bit_offset - host_size * 8, host_size,
1980819986 });
1980919987 }
19810 const elem_bit_size = try elem_ty.bitSizeAdvanced(mod, .sema);
19988 const elem_bit_size = try elem_ty.bitSizeAdvanced(pt, .sema);
1981119989 if (elem_bit_size > host_size * 8 - bit_offset) {
1981219990 return sema.fail(block, bitoffset_src, "packed type '{}' at bit offset {} ends {} bits after the end of a {} byte host integer", .{
19813 elem_ty.fmt(mod), bit_offset, elem_bit_size - (host_size * 8 - bit_offset), host_size,
19991 elem_ty.fmt(pt), bit_offset, elem_bit_size - (host_size * 8 - bit_offset), host_size,
1981419992 });
1981519993 }
1981619994 }
......@@ -19824,7 +20002,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1982420002 } else if (inst_data.size == .C) {
1982520003 if (!try sema.validateExternType(elem_ty, .other)) {
1982620004 const msg = msg: {
19827 const msg = try sema.errMsg(elem_ty_src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(mod)});
20005 const msg = try sema.errMsg(elem_ty_src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(pt)});
1982820006 errdefer msg.destroy(sema.gpa);
1982920007
1983020008 try sema.explainWhyTypeIsNotExtern(msg, elem_ty_src, elem_ty, .other);
......@@ -19841,14 +20019,14 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1984120019
1984220020 if (host_size != 0 and !try sema.validatePackedType(elem_ty)) {
1984320021 return sema.failWithOwnedErrorMsg(block, msg: {
19844 const msg = try sema.errMsg(elem_ty_src, "bit-pointer cannot refer to value of type '{}'", .{elem_ty.fmt(mod)});
20022 const msg = try sema.errMsg(elem_ty_src, "bit-pointer cannot refer to value of type '{}'", .{elem_ty.fmt(pt)});
1984520023 errdefer msg.destroy(sema.gpa);
1984620024 try sema.explainWhyTypeIsNotPacked(msg, elem_ty_src, elem_ty);
1984720025 break :msg msg;
1984820026 });
1984920027 }
1985020028
19851 const ty = try mod.ptrTypeSema(.{
20029 const ty = try pt.ptrTypeSema(.{
1985220030 .child = elem_ty.toIntern(),
1985320031 .sentinel = sentinel,
1985420032 .flags = .{
......@@ -19875,7 +20053,8 @@ fn zirStructInitEmpty(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
1987520053 const src = block.nodeOffset(inst_data.src_node);
1987620054 const ty_src = block.src(.{ .node_offset_init_ty = inst_data.src_node });
1987720055 const obj_ty = try sema.resolveType(block, ty_src, inst_data.operand);
19878 const mod = sema.mod;
20056 const pt = sema.pt;
20057 const mod = pt.zcu;
1987920058
1988020059 switch (obj_ty.zigTypeTag(mod)) {
1988120060 .Struct => return sema.structInitEmpty(block, obj_ty, src, src),
......@@ -19890,7 +20069,8 @@ fn zirStructInitEmptyResult(sema: *Sema, block: *Block, inst: Zir.Inst.Index, is
1989020069 const tracy = trace(@src());
1989120070 defer tracy.end();
1989220071
19893 const mod = sema.mod;
20072 const pt = sema.pt;
20073 const mod = pt.zcu;
1989420074 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1989520075 const src = block.nodeOffset(inst_data.src_node);
1989620076 const ty_operand = sema.resolveType(block, src, inst_data.operand) catch |err| switch (err) {
......@@ -19905,7 +20085,7 @@ fn zirStructInitEmptyResult(sema: *Sema, block: *Block, inst: Zir.Inst.Index, is
1990520085 break :ty ptr_ty.childType(mod);
1990620086 }
1990720087 // To make `&.{}` a `[:s]T`, the init should be a `[0:s]T`.
19908 break :ty try mod.arrayType(.{
20088 break :ty try pt.arrayType(.{
1990920089 .len = 0,
1991020090 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
1991120091 .child = ptr_ty.childType(mod).toIntern(),
......@@ -19936,10 +20116,11 @@ fn structInitEmpty(
1993620116 dest_src: LazySrcLoc,
1993720117 init_src: LazySrcLoc,
1993820118) CompileError!Air.Inst.Ref {
19939 const mod = sema.mod;
20119 const pt = sema.pt;
20120 const mod = pt.zcu;
1994020121 const gpa = sema.gpa;
1994120122 // This logic must be synchronized with that in `zirStructInit`.
19942 try struct_ty.resolveFields(mod);
20123 try struct_ty.resolveFields(pt);
1994320124
1994420125 // The init values to use for the struct instance.
1994520126 const field_inits = try gpa.alloc(Air.Inst.Ref, struct_ty.structFieldCount(mod));
......@@ -19950,7 +20131,8 @@ fn structInitEmpty(
1995020131}
1995120132
1995220133fn arrayInitEmpty(sema: *Sema, block: *Block, src: LazySrcLoc, obj_ty: Type) CompileError!Air.Inst.Ref {
19953 const mod = sema.mod;
20134 const pt = sema.pt;
20135 const mod = pt.zcu;
1995420136 const arr_len = obj_ty.arrayLen(mod);
1995520137 if (arr_len != 0) {
1995620138 if (obj_ty.zigTypeTag(mod) == .Array) {
......@@ -19959,21 +20141,22 @@ fn arrayInitEmpty(sema: *Sema, block: *Block, src: LazySrcLoc, obj_ty: Type) Com
1995920141 return sema.fail(block, src, "expected {d} vector elements; found 0", .{arr_len});
1996020142 }
1996120143 }
19962 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
20144 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1996320145 .ty = obj_ty.toIntern(),
1996420146 .storage = .{ .elems = &.{} },
1996520147 } })));
1996620148}
1996720149
1996820150fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20151 const pt = sema.pt;
1996920152 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1997020153 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1997120154 const field_src = block.builtinCallArgSrc(inst_data.src_node, 1);
1997220155 const init_src = block.builtinCallArgSrc(inst_data.src_node, 2);
1997320156 const extra = sema.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;
1997420157 const union_ty = try sema.resolveType(block, ty_src, extra.union_type);
19975 if (union_ty.zigTypeTag(sema.mod) != .Union) {
19976 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(sema.mod)});
20158 if (union_ty.zigTypeTag(pt.zcu) != .Union) {
20159 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(pt)});
1997720160 }
1997820161 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{
1997920162 .needed_comptime_reason = "name of field being initialized must be comptime-known",
......@@ -19992,7 +20175,8 @@ fn unionInit(
1999220175 field_name: InternPool.NullTerminatedString,
1999320176 field_src: LazySrcLoc,
1999420177) CompileError!Air.Inst.Ref {
19995 const mod = sema.mod;
20178 const pt = sema.pt;
20179 const mod = pt.zcu;
1999620180 const ip = &mod.intern_pool;
1999720181 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
1999820182 const field_ty = Type.fromInterned(mod.typeToUnion(union_ty).?.field_types.get(ip)[field_index]);
......@@ -20000,8 +20184,8 @@ fn unionInit(
2000020184
2000120185 if (try sema.resolveValue(init)) |init_val| {
2000220186 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
20003 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
20004 return Air.internedToRef((try mod.intern(.{ .un = .{
20187 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
20188 return Air.internedToRef((try pt.intern(.{ .un = .{
2000520189 .ty = union_ty.toIntern(),
2000620190 .tag = tag_val.toIntern(),
2000720191 .val = init_val.toIntern(),
......@@ -20025,7 +20209,8 @@ fn zirStructInit(
2002520209 const extra = sema.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);
2002620210 const src = block.nodeOffset(inst_data.src_node);
2002720211
20028 const mod = sema.mod;
20212 const pt = sema.pt;
20213 const mod = pt.zcu;
2002920214 const ip = &mod.intern_pool;
2003020215 const first_item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end).data;
2003120216 const first_field_type_data = zir_datas[@intFromEnum(first_item.field_type)].pl_node;
......@@ -20038,7 +20223,7 @@ fn zirStructInit(
2003820223 else => |e| return e,
2003920224 };
2004020225 const resolved_ty = result_ty.optEuBaseType(mod);
20041 try resolved_ty.resolveLayout(mod);
20226 try resolved_ty.resolveLayout(pt);
2004220227
2004320228 if (resolved_ty.zigTypeTag(mod) == .Struct) {
2004420229 // This logic must be synchronized with that in `zirStructInitEmpty`.
......@@ -20079,8 +20264,8 @@ fn zirStructInit(
2007920264 const field_ty = resolved_ty.structFieldType(field_index, mod);
2008020265 field_inits[field_index] = try sema.coerce(block, field_ty, uncoerced_init, field_src);
2008120266 if (!is_packed) {
20082 try resolved_ty.resolveStructFieldInits(mod);
20083 if (try resolved_ty.structFieldValueComptime(mod, field_index)) |default_value| {
20267 try resolved_ty.resolveStructFieldInits(pt);
20268 if (try resolved_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2008420269 const init_val = (try sema.resolveValue(field_inits[field_index])) orelse {
2008520270 return sema.failWithNeededComptime(block, field_src, .{
2008620271 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
......@@ -20112,7 +20297,7 @@ fn zirStructInit(
2011220297 );
2011320298 const field_index = try sema.unionFieldIndex(block, resolved_ty, field_name, field_src);
2011420299 const tag_ty = resolved_ty.unionTagTypeHypothetical(mod);
20115 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
20300 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
2011620301 const field_ty = Type.fromInterned(mod.typeToUnion(resolved_ty).?.field_types.get(ip)[field_index]);
2011720302
2011820303 if (field_ty.zigTypeTag(mod) == .NoReturn) {
......@@ -20132,11 +20317,11 @@ fn zirStructInit(
2013220317 const init_inst = try sema.coerce(block, field_ty, uncoerced_init_inst, field_src);
2013320318
2013420319 if (try sema.resolveValue(init_inst)) |val| {
20135 const struct_val = Value.fromInterned((try mod.intern(.{ .un = .{
20320 const struct_val = Value.fromInterned(try pt.intern(.{ .un = .{
2013620321 .ty = resolved_ty.toIntern(),
2013720322 .tag = tag_val.toIntern(),
2013820323 .val = val.toIntern(),
20139 } })));
20324 } }));
2014020325 const final_val_inst = try sema.coerce(block, result_ty, Air.internedToRef(struct_val.toIntern()), src);
2014120326 const final_val = (try sema.resolveValue(final_val_inst)).?;
2014220327 return sema.addConstantMaybeRef(final_val.toIntern(), is_ref);
......@@ -20152,7 +20337,7 @@ fn zirStructInit(
2015220337
2015320338 if (is_ref) {
2015420339 const target = mod.getTarget();
20155 const alloc_ty = try mod.ptrTypeSema(.{
20340 const alloc_ty = try pt.ptrTypeSema(.{
2015620341 .child = result_ty.toIntern(),
2015720342 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2015820343 });
......@@ -20182,7 +20367,8 @@ fn finishStructInit(
2018220367 result_ty: Type,
2018320368 is_ref: bool,
2018420369) CompileError!Air.Inst.Ref {
20185 const mod = sema.mod;
20370 const pt = sema.pt;
20371 const mod = pt.zcu;
2018620372 const ip = &mod.intern_pool;
2018720373
2018820374 var root_msg: ?*Module.ErrorMsg = null;
......@@ -20242,7 +20428,7 @@ fn finishStructInit(
2024220428 continue;
2024320429 }
2024420430
20245 try struct_ty.resolveStructFieldInits(mod);
20431 try struct_ty.resolveStructFieldInits(pt);
2024620432
2024720433 const field_init = struct_type.fieldInit(ip, i);
2024820434 if (field_init == .none) {
......@@ -20289,7 +20475,7 @@ fn finishStructInit(
2028920475 for (elems, field_inits) |*elem, field_init| {
2029020476 elem.* = (sema.resolveValue(field_init) catch unreachable).?.toIntern();
2029120477 }
20292 const struct_val = try mod.intern(.{ .aggregate = .{
20478 const struct_val = try pt.intern(.{ .aggregate = .{
2029320479 .ty = struct_ty.toIntern(),
2029420480 .storage = .{ .elems = elems },
2029520481 } });
......@@ -20312,9 +20498,9 @@ fn finishStructInit(
2031220498 }
2031320499
2031420500 if (is_ref) {
20315 try struct_ty.resolveLayout(mod);
20316 const target = sema.mod.getTarget();
20317 const alloc_ty = try mod.ptrTypeSema(.{
20501 try struct_ty.resolveLayout(pt);
20502 const target = mod.getTarget();
20503 const alloc_ty = try pt.ptrTypeSema(.{
2031820504 .child = result_ty.toIntern(),
2031920505 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2032020506 });
......@@ -20334,7 +20520,7 @@ fn finishStructInit(
2033420520 .init_node_offset = init_src.offset.node_offset.x,
2033520521 .elem_index = @intCast(runtime_index),
2033620522 } }));
20337 try struct_ty.resolveStructFieldInits(mod);
20523 try struct_ty.resolveStructFieldInits(pt);
2033820524 const struct_val = try block.addAggregateInit(struct_ty, field_inits);
2033920525 return sema.coerce(block, result_ty, struct_val, init_src);
2034020526}
......@@ -20364,7 +20550,8 @@ fn structInitAnon(
2036420550 extra_end: usize,
2036520551 is_ref: bool,
2036620552) CompileError!Air.Inst.Ref {
20367 const mod = sema.mod;
20553 const pt = sema.pt;
20554 const mod = pt.zcu;
2036820555 const gpa = sema.gpa;
2036920556 const ip = &mod.intern_pool;
2037020557 const zir_datas = sema.code.instructions.items(.data);
......@@ -20422,14 +20609,14 @@ fn structInitAnon(
2042220609 break :rs runtime_index;
2042320610 };
2042420611
20425 const tuple_ty = try ip.getAnonStructType(gpa, .{
20612 const tuple_ty = try ip.getAnonStructType(gpa, pt.tid, .{
2042620613 .names = names,
2042720614 .types = types,
2042820615 .values = values,
2042920616 });
2043020617
2043120618 const runtime_index = opt_runtime_index orelse {
20432 const tuple_val = try mod.intern(.{ .aggregate = .{
20619 const tuple_val = try pt.intern(.{ .aggregate = .{
2043320620 .ty = tuple_ty,
2043420621 .storage = .{ .elems = values },
2043520622 } });
......@@ -20443,7 +20630,7 @@ fn structInitAnon(
2044320630
2044420631 if (is_ref) {
2044520632 const target = mod.getTarget();
20446 const alloc_ty = try mod.ptrTypeSema(.{
20633 const alloc_ty = try pt.ptrTypeSema(.{
2044720634 .child = tuple_ty,
2044820635 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2044920636 });
......@@ -20457,7 +20644,7 @@ fn structInitAnon(
2045720644 };
2045820645 extra_index = item.end;
2045920646
20460 const field_ptr_ty = try mod.ptrTypeSema(.{
20647 const field_ptr_ty = try pt.ptrTypeSema(.{
2046120648 .child = field_ty,
2046220649 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2046320650 });
......@@ -20491,7 +20678,8 @@ fn zirArrayInit(
2049120678 inst: Zir.Inst.Index,
2049220679 is_ref: bool,
2049320680) CompileError!Air.Inst.Ref {
20494 const mod = sema.mod;
20681 const pt = sema.pt;
20682 const mod = pt.zcu;
2049520683 const gpa = sema.gpa;
2049620684 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2049720685 const src = block.nodeOffset(inst_data.src_node);
......@@ -20550,8 +20738,8 @@ fn zirArrayInit(
2055020738 dest.* = try sema.coerce(block, elem_ty, resolved_arg, elem_src);
2055120739 if (is_tuple) {
2055220740 if (array_ty.structFieldIsComptime(i, mod))
20553 try array_ty.resolveStructFieldInits(mod);
20554 if (try array_ty.structFieldValueComptime(mod, i)) |field_val| {
20741 try array_ty.resolveStructFieldInits(pt);
20742 if (try array_ty.structFieldValueComptime(pt, i)) |field_val| {
2055520743 const init_val = try sema.resolveValue(dest.*) orelse {
2055620744 return sema.failWithNeededComptime(block, elem_src, .{
2055720745 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
......@@ -20581,7 +20769,7 @@ fn zirArrayInit(
2058120769 // We checked that all args are comptime above.
2058220770 val.* = (sema.resolveValue(arg) catch unreachable).?.toIntern();
2058320771 }
20584 const arr_val = try mod.intern(.{ .aggregate = .{
20772 const arr_val = try pt.intern(.{ .aggregate = .{
2058520773 .ty = array_ty.toIntern(),
2058620774 .storage = .{ .elems = elem_vals },
2058720775 } });
......@@ -20597,7 +20785,7 @@ fn zirArrayInit(
2059720785
2059820786 if (is_ref) {
2059920787 const target = mod.getTarget();
20600 const alloc_ty = try mod.ptrTypeSema(.{
20788 const alloc_ty = try pt.ptrTypeSema(.{
2060120789 .child = result_ty.toIntern(),
2060220790 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2060320791 });
......@@ -20606,27 +20794,27 @@ fn zirArrayInit(
2060620794
2060720795 if (is_tuple) {
2060820796 for (resolved_args, 0..) |arg, i| {
20609 const elem_ptr_ty = try mod.ptrTypeSema(.{
20797 const elem_ptr_ty = try pt.ptrTypeSema(.{
2061020798 .child = array_ty.structFieldType(i, mod).toIntern(),
2061120799 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2061220800 });
2061320801 const elem_ptr_ty_ref = Air.internedToRef(elem_ptr_ty.toIntern());
2061420802
20615 const index = try mod.intRef(Type.usize, i);
20803 const index = try pt.intRef(Type.usize, i);
2061620804 const elem_ptr = try block.addPtrElemPtrTypeRef(base_ptr, index, elem_ptr_ty_ref);
2061720805 _ = try block.addBinOp(.store, elem_ptr, arg);
2061820806 }
2061920807 return sema.makePtrConst(block, alloc);
2062020808 }
2062120809
20622 const elem_ptr_ty = try mod.ptrTypeSema(.{
20810 const elem_ptr_ty = try pt.ptrTypeSema(.{
2062320811 .child = array_ty.elemType2(mod).toIntern(),
2062420812 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2062520813 });
2062620814 const elem_ptr_ty_ref = Air.internedToRef(elem_ptr_ty.toIntern());
2062720815
2062820816 for (resolved_args, 0..) |arg, i| {
20629 const index = try mod.intRef(Type.usize, i);
20817 const index = try pt.intRef(Type.usize, i);
2063020818 const elem_ptr = try block.addPtrElemPtrTypeRef(base_ptr, index, elem_ptr_ty_ref);
2063120819 _ = try block.addBinOp(.store, elem_ptr, arg);
2063220820 }
......@@ -20656,7 +20844,8 @@ fn arrayInitAnon(
2065620844 operands: []const Zir.Inst.Ref,
2065720845 is_ref: bool,
2065820846) CompileError!Air.Inst.Ref {
20659 const mod = sema.mod;
20847 const pt = sema.pt;
20848 const mod = pt.zcu;
2066020849 const gpa = sema.gpa;
2066120850 const ip = &mod.intern_pool;
2066220851
......@@ -20689,14 +20878,14 @@ fn arrayInitAnon(
2068920878 break :rs runtime_src;
2069020879 };
2069120880
20692 const tuple_ty = try ip.getAnonStructType(gpa, .{
20881 const tuple_ty = try ip.getAnonStructType(gpa, pt.tid, .{
2069320882 .types = types,
2069420883 .values = values,
2069520884 .names = &.{},
2069620885 });
2069720886
2069820887 const runtime_src = opt_runtime_src orelse {
20699 const tuple_val = try mod.intern(.{ .aggregate = .{
20888 const tuple_val = try pt.intern(.{ .aggregate = .{
2070020889 .ty = tuple_ty,
2070120890 .storage = .{ .elems = values },
2070220891 } });
......@@ -20706,15 +20895,15 @@ fn arrayInitAnon(
2070620895 try sema.requireRuntimeBlock(block, src, runtime_src);
2070720896
2070820897 if (is_ref) {
20709 const target = sema.mod.getTarget();
20710 const alloc_ty = try mod.ptrTypeSema(.{
20898 const target = sema.pt.zcu.getTarget();
20899 const alloc_ty = try pt.ptrTypeSema(.{
2071120900 .child = tuple_ty,
2071220901 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2071320902 });
2071420903 const alloc = try block.addTy(.alloc, alloc_ty);
2071520904 for (operands, 0..) |operand, i_usize| {
2071620905 const i: u32 = @intCast(i_usize);
20717 const field_ptr_ty = try mod.ptrTypeSema(.{
20906 const field_ptr_ty = try pt.ptrTypeSema(.{
2071820907 .child = types[i],
2071920908 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2072020909 });
......@@ -20752,7 +20941,8 @@ fn zirFieldTypeRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2075220941}
2075320942
2075420943fn zirStructInitFieldType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20755 const mod = sema.mod;
20944 const pt = sema.pt;
20945 const mod = pt.zcu;
2075620946 const ip = &mod.intern_pool;
2075720947 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2075820948 const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
......@@ -20780,11 +20970,12 @@ fn fieldType(
2078020970 field_src: LazySrcLoc,
2078120971 ty_src: LazySrcLoc,
2078220972) CompileError!Air.Inst.Ref {
20783 const mod = sema.mod;
20973 const pt = sema.pt;
20974 const mod = pt.zcu;
2078420975 const ip = &mod.intern_pool;
2078520976 var cur_ty = aggregate_ty;
2078620977 while (true) {
20787 try cur_ty.resolveFields(mod);
20978 try cur_ty.resolveFields(pt);
2078820979 switch (cur_ty.zigTypeTag(mod)) {
2078920980 .Struct => switch (ip.indexToKey(cur_ty.toIntern())) {
2079020981 .anon_struct_type => |anon_struct| {
......@@ -20823,7 +21014,7 @@ fn fieldType(
2082321014 else => {},
2082421015 }
2082521016 return sema.fail(block, ty_src, "expected struct or union; found '{}'", .{
20826 cur_ty.fmt(sema.mod),
21017 cur_ty.fmt(pt),
2082721018 });
2082821019 }
2082921020}
......@@ -20833,12 +21024,13 @@ fn zirErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
2083321024}
2083421025
2083521026fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
20836 const mod = sema.mod;
21027 const pt = sema.pt;
21028 const mod = pt.zcu;
2083721029 const ip = &mod.intern_pool;
20838 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
20839 try stack_trace_ty.resolveFields(mod);
20840 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
20841 const opt_ptr_stack_trace_ty = try mod.optionalType(ptr_stack_trace_ty.toIntern());
21030 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
21031 try stack_trace_ty.resolveFields(pt);
21032 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
21033 const opt_ptr_stack_trace_ty = try pt.optionalType(ptr_stack_trace_ty.toIntern());
2084221034
2084321035 if (sema.owner_func_index != .none and
2084421036 ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn and
......@@ -20846,7 +21038,7 @@ fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
2084621038 {
2084721039 return block.addTy(.err_return_trace, opt_ptr_stack_trace_ty);
2084821040 }
20849 return Air.internedToRef((try mod.intern(.{ .opt = .{
21041 return Air.internedToRef((try pt.intern(.{ .opt = .{
2085021042 .ty = opt_ptr_stack_trace_ty.toIntern(),
2085121043 .val = .none,
2085221044 } })));
......@@ -20862,19 +21054,20 @@ fn zirFrame(
2086221054}
2086321055
2086421056fn zirAlignOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20865 const mod = sema.mod;
21057 const pt = sema.pt;
2086621058 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2086721059 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2086821060 const ty = try sema.resolveType(block, operand_src, inst_data.operand);
20869 if (ty.isNoReturn(mod)) {
20870 return sema.fail(block, operand_src, "no align available for type '{}'", .{ty.fmt(sema.mod)});
21061 if (ty.isNoReturn(pt.zcu)) {
21062 return sema.fail(block, operand_src, "no align available for type '{}'", .{ty.fmt(pt)});
2087121063 }
20872 const val = try ty.lazyAbiAlignment(mod);
21064 const val = try ty.lazyAbiAlignment(pt);
2087321065 return Air.internedToRef(val.toIntern());
2087421066}
2087521067
2087621068fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20877 const mod = sema.mod;
21069 const pt = sema.pt;
21070 const mod = pt.zcu;
2087821071 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2087921072 const src = block.nodeOffset(inst_data.src_node);
2088021073 const operand = try sema.resolveInst(inst_data.operand);
......@@ -20886,25 +21079,25 @@ fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2088621079 }
2088721080 if (try sema.resolveValue(operand)) |val| {
2088821081 if (!is_vector) {
20889 if (val.isUndef(mod)) return mod.undefRef(Type.u1);
20890 if (val.toBool()) return Air.internedToRef((try mod.intValue(Type.u1, 1)).toIntern());
20891 return Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
21082 if (val.isUndef(mod)) return pt.undefRef(Type.u1);
21083 if (val.toBool()) return Air.internedToRef((try pt.intValue(Type.u1, 1)).toIntern());
21084 return Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
2089221085 }
2089321086 const len = operand_ty.vectorLen(mod);
20894 const dest_ty = try mod.vectorType(.{ .child = .u1_type, .len = len });
20895 if (val.isUndef(mod)) return mod.undefRef(dest_ty);
21087 const dest_ty = try pt.vectorType(.{ .child = .u1_type, .len = len });
21088 if (val.isUndef(mod)) return pt.undefRef(dest_ty);
2089621089 const new_elems = try sema.arena.alloc(InternPool.Index, len);
2089721090 for (new_elems, 0..) |*new_elem, i| {
20898 const old_elem = try val.elemValue(mod, i);
21091 const old_elem = try val.elemValue(pt, i);
2089921092 const new_val = if (old_elem.isUndef(mod))
20900 try mod.undefValue(Type.u1)
21093 try pt.undefValue(Type.u1)
2090121094 else if (old_elem.toBool())
20902 try mod.intValue(Type.u1, 1)
21095 try pt.intValue(Type.u1, 1)
2090321096 else
20904 try mod.intValue(Type.u1, 0);
21097 try pt.intValue(Type.u1, 0);
2090521098 new_elem.* = new_val.toIntern();
2090621099 }
20907 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
21100 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2090821101 .ty = dest_ty.toIntern(),
2090921102 .storage = .{ .elems = new_elems },
2091021103 } }));
......@@ -20913,10 +21106,10 @@ fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2091321106 return block.addUnOp(.int_from_bool, operand);
2091421107 }
2091521108 const len = operand_ty.vectorLen(mod);
20916 const dest_ty = try mod.vectorType(.{ .child = .u1_type, .len = len });
21109 const dest_ty = try pt.vectorType(.{ .child = .u1_type, .len = len });
2091721110 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2091821111 for (new_elems, 0..) |*new_elem, i| {
20919 const idx_ref = try mod.intRef(Type.usize, i);
21112 const idx_ref = try pt.intRef(Type.usize, i);
2092021113 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2092121114 new_elem.* = try block.addUnOp(.int_from_bool, old_elem);
2092221115 }
......@@ -20930,7 +21123,7 @@ fn zirErrorName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2093021123 const operand = try sema.coerce(block, Type.anyerror, uncoerced_operand, operand_src);
2093121124
2093221125 if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
20933 const err_name = sema.mod.intern_pool.indexToKey(val.toIntern()).err.name;
21126 const err_name = sema.pt.zcu.intern_pool.indexToKey(val.toIntern()).err.name;
2093421127 return sema.addNullTerminatedStrLit(err_name);
2093521128 }
2093621129
......@@ -20944,7 +21137,8 @@ fn zirAbs(
2094421137 block: *Block,
2094521138 inst: Zir.Inst.Index,
2094621139) CompileError!Air.Inst.Ref {
20947 const mod = sema.mod;
21140 const pt = sema.pt;
21141 const mod = pt.zcu;
2094821142 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2094921143 const operand = try sema.resolveInst(inst_data.operand);
2095021144 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -20953,12 +21147,12 @@ fn zirAbs(
2095321147
2095421148 const result_ty = switch (scalar_ty.zigTypeTag(mod)) {
2095521149 .ComptimeFloat, .Float, .ComptimeInt => operand_ty,
20956 .Int => if (scalar_ty.isSignedInt(mod)) try operand_ty.toUnsigned(mod) else return operand,
21150 .Int => if (scalar_ty.isSignedInt(mod)) try operand_ty.toUnsigned(pt) else return operand,
2095721151 else => return sema.fail(
2095821152 block,
2095921153 operand_src,
2096021154 "expected integer, float, or vector of either integers or floats, found '{}'",
20961 .{operand_ty.fmt(mod)},
21155 .{operand_ty.fmt(pt)},
2096221156 ),
2096321157 };
2096421158
......@@ -20972,30 +21166,31 @@ fn maybeConstantUnaryMath(
2097221166 sema: *Sema,
2097321167 operand: Air.Inst.Ref,
2097421168 result_ty: Type,
20975 comptime eval: fn (Value, Type, Allocator, *Module) Allocator.Error!Value,
21169 comptime eval: fn (Value, Type, Allocator, Zcu.PerThread) Allocator.Error!Value,
2097621170) CompileError!?Air.Inst.Ref {
20977 const mod = sema.mod;
21171 const pt = sema.pt;
21172 const mod = pt.zcu;
2097821173 switch (result_ty.zigTypeTag(mod)) {
2097921174 .Vector => if (try sema.resolveValue(operand)) |val| {
2098021175 const scalar_ty = result_ty.scalarType(mod);
2098121176 const vec_len = result_ty.vectorLen(mod);
2098221177 if (val.isUndef(mod))
20983 return try mod.undefRef(result_ty);
21178 return try pt.undefRef(result_ty);
2098421179
2098521180 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2098621181 for (elems, 0..) |*elem, i| {
20987 const elem_val = try val.elemValue(sema.mod, i);
20988 elem.* = (try eval(elem_val, scalar_ty, sema.arena, sema.mod)).toIntern();
21182 const elem_val = try val.elemValue(pt, i);
21183 elem.* = (try eval(elem_val, scalar_ty, sema.arena, pt)).toIntern();
2098921184 }
20990 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
21185 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2099121186 .ty = result_ty.toIntern(),
2099221187 .storage = .{ .elems = elems },
2099321188 } })));
2099421189 },
2099521190 else => if (try sema.resolveValue(operand)) |operand_val| {
2099621191 if (operand_val.isUndef(mod))
20997 return try mod.undefRef(result_ty);
20998 const result_val = try eval(operand_val, result_ty, sema.arena, sema.mod);
21192 return try pt.undefRef(result_ty);
21193 const result_val = try eval(operand_val, result_ty, sema.arena, pt);
2099921194 return Air.internedToRef(result_val.toIntern());
2100021195 },
2100121196 }
......@@ -21007,12 +21202,13 @@ fn zirUnaryMath(
2100721202 block: *Block,
2100821203 inst: Zir.Inst.Index,
2100921204 air_tag: Air.Inst.Tag,
21010 comptime eval: fn (Value, Type, Allocator, *Module) Allocator.Error!Value,
21205 comptime eval: fn (Value, Type, Allocator, Zcu.PerThread) Allocator.Error!Value,
2101121206) CompileError!Air.Inst.Ref {
2101221207 const tracy = trace(@src());
2101321208 defer tracy.end();
2101421209
21015 const mod = sema.mod;
21210 const pt = sema.pt;
21211 const mod = pt.zcu;
2101621212 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2101721213 const operand = try sema.resolveInst(inst_data.operand);
2101821214 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -21025,7 +21221,7 @@ fn zirUnaryMath(
2102521221 block,
2102621222 operand_src,
2102721223 "expected vector of floats or float type, found '{}'",
21028 .{operand_ty.fmt(sema.mod)},
21224 .{operand_ty.fmt(pt)},
2102921225 ),
2103021226 }
2103121227
......@@ -21041,10 +21237,11 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2104121237 const src = block.nodeOffset(inst_data.src_node);
2104221238 const operand = try sema.resolveInst(inst_data.operand);
2104321239 const operand_ty = sema.typeOf(operand);
21044 const mod = sema.mod;
21240 const pt = sema.pt;
21241 const mod = pt.zcu;
2104521242 const ip = &mod.intern_pool;
2104621243
21047 try operand_ty.resolveLayout(mod);
21244 try operand_ty.resolveLayout(pt);
2104821245 const enum_ty = switch (operand_ty.zigTypeTag(mod)) {
2104921246 .EnumLiteral => {
2105021247 const val = try sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, operand, undefined);
......@@ -21053,9 +21250,9 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2105321250 },
2105421251 .Enum => operand_ty,
2105521252 .Union => operand_ty.unionTagType(mod) orelse
21056 return sema.fail(block, src, "union '{}' is untagged", .{operand_ty.fmt(sema.mod)}),
21253 return sema.fail(block, src, "union '{}' is untagged", .{operand_ty.fmt(pt)}),
2105721254 else => return sema.fail(block, operand_src, "expected enum or union; found '{}'", .{
21058 operand_ty.fmt(mod),
21255 operand_ty.fmt(pt),
2105921256 }),
2106021257 };
2106121258 if (enum_ty.enumFieldCount(mod) == 0) {
......@@ -21063,7 +21260,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2106321260 // it prevents a crash.
2106421261 // https://github.com/ziglang/zig/issues/15909
2106521262 return sema.fail(block, operand_src, "cannot get @tagName of empty enum '{}'", .{
21066 enum_ty.fmt(mod),
21263 enum_ty.fmt(pt),
2106721264 });
2106821265 }
2106921266 const enum_decl_index = enum_ty.getOwnerDecl(mod);
......@@ -21072,7 +21269,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2107221269 const field_index = enum_ty.enumTagFieldIndex(val, mod) orelse {
2107321270 const msg = msg: {
2107421271 const msg = try sema.errMsg(src, "no field with value '{}' in enum '{}'", .{
21075 val.fmtValue(sema.mod, sema), mod.declPtr(enum_decl_index).name.fmt(ip),
21272 val.fmtValue(pt, sema), mod.declPtr(enum_decl_index).name.fmt(ip),
2107621273 });
2107721274 errdefer msg.destroy(sema.gpa);
2107821275 try sema.errNote(enum_ty.srcLoc(mod), msg, "declared here", .{});
......@@ -21085,7 +21282,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2108521282 return sema.addNullTerminatedStrLit(field_name);
2108621283 }
2108721284 try sema.requireRuntimeBlock(block, src, operand_src);
21088 if (block.wantSafety() and sema.mod.backendSupportsFeature(.is_named_enum_value)) {
21285 if (block.wantSafety() and mod.backendSupportsFeature(.is_named_enum_value)) {
2108921286 const ok = try block.addUnOp(.is_named_enum_value, casted_operand);
2109021287 try sema.addSafetyCheck(block, src, ok, .invalid_enum_value);
2109121288 }
......@@ -21101,7 +21298,8 @@ fn zirReify(
2110121298 extended: Zir.Inst.Extended.InstData,
2110221299 inst: Zir.Inst.Index,
2110321300) CompileError!Air.Inst.Ref {
21104 const mod = sema.mod;
21301 const pt = sema.pt;
21302 const mod = pt.zcu;
2110521303 const gpa = sema.gpa;
2110621304 const ip = &mod.intern_pool;
2110721305 const name_strategy: Zir.Inst.NameStrategy = @enumFromInt(extended.small);
......@@ -21120,7 +21318,7 @@ fn zirReify(
2112021318 },
2112121319 },
2112221320 };
21123 const type_info_ty = try mod.getBuiltinType("Type");
21321 const type_info_ty = try pt.getBuiltinType("Type");
2112421322 const uncasted_operand = try sema.resolveInst(extra.operand);
2112521323 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
2112621324 const val = try sema.resolveConstDefinedValue(block, operand_src, type_info, .{
......@@ -21145,36 +21343,36 @@ fn zirReify(
2114521343 .Int => {
2114621344 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
2114721345 const signedness_val = try Value.fromInterned(union_val.val).fieldValue(
21148 mod,
21346 pt,
2114921347 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, "signedness", .no_embedded_nulls)).?,
2115021348 );
2115121349 const bits_val = try Value.fromInterned(union_val.val).fieldValue(
21152 mod,
21350 pt,
2115321351 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, "bits", .no_embedded_nulls)).?,
2115421352 );
2115521353
2115621354 const signedness = mod.toEnum(std.builtin.Signedness, signedness_val);
21157 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(mod));
21158 const ty = try mod.intType(signedness, bits);
21355 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(pt));
21356 const ty = try pt.intType(signedness, bits);
2115921357 return Air.internedToRef(ty.toIntern());
2116021358 },
2116121359 .Vector => {
2116221360 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21163 const len_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21361 const len_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2116421362 ip,
2116521363 try ip.getOrPutString(gpa, "len", .no_embedded_nulls),
2116621364 ).?);
21167 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21365 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2116821366 ip,
2116921367 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
2117021368 ).?);
2117121369
21172 const len: u32 = @intCast(try len_val.toUnsignedIntSema(mod));
21370 const len: u32 = @intCast(try len_val.toUnsignedIntSema(pt));
2117321371 const child_ty = child_val.toType();
2117421372
2117521373 try sema.checkVectorElemType(block, src, child_ty);
2117621374
21177 const ty = try mod.vectorType(.{
21375 const ty = try pt.vectorType(.{
2117821376 .len = len,
2117921377 .child = child_ty.toIntern(),
2118021378 });
......@@ -21182,12 +21380,12 @@ fn zirReify(
2118221380 },
2118321381 .Float => {
2118421382 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21185 const bits_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21383 const bits_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2118621384 ip,
2118721385 try ip.getOrPutString(gpa, "bits", .no_embedded_nulls),
2118821386 ).?);
2118921387
21190 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(mod));
21388 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(pt));
2119121389 const ty = switch (bits) {
2119221390 16 => Type.f16,
2119321391 32 => Type.f32,
......@@ -21200,35 +21398,35 @@ fn zirReify(
2120021398 },
2120121399 .Pointer => {
2120221400 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21203 const size_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21401 const size_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2120421402 ip,
2120521403 try ip.getOrPutString(gpa, "size", .no_embedded_nulls),
2120621404 ).?);
21207 const is_const_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21405 const is_const_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2120821406 ip,
2120921407 try ip.getOrPutString(gpa, "is_const", .no_embedded_nulls),
2121021408 ).?);
21211 const is_volatile_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21409 const is_volatile_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2121221410 ip,
2121321411 try ip.getOrPutString(gpa, "is_volatile", .no_embedded_nulls),
2121421412 ).?);
21215 const alignment_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21413 const alignment_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2121621414 ip,
2121721415 try ip.getOrPutString(gpa, "alignment", .no_embedded_nulls),
2121821416 ).?);
21219 const address_space_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21417 const address_space_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122021418 ip,
2122121419 try ip.getOrPutString(gpa, "address_space", .no_embedded_nulls),
2122221420 ).?);
21223 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21421 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122421422 ip,
2122521423 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
2122621424 ).?);
21227 const is_allowzero_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21425 const is_allowzero_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122821426 ip,
2122921427 try ip.getOrPutString(gpa, "is_allowzero", .no_embedded_nulls),
2123021428 ).?);
21231 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21429 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2123221430 ip,
2123321431 try ip.getOrPutString(gpa, "sentinel", .no_embedded_nulls),
2123421432 ).?);
......@@ -21237,7 +21435,7 @@ fn zirReify(
2123721435 return sema.fail(block, src, "alignment must fit in 'u32'", .{});
2123821436 }
2123921437
21240 const alignment_val_int = (try alignment_val.getUnsignedIntAdvanced(mod, .sema)).?;
21438 const alignment_val_int = (try alignment_val.getUnsignedIntAdvanced(pt, .sema)).?;
2124121439 if (alignment_val_int > 0 and !math.isPowerOfTwo(alignment_val_int)) {
2124221440 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{alignment_val_int});
2124321441 }
......@@ -21245,7 +21443,7 @@ fn zirReify(
2124521443
2124621444 const elem_ty = child_val.toType();
2124721445 if (abi_align != .none) {
21248 try elem_ty.resolveLayout(mod);
21446 try elem_ty.resolveLayout(pt);
2124921447 }
2125021448
2125121449 const ptr_size = mod.toEnum(std.builtin.Type.Pointer.Size, size_val);
......@@ -21256,7 +21454,7 @@ fn zirReify(
2125621454 return sema.fail(block, src, "sentinels are only allowed on slices and unknown-length pointers", .{});
2125721455 }
2125821456 const sentinel_ptr_val = sentinel_val.optionalValue(mod).?;
21259 const ptr_ty = try mod.singleMutPtrType(elem_ty);
21457 const ptr_ty = try pt.singleMutPtrType(elem_ty);
2126021458 const sent_val = (try sema.pointerDeref(block, src, sentinel_ptr_val, ptr_ty)).?;
2126121459 break :s sent_val.toIntern();
2126221460 }
......@@ -21274,7 +21472,7 @@ fn zirReify(
2127421472 } else if (ptr_size == .C) {
2127521473 if (!try sema.validateExternType(elem_ty, .other)) {
2127621474 const msg = msg: {
21277 const msg = try sema.errMsg(src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(mod)});
21475 const msg = try sema.errMsg(src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(pt)});
2127821476 errdefer msg.destroy(gpa);
2127921477
2128021478 try sema.explainWhyTypeIsNotExtern(msg, src, elem_ty, .other);
......@@ -21289,7 +21487,7 @@ fn zirReify(
2128921487 }
2129021488 }
2129121489
21292 const ty = try mod.ptrTypeSema(.{
21490 const ty = try pt.ptrTypeSema(.{
2129321491 .child = elem_ty.toIntern(),
2129421492 .sentinel = actual_sentinel,
2129521493 .flags = .{
......@@ -21305,27 +21503,27 @@ fn zirReify(
2130521503 },
2130621504 .Array => {
2130721505 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21308 const len_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21506 const len_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2130921507 ip,
2131021508 try ip.getOrPutString(gpa, "len", .no_embedded_nulls),
2131121509 ).?);
21312 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21510 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2131321511 ip,
2131421512 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
2131521513 ).?);
21316 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21514 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2131721515 ip,
2131821516 try ip.getOrPutString(gpa, "sentinel", .no_embedded_nulls),
2131921517 ).?);
2132021518
21321 const len = try len_val.toUnsignedIntSema(mod);
21519 const len = try len_val.toUnsignedIntSema(pt);
2132221520 const child_ty = child_val.toType();
2132321521 const sentinel = if (sentinel_val.optionalValue(mod)) |p| blk: {
21324 const ptr_ty = try mod.singleMutPtrType(child_ty);
21522 const ptr_ty = try pt.singleMutPtrType(child_ty);
2132521523 break :blk (try sema.pointerDeref(block, src, p, ptr_ty)).?;
2132621524 } else null;
2132721525
21328 const ty = try mod.arrayType(.{
21526 const ty = try pt.arrayType(.{
2132921527 .len = len,
2133021528 .sentinel = if (sentinel) |s| s.toIntern() else .none,
2133121529 .child = child_ty.toIntern(),
......@@ -21334,23 +21532,23 @@ fn zirReify(
2133421532 },
2133521533 .Optional => {
2133621534 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21337 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21535 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2133821536 ip,
2133921537 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
2134021538 ).?);
2134121539
2134221540 const child_ty = child_val.toType();
2134321541
21344 const ty = try mod.optionalType(child_ty.toIntern());
21542 const ty = try pt.optionalType(child_ty.toIntern());
2134521543 return Air.internedToRef(ty.toIntern());
2134621544 },
2134721545 .ErrorUnion => {
2134821546 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21349 const error_set_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21547 const error_set_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2135021548 ip,
2135121549 try ip.getOrPutString(gpa, "error_set", .no_embedded_nulls),
2135221550 ).?);
21353 const payload_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21551 const payload_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2135421552 ip,
2135521553 try ip.getOrPutString(gpa, "payload", .no_embedded_nulls),
2135621554 ).?);
......@@ -21362,7 +21560,7 @@ fn zirReify(
2136221560 return sema.fail(block, src, "Type.ErrorUnion.error_set must be an error set type", .{});
2136321561 }
2136421562
21365 const ty = try mod.errorUnionType(error_set_ty, payload_ty);
21563 const ty = try pt.errorUnionType(error_set_ty, payload_ty);
2136621564 return Air.internedToRef(ty.toIntern());
2136721565 },
2136821566 .ErrorSet => {
......@@ -21377,9 +21575,9 @@ fn zirReify(
2137721575 var names: InferredErrorSet.NameMap = .{};
2137821576 try names.ensureUnusedCapacity(sema.arena, len);
2137921577 for (0..len) |i| {
21380 const elem_val = try names_val.elemValue(mod, i);
21578 const elem_val = try names_val.elemValue(pt, i);
2138121579 const elem_struct_type = ip.loadStructType(ip.typeOf(elem_val.toIntern()));
21382 const name_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21580 const name_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2138321581 ip,
2138421582 try ip.getOrPutString(gpa, "name", .no_embedded_nulls),
2138521583 ).?);
......@@ -21396,28 +21594,28 @@ fn zirReify(
2139621594 }
2139721595 }
2139821596
21399 const ty = try mod.errorSetFromUnsortedNames(names.keys());
21597 const ty = try pt.errorSetFromUnsortedNames(names.keys());
2140021598 return Air.internedToRef(ty.toIntern());
2140121599 },
2140221600 .Struct => {
2140321601 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21404 const layout_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21602 const layout_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2140521603 ip,
2140621604 try ip.getOrPutString(gpa, "layout", .no_embedded_nulls),
2140721605 ).?);
21408 const backing_integer_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21606 const backing_integer_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2140921607 ip,
2141021608 try ip.getOrPutString(gpa, "backing_integer", .no_embedded_nulls),
2141121609 ).?);
21412 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21610 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2141321611 ip,
2141421612 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
2141521613 ).?);
21416 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21614 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2141721615 ip,
2141821616 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
2141921617 ).?);
21420 const is_tuple_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21618 const is_tuple_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2142121619 ip,
2142221620 try ip.getOrPutString(gpa, "is_tuple", .no_embedded_nulls),
2142321621 ).?);
......@@ -21425,7 +21623,7 @@ fn zirReify(
2142521623 const layout = mod.toEnum(std.builtin.Type.ContainerLayout, layout_val);
2142621624
2142721625 // Decls
21428 if (try decls_val.sliceLen(mod) > 0) {
21626 if (try decls_val.sliceLen(pt) > 0) {
2142921627 return sema.fail(block, src, "reified structs must have no decls", .{});
2143021628 }
2143121629
......@@ -21441,24 +21639,24 @@ fn zirReify(
2144121639 },
2144221640 .Enum => {
2144321641 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21444 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21642 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2144521643 ip,
2144621644 try ip.getOrPutString(gpa, "tag_type", .no_embedded_nulls),
2144721645 ).?);
21448 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21646 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2144921647 ip,
2145021648 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
2145121649 ).?);
21452 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21650 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2145321651 ip,
2145421652 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
2145521653 ).?);
21456 const is_exhaustive_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21654 const is_exhaustive_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2145721655 ip,
2145821656 try ip.getOrPutString(gpa, "is_exhaustive", .no_embedded_nulls),
2145921657 ).?);
2146021658
21461 if (try decls_val.sliceLen(mod) > 0) {
21659 if (try decls_val.sliceLen(pt) > 0) {
2146221660 return sema.fail(block, src, "reified enums must have no decls", .{});
2146321661 }
2146421662
......@@ -21470,17 +21668,17 @@ fn zirReify(
2147021668 },
2147121669 .Opaque => {
2147221670 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21473 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21671 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2147421672 ip,
2147521673 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
2147621674 ).?);
2147721675
2147821676 // Decls
21479 if (try decls_val.sliceLen(mod) > 0) {
21677 if (try decls_val.sliceLen(pt) > 0) {
2148021678 return sema.fail(block, src, "reified opaque must have no decls", .{});
2148121679 }
2148221680
21483 const wip_ty = switch (try ip.getOpaqueType(gpa, .{
21681 const wip_ty = switch (try ip.getOpaqueType(gpa, pt.tid, .{
2148421682 .has_namespace = false,
2148521683 .key = .{ .reified = .{
2148621684 .zir_index = try block.trackZir(inst),
......@@ -21501,30 +21699,30 @@ fn zirReify(
2150121699 mod.declPtr(new_decl_index).owns_tv = true;
2150221700 errdefer mod.abortAnonDecl(new_decl_index);
2150321701
21504 try mod.finalizeAnonDecl(new_decl_index);
21702 try pt.finalizeAnonDecl(new_decl_index);
2150521703
2150621704 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
2150721705 },
2150821706 .Union => {
2150921707 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21510 const layout_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21708 const layout_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151121709 ip,
2151221710 try ip.getOrPutString(gpa, "layout", .no_embedded_nulls),
2151321711 ).?);
21514 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21712 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151521713 ip,
2151621714 try ip.getOrPutString(gpa, "tag_type", .no_embedded_nulls),
2151721715 ).?);
21518 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21716 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151921717 ip,
2152021718 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
2152121719 ).?);
21522 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21720 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2152321721 ip,
2152421722 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
2152521723 ).?);
2152621724
21527 if (try decls_val.sliceLen(mod) > 0) {
21725 if (try decls_val.sliceLen(pt) > 0) {
2152821726 return sema.fail(block, src, "reified unions must have no decls", .{});
2152921727 }
2153021728 const layout = mod.toEnum(std.builtin.Type.ContainerLayout, layout_val);
......@@ -21537,23 +21735,23 @@ fn zirReify(
2153721735 },
2153821736 .Fn => {
2153921737 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21540 const calling_convention_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21738 const calling_convention_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154121739 ip,
2154221740 try ip.getOrPutString(gpa, "calling_convention", .no_embedded_nulls),
2154321741 ).?);
21544 const is_generic_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21742 const is_generic_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154521743 ip,
2154621744 try ip.getOrPutString(gpa, "is_generic", .no_embedded_nulls),
2154721745 ).?);
21548 const is_var_args_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21746 const is_var_args_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154921747 ip,
2155021748 try ip.getOrPutString(gpa, "is_var_args", .no_embedded_nulls),
2155121749 ).?);
21552 const return_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21750 const return_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2155321751 ip,
2155421752 try ip.getOrPutString(gpa, "return_type", .no_embedded_nulls),
2155521753 ).?);
21556 const params_slice_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21754 const params_slice_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2155721755 ip,
2155821756 try ip.getOrPutString(gpa, "params", .no_embedded_nulls),
2155921757 ).?);
......@@ -21581,17 +21779,17 @@ fn zirReify(
2158121779
2158221780 var noalias_bits: u32 = 0;
2158321781 for (param_types, 0..) |*param_type, i| {
21584 const elem_val = try params_val.elemValue(mod, i);
21782 const elem_val = try params_val.elemValue(pt, i);
2158521783 const elem_struct_type = ip.loadStructType(ip.typeOf(elem_val.toIntern()));
21586 const param_is_generic_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21784 const param_is_generic_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2158721785 ip,
2158821786 try ip.getOrPutString(gpa, "is_generic", .no_embedded_nulls),
2158921787 ).?);
21590 const param_is_noalias_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21788 const param_is_noalias_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2159121789 ip,
2159221790 try ip.getOrPutString(gpa, "is_noalias", .no_embedded_nulls),
2159321791 ).?);
21594 const opt_param_type_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21792 const opt_param_type_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2159521793 ip,
2159621794 try ip.getOrPutString(gpa, "type", .no_embedded_nulls),
2159721795 ).?);
......@@ -21613,7 +21811,7 @@ fn zirReify(
2161321811 }
2161421812 }
2161521813
21616 const ty = try mod.funcType(.{
21814 const ty = try pt.funcType(.{
2161721815 .param_types = param_types,
2161821816 .noalias_bits = noalias_bits,
2161921817 .return_type = return_type.toIntern(),
......@@ -21636,7 +21834,8 @@ fn reifyEnum(
2163621834 fields_val: Value,
2163721835 name_strategy: Zir.Inst.NameStrategy,
2163821836) CompileError!Air.Inst.Ref {
21639 const mod = sema.mod;
21837 const pt = sema.pt;
21838 const mod = pt.zcu;
2164021839 const gpa = sema.gpa;
2164121840 const ip = &mod.intern_pool;
2164221841
......@@ -21656,10 +21855,10 @@ fn reifyEnum(
2165621855 std.hash.autoHash(&hasher, fields_len);
2165721856
2165821857 for (0..fields_len) |field_idx| {
21659 const field_info = try fields_val.elemValue(mod, field_idx);
21858 const field_info = try fields_val.elemValue(pt, field_idx);
2166021859
21661 const field_name_val = try field_info.fieldValue(mod, 0);
21662 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 1));
21860 const field_name_val = try field_info.fieldValue(pt, 0);
21861 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));
2166321862
2166421863 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2166521864 .needed_comptime_reason = "enum field name must be comptime-known",
......@@ -21671,7 +21870,7 @@ fn reifyEnum(
2167121870 });
2167221871 }
2167321872
21674 const wip_ty = switch (try ip.getEnumType(gpa, .{
21873 const wip_ty = switch (try ip.getEnumType(gpa, pt.tid, .{
2167521874 .has_namespace = false,
2167621875 .has_values = true,
2167721876 .tag_mode = if (is_exhaustive) .explicit else .nonexhaustive,
......@@ -21704,10 +21903,10 @@ fn reifyEnum(
2170421903 wip_ty.setTagTy(ip, tag_ty.toIntern());
2170521904
2170621905 for (0..fields_len) |field_idx| {
21707 const field_info = try fields_val.elemValue(mod, field_idx);
21906 const field_info = try fields_val.elemValue(pt, field_idx);
2170821907
21709 const field_name_val = try field_info.fieldValue(mod, 0);
21710 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 1));
21908 const field_name_val = try field_info.fieldValue(pt, 0);
21909 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));
2171121910
2171221911 // Don't pass a reason; first loop acts as an assertion that this is valid.
2171321912 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21716,12 +21915,12 @@ fn reifyEnum(
2171621915 // TODO: better source location
2171721916 return sema.fail(block, src, "field '{}' with enumeration value '{}' is too large for backing int type '{}'", .{
2171821917 field_name.fmt(ip),
21719 field_value_val.fmtValue(mod, sema),
21720 tag_ty.fmt(mod),
21918 field_value_val.fmtValue(pt, sema),
21919 tag_ty.fmt(pt),
2172121920 });
2172221921 }
2172321922
21724 const coerced_field_val = try mod.getCoerced(field_value_val, tag_ty);
21923 const coerced_field_val = try pt.getCoerced(field_value_val, tag_ty);
2172521924 if (wip_ty.nextField(ip, field_name, coerced_field_val.toIntern())) |conflict| {
2172621925 return sema.failWithOwnedErrorMsg(block, switch (conflict.kind) {
2172721926 .name => msg: {
......@@ -21732,7 +21931,7 @@ fn reifyEnum(
2173221931 break :msg msg;
2173321932 },
2173421933 .value => msg: {
21735 const msg = try sema.errMsg(src, "enum tag value {} already taken", .{field_value_val.fmtValue(mod, sema)});
21934 const msg = try sema.errMsg(src, "enum tag value {} already taken", .{field_value_val.fmtValue(pt, sema)});
2173621935 errdefer msg.destroy(gpa);
2173721936 _ = conflict.prev_field_idx; // TODO: this note is incorrect
2173821937 try sema.errNote(src, msg, "other enum tag value here", .{});
......@@ -21742,11 +21941,11 @@ fn reifyEnum(
2174221941 }
2174321942 }
2174421943
21745 if (!is_exhaustive and fields_len > 1 and std.math.log2_int(u64, fields_len) == tag_ty.bitSize(mod)) {
21944 if (!is_exhaustive and fields_len > 1 and std.math.log2_int(u64, fields_len) == tag_ty.bitSize(pt)) {
2174621945 return sema.fail(block, src, "non-exhaustive enum specified every value", .{});
2174721946 }
2174821947
21749 try mod.finalizeAnonDecl(new_decl_index);
21948 try pt.finalizeAnonDecl(new_decl_index);
2175021949 return Air.internedToRef(wip_ty.index);
2175121950}
2175221951
......@@ -21760,7 +21959,8 @@ fn reifyUnion(
2176021959 fields_val: Value,
2176121960 name_strategy: Zir.Inst.NameStrategy,
2176221961) CompileError!Air.Inst.Ref {
21763 const mod = sema.mod;
21962 const pt = sema.pt;
21963 const mod = pt.zcu;
2176421964 const gpa = sema.gpa;
2176521965 const ip = &mod.intern_pool;
2176621966
......@@ -21782,11 +21982,11 @@ fn reifyUnion(
2178221982 var any_aligns = false;
2178321983
2178421984 for (0..fields_len) |field_idx| {
21785 const field_info = try fields_val.elemValue(mod, field_idx);
21985 const field_info = try fields_val.elemValue(pt, field_idx);
2178621986
21787 const field_name_val = try field_info.fieldValue(mod, 0);
21788 const field_type_val = try field_info.fieldValue(mod, 1);
21789 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 2));
21987 const field_name_val = try field_info.fieldValue(pt, 0);
21988 const field_type_val = try field_info.fieldValue(pt, 1);
21989 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 2));
2179021990
2179121991 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2179221992 .needed_comptime_reason = "union field name must be comptime-known",
......@@ -21798,12 +21998,12 @@ fn reifyUnion(
2179821998 field_align_val.toIntern(),
2179921999 });
2180022000
21801 if (field_align_val.toUnsignedInt(mod) != 0) {
22001 if (field_align_val.toUnsignedInt(pt) != 0) {
2180222002 any_aligns = true;
2180322003 }
2180422004 }
2180522005
21806 const wip_ty = switch (try ip.getUnionType(gpa, .{
22006 const wip_ty = switch (try ip.getUnionType(gpa, pt.tid, .{
2180722007 .flags = .{
2180822008 .layout = layout,
2180922009 .status = .none,
......@@ -21861,10 +22061,10 @@ fn reifyUnion(
2186122061 var seen_tags = try std.DynamicBitSetUnmanaged.initEmpty(sema.arena, tag_ty_fields_len);
2186222062
2186322063 for (field_types, 0..) |*field_ty, field_idx| {
21864 const field_info = try fields_val.elemValue(mod, field_idx);
22064 const field_info = try fields_val.elemValue(pt, field_idx);
2186522065
21866 const field_name_val = try field_info.fieldValue(mod, 0);
21867 const field_type_val = try field_info.fieldValue(mod, 1);
22066 const field_name_val = try field_info.fieldValue(pt, 0);
22067 const field_type_val = try field_info.fieldValue(pt, 1);
2186822068
2186922069 // Don't pass a reason; first loop acts as an assertion that this is valid.
2187022070 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21872,7 +22072,7 @@ fn reifyUnion(
2187222072 const enum_index = enum_tag_ty.enumFieldIndex(field_name, mod) orelse {
2187322073 // TODO: better source location
2187422074 return sema.fail(block, src, "no field named '{}' in enum '{}'", .{
21875 field_name.fmt(ip), enum_tag_ty.fmt(mod),
22075 field_name.fmt(ip), enum_tag_ty.fmt(pt),
2187622076 });
2187722077 };
2187822078 if (seen_tags.isSet(enum_index)) {
......@@ -21883,7 +22083,7 @@ fn reifyUnion(
2188322083
2188422084 field_ty.* = field_type_val.toIntern();
2188522085 if (any_aligns) {
21886 const byte_align = try (try field_info.fieldValue(mod, 2)).toUnsignedIntSema(mod);
22086 const byte_align = try (try field_info.fieldValue(pt, 2)).toUnsignedIntSema(pt);
2188722087 if (byte_align > 0 and !math.isPowerOfTwo(byte_align)) {
2188822088 // TODO: better source location
2188922089 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{byte_align});
......@@ -21913,10 +22113,10 @@ fn reifyUnion(
2191322113 try field_names.ensureTotalCapacity(sema.arena, fields_len);
2191422114
2191522115 for (field_types, 0..) |*field_ty, field_idx| {
21916 const field_info = try fields_val.elemValue(mod, field_idx);
22116 const field_info = try fields_val.elemValue(pt, field_idx);
2191722117
21918 const field_name_val = try field_info.fieldValue(mod, 0);
21919 const field_type_val = try field_info.fieldValue(mod, 1);
22118 const field_name_val = try field_info.fieldValue(pt, 0);
22119 const field_type_val = try field_info.fieldValue(pt, 1);
2192022120
2192122121 // Don't pass a reason; first loop acts as an assertion that this is valid.
2192222122 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21928,7 +22128,7 @@ fn reifyUnion(
2192822128
2192922129 field_ty.* = field_type_val.toIntern();
2193022130 if (any_aligns) {
21931 const byte_align = try (try field_info.fieldValue(mod, 2)).toUnsignedIntSema(mod);
22131 const byte_align = try (try field_info.fieldValue(pt, 2)).toUnsignedIntSema(pt);
2193222132 if (byte_align > 0 and !math.isPowerOfTwo(byte_align)) {
2193322133 // TODO: better source location
2193422134 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{byte_align});
......@@ -21955,7 +22155,7 @@ fn reifyUnion(
2195522155 }
2195622156 if (layout == .@"extern" and !try sema.validateExternType(field_ty, .union_field)) {
2195722157 return sema.failWithOwnedErrorMsg(block, msg: {
21958 const msg = try sema.errMsg(src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
22158 const msg = try sema.errMsg(src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2195922159 errdefer msg.destroy(gpa);
2196022160
2196122161 try sema.explainWhyTypeIsNotExtern(msg, src, field_ty, .union_field);
......@@ -21965,7 +22165,7 @@ fn reifyUnion(
2196522165 });
2196622166 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
2196722167 return sema.failWithOwnedErrorMsg(block, msg: {
21968 const msg = try sema.errMsg(src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
22168 const msg = try sema.errMsg(src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2196922169 errdefer msg.destroy(gpa);
2197022170
2197122171 try sema.explainWhyTypeIsNotPacked(msg, src, field_ty);
......@@ -21984,7 +22184,7 @@ fn reifyUnion(
2198422184 loaded_union.tagTypePtr(ip).* = enum_tag_ty;
2198522185 loaded_union.flagsPtr(ip).status = .have_field_types;
2198622186
21987 try mod.finalizeAnonDecl(new_decl_index);
22187 try pt.finalizeAnonDecl(new_decl_index);
2198822188 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
2198922189 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
2199022190 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
......@@ -22001,7 +22201,8 @@ fn reifyStruct(
2200122201 name_strategy: Zir.Inst.NameStrategy,
2200222202 is_tuple: bool,
2200322203) CompileError!Air.Inst.Ref {
22004 const mod = sema.mod;
22204 const pt = sema.pt;
22205 const mod = pt.zcu;
2200522206 const gpa = sema.gpa;
2200622207 const ip = &mod.intern_pool;
2200722208
......@@ -22026,20 +22227,20 @@ fn reifyStruct(
2202622227 var any_aligned_fields = false;
2202722228
2202822229 for (0..fields_len) |field_idx| {
22029 const field_info = try fields_val.elemValue(mod, field_idx);
22230 const field_info = try fields_val.elemValue(pt, field_idx);
2203022231
22031 const field_name_val = try field_info.fieldValue(mod, 0);
22032 const field_type_val = try field_info.fieldValue(mod, 1);
22033 const field_default_value_val = try field_info.fieldValue(mod, 2);
22034 const field_is_comptime_val = try field_info.fieldValue(mod, 3);
22035 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 4));
22232 const field_name_val = try field_info.fieldValue(pt, 0);
22233 const field_type_val = try field_info.fieldValue(pt, 1);
22234 const field_default_value_val = try field_info.fieldValue(pt, 2);
22235 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22236 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));
2203622237
2203722238 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2203822239 .needed_comptime_reason = "struct field name must be comptime-known",
2203922240 });
2204022241 const field_is_comptime = field_is_comptime_val.toBool();
2204122242 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(mod)) |ptr_val| d: {
22042 const ptr_ty = try mod.singleConstPtrType(field_type_val.toType());
22243 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());
2204322244 // We need to do this deref here, so we won't check for this error case later on.
2204422245 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(
2204522246 block,
......@@ -22060,14 +22261,14 @@ fn reifyStruct(
2206022261
2206122262 if (field_is_comptime) any_comptime_fields = true;
2206222263 if (field_default_value != .none) any_default_inits = true;
22063 switch (try field_alignment_val.orderAgainstZeroAdvanced(mod, .sema)) {
22264 switch (try field_alignment_val.orderAgainstZeroAdvanced(pt, .sema)) {
2206422265 .eq => {},
2206522266 .gt => any_aligned_fields = true,
2206622267 .lt => unreachable,
2206722268 }
2206822269 }
2206922270
22070 const wip_ty = switch (try ip.getStructType(gpa, .{
22271 const wip_ty = switch (try ip.getStructType(gpa, pt.tid, .{
2207122272 .layout = layout,
2207222273 .fields_len = fields_len,
2207322274 .known_non_opv = false,
......@@ -22107,13 +22308,13 @@ fn reifyStruct(
2210722308 const struct_type = ip.loadStructType(wip_ty.index);
2210822309
2210922310 for (0..fields_len) |field_idx| {
22110 const field_info = try fields_val.elemValue(mod, field_idx);
22311 const field_info = try fields_val.elemValue(pt, field_idx);
2211122312
22112 const field_name_val = try field_info.fieldValue(mod, 0);
22113 const field_type_val = try field_info.fieldValue(mod, 1);
22114 const field_default_value_val = try field_info.fieldValue(mod, 2);
22115 const field_is_comptime_val = try field_info.fieldValue(mod, 3);
22116 const field_alignment_val = try field_info.fieldValue(mod, 4);
22313 const field_name_val = try field_info.fieldValue(pt, 0);
22314 const field_type_val = try field_info.fieldValue(pt, 1);
22315 const field_default_value_val = try field_info.fieldValue(pt, 2);
22316 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22317 const field_alignment_val = try field_info.fieldValue(pt, 4);
2211722318
2211822319 const field_ty = field_type_val.toType();
2211922320 // Don't pass a reason; first loop acts as an assertion that this is valid.
......@@ -22143,7 +22344,7 @@ fn reifyStruct(
2214322344 return sema.fail(block, src, "alignment must fit in 'u32'", .{});
2214422345 }
2214522346
22146 const byte_align = try field_alignment_val.toUnsignedIntSema(mod);
22347 const byte_align = try field_alignment_val.toUnsignedIntSema(pt);
2214722348 if (byte_align == 0) {
2214822349 if (layout != .@"packed") {
2214922350 struct_type.field_aligns.get(ip)[field_idx] = .none;
......@@ -22168,7 +22369,7 @@ fn reifyStruct(
2216822369 const field_default: InternPool.Index = d: {
2216922370 if (!any_default_inits) break :d .none;
2217022371 const ptr_val = field_default_value_val.optionalValue(mod) orelse break :d .none;
22171 const ptr_ty = try mod.singleConstPtrType(field_ty);
22372 const ptr_ty = try pt.singleConstPtrType(field_ty);
2217222373 // Asserted comptime-dereferencable above.
2217322374 const val = (try sema.pointerDeref(block, src, ptr_val, ptr_ty)).?;
2217422375 // We already resolved this for deduplication, so we may as well do it now.
......@@ -22204,7 +22405,7 @@ fn reifyStruct(
2220422405 }
2220522406 if (layout == .@"extern" and !try sema.validateExternType(field_ty, .struct_field)) {
2220622407 return sema.failWithOwnedErrorMsg(block, msg: {
22207 const msg = try sema.errMsg(src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
22408 const msg = try sema.errMsg(src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2220822409 errdefer msg.destroy(gpa);
2220922410
2221022411 try sema.explainWhyTypeIsNotExtern(msg, src, field_ty, .struct_field);
......@@ -22214,7 +22415,7 @@ fn reifyStruct(
2221422415 });
2221522416 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
2221622417 return sema.failWithOwnedErrorMsg(block, msg: {
22217 const msg = try sema.errMsg(src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
22418 const msg = try sema.errMsg(src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2221822419 errdefer msg.destroy(gpa);
2221922420
2222022421 try sema.explainWhyTypeIsNotPacked(msg, src, field_ty);
......@@ -22229,7 +22430,7 @@ fn reifyStruct(
2222922430 var fields_bit_sum: u64 = 0;
2223022431 for (0..struct_type.field_types.len) |field_idx| {
2223122432 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_idx]);
22232 field_ty.resolveLayout(mod) catch |err| switch (err) {
22433 field_ty.resolveLayout(pt) catch |err| switch (err) {
2223322434 error.AnalysisFail => {
2223422435 const msg = sema.err orelse return err;
2223522436 try sema.errNote(src, msg, "while checking a field of this struct", .{});
......@@ -22237,7 +22438,7 @@ fn reifyStruct(
2223722438 },
2223822439 else => return err,
2223922440 };
22240 fields_bit_sum += field_ty.bitSize(mod);
22441 fields_bit_sum += field_ty.bitSize(pt);
2224122442 }
2224222443
2224322444 if (opt_backing_int_val.optionalValue(mod)) |backing_int_val| {
......@@ -22245,20 +22446,21 @@ fn reifyStruct(
2224522446 try sema.checkBackingIntType(block, src, backing_int_ty, fields_bit_sum);
2224622447 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
2224722448 } else {
22248 const backing_int_ty = try mod.intType(.unsigned, @intCast(fields_bit_sum));
22449 const backing_int_ty = try pt.intType(.unsigned, @intCast(fields_bit_sum));
2224922450 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
2225022451 }
2225122452 }
2225222453
22253 try mod.finalizeAnonDecl(new_decl_index);
22454 try pt.finalizeAnonDecl(new_decl_index);
2225422455 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
2225522456 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
2225622457 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
2225722458}
2225822459
2225922460fn resolveVaListRef(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) CompileError!Air.Inst.Ref {
22260 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22261 const va_list_ptr = try sema.mod.singleMutPtrType(va_list_ty);
22461 const pt = sema.pt;
22462 const va_list_ty = try pt.getBuiltinType("VaList");
22463 const va_list_ptr = try pt.singleMutPtrType(va_list_ty);
2226222464
2226322465 const inst = try sema.resolveInst(zir_ref);
2226422466 return sema.coerce(block, va_list_ptr, inst, src);
......@@ -22275,7 +22477,7 @@ fn zirCVaArg(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2227522477
2227622478 if (!try sema.validateExternType(arg_ty, .param_ty)) {
2227722479 const msg = msg: {
22278 const msg = try sema.errMsg(ty_src, "cannot get '{}' from variadic argument", .{arg_ty.fmt(sema.mod)});
22480 const msg = try sema.errMsg(ty_src, "cannot get '{}' from variadic argument", .{arg_ty.fmt(sema.pt)});
2227922481 errdefer msg.destroy(sema.gpa);
2228022482
2228122483 try sema.explainWhyTypeIsNotExtern(msg, ty_src, arg_ty, .param_ty);
......@@ -22296,7 +22498,7 @@ fn zirCVaCopy(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData)
2229622498 const va_list_src = block.builtinCallArgSrc(extra.node, 0);
2229722499
2229822500 const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.operand);
22299 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22501 const va_list_ty = try sema.pt.getBuiltinType("VaList");
2230022502
2230122503 try sema.requireRuntimeBlock(block, src, null);
2230222504 return block.addTyOp(.c_va_copy, va_list_ty, va_list_ref);
......@@ -22316,7 +22518,7 @@ fn zirCVaEnd(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2231622518fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
2231722519 const src = block.nodeOffset(@bitCast(extended.operand));
2231822520
22319 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22521 const va_list_ty = try sema.pt.getBuiltinType("VaList");
2232022522 try sema.requireRuntimeBlock(block, src, null);
2232122523 return block.addInst(.{
2232222524 .tag = .c_va_start,
......@@ -22325,14 +22527,15 @@ fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData)
2232522527}
2232622528
2232722529fn zirTypeName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22328 const mod = sema.mod;
22530 const pt = sema.pt;
22531 const mod = pt.zcu;
2232922532 const ip = &mod.intern_pool;
2233022533
2233122534 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2233222535 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2233322536 const ty = try sema.resolveType(block, ty_src, inst_data.operand);
2233422537
22335 const type_name = try ip.getOrPutStringFmt(sema.gpa, "{}", .{ty.fmt(mod)}, .no_embedded_nulls);
22538 const type_name = try ip.getOrPutStringFmt(sema.gpa, "{}", .{ty.fmt(pt)}, .no_embedded_nulls);
2233622539 return sema.addNullTerminatedStrLit(type_name);
2233722540}
2233822541
......@@ -22349,7 +22552,8 @@ fn zirFrameSize(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2234922552}
2235022553
2235122554fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22352 const mod = sema.mod;
22555 const pt = sema.pt;
22556 const mod = pt.zcu;
2235322557 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2235422558 const src = block.nodeOffset(inst_data.src_node);
2235522559 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -22380,23 +22584,23 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2238022584 if (dest_scalar_ty.intInfo(mod).bits == 0) {
2238122585 if (!is_vector) {
2238222586 if (block.wantSafety()) {
22383 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, operand, Air.internedToRef((try mod.floatValue(operand_ty, 0.0)).toIntern()));
22587 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, operand, Air.internedToRef((try pt.floatValue(operand_ty, 0.0)).toIntern()));
2238422588 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2238522589 }
22386 return Air.internedToRef((try mod.intValue(dest_ty, 0)).toIntern());
22590 return Air.internedToRef((try pt.intValue(dest_ty, 0)).toIntern());
2238722591 }
2238822592 if (block.wantSafety()) {
2238922593 const len = dest_ty.vectorLen(mod);
2239022594 for (0..len) |i| {
22391 const idx_ref = try mod.intRef(Type.usize, i);
22595 const idx_ref = try pt.intRef(Type.usize, i);
2239222596 const elem_ref = try block.addBinOp(.array_elem_val, operand, idx_ref);
22393 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, elem_ref, Air.internedToRef((try mod.floatValue(operand_scalar_ty, 0.0)).toIntern()));
22597 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, elem_ref, Air.internedToRef((try pt.floatValue(operand_scalar_ty, 0.0)).toIntern()));
2239422598 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2239522599 }
2239622600 }
22397 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
22601 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2239822602 .ty = dest_ty.toIntern(),
22399 .storage = .{ .repeated_elem = (try mod.intValue(dest_scalar_ty, 0)).toIntern() },
22603 .storage = .{ .repeated_elem = (try pt.intValue(dest_scalar_ty, 0)).toIntern() },
2240022604 } }));
2240122605 }
2240222606 if (!is_vector) {
......@@ -22404,8 +22608,8 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2240422608 if (block.wantSafety()) {
2240522609 const back = try block.addTyOp(.float_from_int, operand_ty, result);
2240622610 const diff = try block.addBinOp(.sub, operand, back);
22407 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try mod.floatValue(operand_ty, 1.0)).toIntern()));
22408 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try mod.floatValue(operand_ty, -1.0)).toIntern()));
22611 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try pt.floatValue(operand_ty, 1.0)).toIntern()));
22612 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try pt.floatValue(operand_ty, -1.0)).toIntern()));
2240922613 const ok = try block.addBinOp(.bool_and, ok_pos, ok_neg);
2241022614 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2241122615 }
......@@ -22414,14 +22618,14 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2241422618 const len = dest_ty.vectorLen(mod);
2241522619 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2241622620 for (new_elems, 0..) |*new_elem, i| {
22417 const idx_ref = try mod.intRef(Type.usize, i);
22621 const idx_ref = try pt.intRef(Type.usize, i);
2241822622 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2241922623 const result = try block.addTyOp(if (block.float_mode == .optimized) .int_from_float_optimized else .int_from_float, dest_scalar_ty, old_elem);
2242022624 if (block.wantSafety()) {
2242122625 const back = try block.addTyOp(.float_from_int, operand_scalar_ty, result);
2242222626 const diff = try block.addBinOp(.sub, old_elem, back);
22423 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try mod.floatValue(operand_scalar_ty, 1.0)).toIntern()));
22424 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try mod.floatValue(operand_scalar_ty, -1.0)).toIntern()));
22627 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try pt.floatValue(operand_scalar_ty, 1.0)).toIntern()));
22628 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try pt.floatValue(operand_scalar_ty, -1.0)).toIntern()));
2242522629 const ok = try block.addBinOp(.bool_and, ok_pos, ok_neg);
2242622630 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2242722631 }
......@@ -22431,7 +22635,8 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2243122635}
2243222636
2243322637fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22434 const mod = sema.mod;
22638 const pt = sema.pt;
22639 const mod = pt.zcu;
2243522640 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2243622641 const src = block.nodeOffset(inst_data.src_node);
2243722642 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -22450,7 +22655,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2245022655 _ = try sema.checkIntType(block, operand_src, operand_scalar_ty);
2245122656
2245222657 if (try sema.resolveValue(operand)) |operand_val| {
22453 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, mod, .sema);
22658 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, pt, .sema);
2245422659 return Air.internedToRef(result_val.toIntern());
2245522660 } else if (dest_scalar_ty.zigTypeTag(mod) == .ComptimeFloat) {
2245622661 return sema.failWithNeededComptime(block, operand_src, .{
......@@ -22465,7 +22670,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2246522670 const len = operand_ty.vectorLen(mod);
2246622671 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2246722672 for (new_elems, 0..) |*new_elem, i| {
22468 const idx_ref = try mod.intRef(Type.usize, i);
22673 const idx_ref = try pt.intRef(Type.usize, i);
2246922674 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2247022675 new_elem.* = try block.addTyOp(.float_from_int, dest_scalar_ty, old_elem);
2247122676 }
......@@ -22473,7 +22678,8 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2247322678}
2247422679
2247522680fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22476 const mod = sema.mod;
22681 const pt = sema.pt;
22682 const mod = pt.zcu;
2247722683 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2247822684 const src = block.nodeOffset(inst_data.src_node);
2247922685
......@@ -22489,7 +22695,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2248922695 const is_vector = dest_ty.zigTypeTag(mod) == .Vector;
2249022696 const operand_ty = if (is_vector) operand_ty: {
2249122697 const len = dest_ty.vectorLen(mod);
22492 break :operand_ty try mod.vectorType(.{ .child = .usize_type, .len = len });
22698 break :operand_ty try pt.vectorType(.{ .child = .usize_type, .len = len });
2249322699 } else Type.usize;
2249422700
2249522701 const operand_coerced = try sema.coerce(block, operand_ty, operand_res, operand_src);
......@@ -22498,11 +22704,11 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2249822704 try sema.checkPtrType(block, src, ptr_ty, true);
2249922705
2250022706 const elem_ty = ptr_ty.elemType2(mod);
22501 const ptr_align = try ptr_ty.ptrAlignmentAdvanced(mod, .sema);
22707 const ptr_align = try ptr_ty.ptrAlignmentAdvanced(pt, .sema);
2250222708
2250322709 if (ptr_ty.isSlice(mod)) {
2250422710 const msg = msg: {
22505 const msg = try sema.errMsg(src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(sema.mod)});
22711 const msg = try sema.errMsg(src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(pt)});
2250622712 errdefer msg.destroy(sema.gpa);
2250722713 try sema.errNote(src, msg, "slice length cannot be inferred from address", .{});
2250822714 break :msg msg;
......@@ -22518,18 +22724,18 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2251822724 const len = dest_ty.vectorLen(mod);
2251922725 const new_elems = try sema.arena.alloc(InternPool.Index, len);
2252022726 for (new_elems, 0..) |*new_elem, i| {
22521 const elem = try val.elemValue(mod, i);
22727 const elem = try val.elemValue(pt, i);
2252222728 const ptr_val = try sema.ptrFromIntVal(block, operand_src, elem, ptr_ty, ptr_align);
2252322729 new_elem.* = ptr_val.toIntern();
2252422730 }
22525 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
22731 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2252622732 .ty = dest_ty.toIntern(),
2252722733 .storage = .{ .elems = new_elems },
2252822734 } }));
2252922735 }
2253022736 if (try sema.typeRequiresComptime(ptr_ty)) {
2253122737 return sema.failWithOwnedErrorMsg(block, msg: {
22532 const msg = try sema.errMsg(src, "pointer to comptime-only type '{}' must be comptime-known, but operand is runtime-known", .{ptr_ty.fmt(mod)});
22738 const msg = try sema.errMsg(src, "pointer to comptime-only type '{}' must be comptime-known, but operand is runtime-known", .{ptr_ty.fmt(pt)});
2253322739 errdefer msg.destroy(sema.gpa);
2253422740
2253522741 try sema.explainWhyTypeIsComptime(msg, src, ptr_ty);
......@@ -22545,7 +22751,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2254522751 }
2254622752 if (ptr_align.compare(.gt, .@"1")) {
2254722753 const align_bytes_minus_1 = ptr_align.toByteUnits().? - 1;
22548 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
22754 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2254922755 const remainder = try block.addBinOp(.bit_and, operand_coerced, align_minus_1);
2255022756 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
2255122757 try sema.addSafetyCheck(block, src, is_aligned, .incorrect_alignment);
......@@ -22557,7 +22763,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2255722763 const len = dest_ty.vectorLen(mod);
2255822764 if (block.wantSafety() and (try sema.typeHasRuntimeBits(elem_ty) or elem_ty.zigTypeTag(mod) == .Fn)) {
2255922765 for (0..len) |i| {
22560 const idx_ref = try mod.intRef(Type.usize, i);
22766 const idx_ref = try pt.intRef(Type.usize, i);
2256122767 const elem_coerced = try block.addBinOp(.array_elem_val, operand_coerced, idx_ref);
2256222768 if (!ptr_ty.isAllowzeroPtr(mod)) {
2256322769 const is_non_zero = try block.addBinOp(.cmp_neq, elem_coerced, .zero_usize);
......@@ -22565,7 +22771,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2256522771 }
2256622772 if (ptr_align.compare(.gt, .@"1")) {
2256722773 const align_bytes_minus_1 = ptr_align.toByteUnits().? - 1;
22568 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
22774 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2256922775 const remainder = try block.addBinOp(.bit_and, elem_coerced, align_minus_1);
2257022776 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
2257122777 try sema.addSafetyCheck(block, src, is_aligned, .incorrect_alignment);
......@@ -22575,7 +22781,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2257522781
2257622782 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2257722783 for (new_elems, 0..) |*new_elem, i| {
22578 const idx_ref = try mod.intRef(Type.usize, i);
22784 const idx_ref = try pt.intRef(Type.usize, i);
2257922785 const old_elem = try block.addBinOp(.array_elem_val, operand_coerced, idx_ref);
2258022786 new_elem.* = try block.addBitCast(ptr_ty, old_elem);
2258122787 }
......@@ -22590,31 +22796,33 @@ fn ptrFromIntVal(
2259022796 ptr_ty: Type,
2259122797 ptr_align: Alignment,
2259222798) !Value {
22593 const zcu = sema.mod;
22799 const pt = sema.pt;
22800 const zcu = pt.zcu;
2259422801 if (operand_val.isUndef(zcu)) {
2259522802 if (ptr_ty.isAllowzeroPtr(zcu) and ptr_align == .@"1") {
22596 return zcu.undefValue(ptr_ty);
22803 return pt.undefValue(ptr_ty);
2259722804 }
2259822805 return sema.failWithUseOfUndef(block, operand_src);
2259922806 }
22600 const addr = try operand_val.toUnsignedIntSema(zcu);
22807 const addr = try operand_val.toUnsignedIntSema(pt);
2260122808 if (!ptr_ty.isAllowzeroPtr(zcu) and addr == 0)
22602 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{ptr_ty.fmt(zcu)});
22809 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{ptr_ty.fmt(pt)});
2260322810 if (addr != 0 and ptr_align != .none and !ptr_align.check(addr))
22604 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{ptr_ty.fmt(zcu)});
22811 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{ptr_ty.fmt(pt)});
2260522812
2260622813 return switch (ptr_ty.zigTypeTag(zcu)) {
22607 .Optional => Value.fromInterned((try zcu.intern(.{ .opt = .{
22814 .Optional => Value.fromInterned(try pt.intern(.{ .opt = .{
2260822815 .ty = ptr_ty.toIntern(),
22609 .val = if (addr == 0) .none else (try zcu.ptrIntValue(ptr_ty.childType(zcu), addr)).toIntern(),
22610 } }))),
22611 .Pointer => try zcu.ptrIntValue(ptr_ty, addr),
22816 .val = if (addr == 0) .none else (try pt.ptrIntValue(ptr_ty.childType(zcu), addr)).toIntern(),
22817 } })),
22818 .Pointer => try pt.ptrIntValue(ptr_ty, addr),
2261222819 else => unreachable,
2261322820 };
2261422821}
2261522822
2261622823fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
22617 const mod = sema.mod;
22824 const pt = sema.pt;
22825 const mod = pt.zcu;
2261822826 const ip = &mod.intern_pool;
2261922827 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2262022828 const src = block.nodeOffset(extra.node);
......@@ -22642,8 +22850,8 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2264222850 errdefer msg.destroy(sema.gpa);
2264322851 const dest_ty = base_dest_ty.errorUnionPayload(mod);
2264422852 const operand_ty = base_operand_ty.errorUnionPayload(mod);
22645 try sema.errNote(src, msg, "destination payload is '{}'", .{dest_ty.fmt(mod)});
22646 try sema.errNote(src, msg, "operand payload is '{}'", .{operand_ty.fmt(mod)});
22853 try sema.errNote(src, msg, "destination payload is '{}'", .{dest_ty.fmt(pt)});
22854 try sema.errNote(src, msg, "operand payload is '{}'", .{operand_ty.fmt(pt)});
2264722855 try addDeclaredHereNote(sema, msg, dest_ty);
2264822856 try addDeclaredHereNote(sema, msg, operand_ty);
2264922857 break :msg msg;
......@@ -22684,7 +22892,7 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2268422892 };
2268522893 if (disjoint and dest_tag != .ErrorUnion) {
2268622894 return sema.fail(block, src, "error sets '{}' and '{}' have no common errors", .{
22687 operand_ty.fmt(sema.mod), dest_ty.fmt(sema.mod),
22895 operand_ty.fmt(pt), dest_ty.fmt(pt),
2268822896 });
2268922897 }
2269022898
......@@ -22700,24 +22908,24 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2270022908 }
2270122909 if (!Type.errorSetHasFieldIp(ip, dest_ty.toIntern(), error_name)) {
2270222910 return sema.fail(block, src, "'error.{}' not a member of error set '{}'", .{
22703 error_name.fmt(ip), dest_ty.fmt(sema.mod),
22911 error_name.fmt(ip), dest_ty.fmt(pt),
2270422912 });
2270522913 }
2270622914 }
2270722915
22708 return Air.internedToRef((try mod.getCoerced(val, base_dest_ty)).toIntern());
22916 return Air.internedToRef((try pt.getCoerced(val, base_dest_ty)).toIntern());
2270922917 }
2271022918
2271122919 try sema.requireRuntimeBlock(block, src, operand_src);
22712 const err_int_ty = try mod.errorIntType();
22920 const err_int_ty = try pt.errorIntType();
2271322921 if (block.wantSafety() and !dest_ty.isAnyError(mod) and
2271422922 dest_ty.toIntern() != .adhoc_inferred_error_set_type and
22715 sema.mod.backendSupportsFeature(.error_set_has_value))
22923 mod.backendSupportsFeature(.error_set_has_value))
2271622924 {
2271722925 if (dest_tag == .ErrorUnion) {
2271822926 const err_code = try sema.analyzeErrUnionCode(block, operand_src, operand);
2271922927 const err_int = try block.addBitCast(err_int_ty, err_code);
22720 const zero_err = try mod.intRef(try mod.errorIntType(), 0);
22928 const zero_err = try pt.intRef(try pt.errorIntType(), 0);
2272122929
2272222930 const is_zero = try block.addBinOp(.cmp_eq, err_int, zero_err);
2272322931 if (disjoint) {
......@@ -22786,7 +22994,8 @@ fn ptrCastFull(
2278622994 dest_ty: Type,
2278722995 operation: []const u8,
2278822996) CompileError!Air.Inst.Ref {
22789 const mod = sema.mod;
22997 const pt = sema.pt;
22998 const mod = pt.zcu;
2279022999 const operand_ty = sema.typeOf(operand);
2279123000
2279223001 try sema.checkPtrType(block, src, dest_ty, true);
......@@ -22795,8 +23004,8 @@ fn ptrCastFull(
2279523004 const src_info = operand_ty.ptrInfo(mod);
2279623005 const dest_info = dest_ty.ptrInfo(mod);
2279723006
22798 try Type.fromInterned(src_info.child).resolveLayout(mod);
22799 try Type.fromInterned(dest_info.child).resolveLayout(mod);
23007 try Type.fromInterned(src_info.child).resolveLayout(pt);
23008 try Type.fromInterned(dest_info.child).resolveLayout(pt);
2280023009
2280123010 const src_slice_like = src_info.flags.size == .Slice or
2280223011 (src_info.flags.size == .One and Type.fromInterned(src_info.child).zigTypeTag(mod) == .Array);
......@@ -22810,12 +23019,12 @@ fn ptrCastFull(
2281023019
2281123020 if (dest_info.flags.size == .Slice) {
2281223021 const src_elem_size = switch (src_info.flags.size) {
22813 .Slice => Type.fromInterned(src_info.child).abiSize(mod),
23022 .Slice => Type.fromInterned(src_info.child).abiSize(pt),
2281423023 // pointer to array
22815 .One => Type.fromInterned(src_info.child).childType(mod).abiSize(mod),
23024 .One => Type.fromInterned(src_info.child).childType(mod).abiSize(pt),
2281623025 else => unreachable,
2281723026 };
22818 const dest_elem_size = Type.fromInterned(dest_info.child).abiSize(mod);
23027 const dest_elem_size = Type.fromInterned(dest_info.child).abiSize(pt);
2281923028 if (src_elem_size != dest_elem_size) {
2282023029 return sema.fail(block, src, "TODO: implement {s} between slices changing the length", .{operation});
2282123030 }
......@@ -22867,8 +23076,7 @@ fn ptrCastFull(
2286723076 if (imc_res == .ok) break :check_child;
2286823077 return sema.failWithOwnedErrorMsg(block, msg: {
2286923078 const msg = try sema.errMsg(src, "pointer element type '{}' cannot coerce into element type '{}'", .{
22870 src_child.fmt(mod),
22871 dest_child.fmt(mod),
23079 src_child.fmt(pt), dest_child.fmt(pt),
2287223080 });
2287323081 errdefer msg.destroy(sema.gpa);
2287423082 try imc_res.report(sema, src, msg);
......@@ -22881,26 +23089,26 @@ fn ptrCastFull(
2288123089 if (dest_info.sentinel == .none) break :check_sent;
2288223090 if (src_info.flags.size == .C) break :check_sent;
2288323091 if (src_info.sentinel != .none) {
22884 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_info.sentinel, dest_info.child);
23092 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child);
2288523093 if (dest_info.sentinel == coerced_sent) break :check_sent;
2288623094 }
2288723095 if (src_slice_like and src_info.flags.size == .One and dest_info.flags.size == .Slice) {
2288823096 // [*]nT -> []T
2288923097 const arr_ty = Type.fromInterned(src_info.child);
2289023098 if (arr_ty.sentinel(mod)) |src_sentinel| {
22891 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_sentinel.toIntern(), dest_info.child);
23099 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, pt.tid, src_sentinel.toIntern(), dest_info.child);
2289223100 if (dest_info.sentinel == coerced_sent) break :check_sent;
2289323101 }
2289423102 }
2289523103 return sema.failWithOwnedErrorMsg(block, msg: {
2289623104 const msg = if (src_info.sentinel == .none) blk: {
2289723105 break :blk try sema.errMsg(src, "destination pointer requires '{}' sentinel", .{
22898 Value.fromInterned(dest_info.sentinel).fmtValue(mod, sema),
23106 Value.fromInterned(dest_info.sentinel).fmtValue(pt, sema),
2289923107 });
2290023108 } else blk: {
2290123109 break :blk try sema.errMsg(src, "pointer sentinel '{}' cannot coerce into pointer sentinel '{}'", .{
22902 Value.fromInterned(src_info.sentinel).fmtValue(mod, sema),
22903 Value.fromInterned(dest_info.sentinel).fmtValue(mod, sema),
23110 Value.fromInterned(src_info.sentinel).fmtValue(pt, sema),
23111 Value.fromInterned(dest_info.sentinel).fmtValue(pt, sema),
2290423112 });
2290523113 };
2290623114 errdefer msg.destroy(sema.gpa);
......@@ -22941,8 +23149,8 @@ fn ptrCastFull(
2294123149
2294223150 return sema.failWithOwnedErrorMsg(block, msg: {
2294323151 const msg = try sema.errMsg(src, "'{}' could have null values which are illegal in type '{}'", .{
22944 operand_ty.fmt(mod),
22945 dest_ty.fmt(mod),
23152 operand_ty.fmt(pt),
23153 dest_ty.fmt(pt),
2294623154 });
2294723155 errdefer msg.destroy(sema.gpa);
2294823156 try sema.errNote(src, msg, "use @ptrCast to assert the pointer is not null", .{});
......@@ -22956,12 +23164,12 @@ fn ptrCastFull(
2295623164 const src_align = if (src_info.flags.alignment != .none)
2295723165 src_info.flags.alignment
2295823166 else
22959 Type.fromInterned(src_info.child).abiAlignment(mod);
23167 Type.fromInterned(src_info.child).abiAlignment(pt);
2296023168
2296123169 const dest_align = if (dest_info.flags.alignment != .none)
2296223170 dest_info.flags.alignment
2296323171 else
22964 Type.fromInterned(dest_info.child).abiAlignment(mod);
23172 Type.fromInterned(dest_info.child).abiAlignment(pt);
2296523173
2296623174 if (!flags.align_cast) {
2296723175 if (dest_align.compare(.gt, src_align)) {
......@@ -22969,10 +23177,10 @@ fn ptrCastFull(
2296923177 const msg = try sema.errMsg(src, "{s} increases pointer alignment", .{operation});
2297023178 errdefer msg.destroy(sema.gpa);
2297123179 try sema.errNote(operand_src, msg, "'{}' has alignment '{d}'", .{
22972 operand_ty.fmt(mod), src_align.toByteUnits() orelse 0,
23180 operand_ty.fmt(pt), src_align.toByteUnits() orelse 0,
2297323181 });
2297423182 try sema.errNote(src, msg, "'{}' has alignment '{d}'", .{
22975 dest_ty.fmt(mod), dest_align.toByteUnits() orelse 0,
23183 dest_ty.fmt(pt), dest_align.toByteUnits() orelse 0,
2297623184 });
2297723185 try sema.errNote(src, msg, "use @alignCast to assert pointer alignment", .{});
2297823186 break :msg msg;
......@@ -22986,10 +23194,10 @@ fn ptrCastFull(
2298623194 const msg = try sema.errMsg(src, "{s} changes pointer address space", .{operation});
2298723195 errdefer msg.destroy(sema.gpa);
2298823196 try sema.errNote(operand_src, msg, "'{}' has address space '{s}'", .{
22989 operand_ty.fmt(mod), @tagName(src_info.flags.address_space),
23197 operand_ty.fmt(pt), @tagName(src_info.flags.address_space),
2299023198 });
2299123199 try sema.errNote(src, msg, "'{}' has address space '{s}'", .{
22992 dest_ty.fmt(mod), @tagName(dest_info.flags.address_space),
23200 dest_ty.fmt(pt), @tagName(dest_info.flags.address_space),
2299323201 });
2299423202 try sema.errNote(src, msg, "use @addrSpaceCast to cast pointer address space", .{});
2299523203 break :msg msg;
......@@ -23044,9 +23252,9 @@ fn ptrCastFull(
2304423252 // Only convert to a many-pointer at first
2304523253 var info = dest_info;
2304623254 info.flags.size = .Many;
23047 const ty = try mod.ptrTypeSema(info);
23255 const ty = try pt.ptrTypeSema(info);
2304823256 if (dest_ty.zigTypeTag(mod) == .Optional) {
23049 break :blk try mod.optionalType(ty.toIntern());
23257 break :blk try pt.optionalType(ty.toIntern());
2305023258 } else {
2305123259 break :blk ty;
2305223260 }
......@@ -23059,10 +23267,10 @@ fn ptrCastFull(
2305923267 return sema.failWithUseOfUndef(block, operand_src);
2306023268 }
2306123269 if (!dest_ty.ptrAllowsZero(mod) and ptr_val.isNull(mod)) {
23062 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(mod)});
23270 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(pt)});
2306323271 }
2306423272 if (dest_align.compare(.gt, src_align)) {
23065 if (try ptr_val.getUnsignedIntAdvanced(mod, .sema)) |addr| {
23273 if (try ptr_val.getUnsignedIntAdvanced(pt, .sema)) |addr| {
2306623274 if (!dest_align.check(addr)) {
2306723275 return sema.fail(block, operand_src, "pointer address 0x{X} is not aligned to {d} bytes", .{
2306823276 addr,
......@@ -23072,12 +23280,12 @@ fn ptrCastFull(
2307223280 }
2307323281 }
2307423282 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
23075 if (ptr_val.isUndef(mod)) return mod.undefRef(dest_ty);
23076 const arr_len = try mod.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod));
23283 if (ptr_val.isUndef(mod)) return pt.undefRef(dest_ty);
23284 const arr_len = try pt.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod));
2307723285 const ptr_val_key = mod.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
23078 return Air.internedToRef((try mod.intern(.{ .slice = .{
23286 return Air.internedToRef((try pt.intern(.{ .slice = .{
2307923287 .ty = dest_ty.toIntern(),
23080 .ptr = try mod.intern(.{ .ptr = .{
23288 .ptr = try pt.intern(.{ .ptr = .{
2308123289 .ty = dest_ty.slicePtrFieldType(mod).toIntern(),
2308223290 .base_addr = ptr_val_key.base_addr,
2308323291 .byte_offset = ptr_val_key.byte_offset,
......@@ -23086,7 +23294,7 @@ fn ptrCastFull(
2308623294 } })));
2308723295 } else {
2308823296 assert(dest_ptr_ty.eql(dest_ty, mod));
23089 return Air.internedToRef((try mod.getCoerced(ptr_val, dest_ty)).toIntern());
23297 return Air.internedToRef((try pt.getCoerced(ptr_val, dest_ty)).toIntern());
2309023298 }
2309123299 }
2309223300 }
......@@ -23112,7 +23320,7 @@ fn ptrCastFull(
2311223320 try sema.typeHasRuntimeBits(Type.fromInterned(dest_info.child)))
2311323321 {
2311423322 const align_bytes_minus_1 = dest_align.toByteUnits().? - 1;
23115 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
23323 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2311623324 const ptr_int = try block.addUnOp(.int_from_ptr, ptr);
2311723325 const remainder = try block.addBinOp(.bit_and, ptr_int, align_minus_1);
2311823326 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
......@@ -23129,9 +23337,9 @@ fn ptrCastFull(
2312923337 // We can't change address spaces with a bitcast, so this requires two instructions
2313023338 var intermediate_info = src_info;
2313123339 intermediate_info.flags.address_space = dest_info.flags.address_space;
23132 const intermediate_ptr_ty = try mod.ptrTypeSema(intermediate_info);
23340 const intermediate_ptr_ty = try pt.ptrTypeSema(intermediate_info);
2313323341 const intermediate_ty = if (dest_ptr_ty.zigTypeTag(mod) == .Optional) blk: {
23134 break :blk try mod.optionalType(intermediate_ptr_ty.toIntern());
23342 break :blk try pt.optionalType(intermediate_ptr_ty.toIntern());
2313523343 } else intermediate_ptr_ty;
2313623344 const intermediate = try block.addInst(.{
2313723345 .tag = .addrspace_cast,
......@@ -23152,7 +23360,7 @@ fn ptrCastFull(
2315223360 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
2315323361 // We have to construct a slice using the operand's child's array length
2315423362 // Note that we know from the check at the start of the function that operand_ty is slice-like
23155 const arr_len = Air.internedToRef((try mod.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod))).toIntern());
23363 const arr_len = Air.internedToRef((try pt.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod))).toIntern());
2315623364 return block.addInst(.{
2315723365 .tag = .slice,
2315823366 .data = .{ .ty_pl = .{
......@@ -23171,7 +23379,8 @@ fn ptrCastFull(
2317123379}
2317223380
2317323381fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
23174 const mod = sema.mod;
23382 const pt = sema.pt;
23383 const mod = pt.zcu;
2317523384 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).Struct.backing_integer.?;
2317623385 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));
2317723386 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
......@@ -23186,15 +23395,15 @@ fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
2318623395 if (flags.volatile_cast) ptr_info.flags.is_volatile = false;
2318723396
2318823397 const dest_ty = blk: {
23189 const dest_ty = try mod.ptrTypeSema(ptr_info);
23398 const dest_ty = try pt.ptrTypeSema(ptr_info);
2319023399 if (operand_ty.zigTypeTag(mod) == .Optional) {
23191 break :blk try mod.optionalType(dest_ty.toIntern());
23400 break :blk try pt.optionalType(dest_ty.toIntern());
2319223401 }
2319323402 break :blk dest_ty;
2319423403 };
2319523404
2319623405 if (try sema.resolveValue(operand)) |operand_val| {
23197 return Air.internedToRef((try mod.getCoerced(operand_val, dest_ty)).toIntern());
23406 return Air.internedToRef((try pt.getCoerced(operand_val, dest_ty)).toIntern());
2319823407 }
2319923408
2320023409 try sema.requireRuntimeBlock(block, src, null);
......@@ -23204,7 +23413,8 @@ fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
2320423413}
2320523414
2320623415fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
23207 const mod = sema.mod;
23416 const pt = sema.pt;
23417 const mod = pt.zcu;
2320823418 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2320923419 const src = block.nodeOffset(inst_data.src_node);
2321023420 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23218,7 +23428,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2321823428 const operand_is_vector = operand_ty.zigTypeTag(mod) == .Vector;
2321923429 const dest_is_vector = dest_ty.zigTypeTag(mod) == .Vector;
2322023430 if (operand_is_vector != dest_is_vector) {
23221 return sema.fail(block, operand_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(mod), operand_ty.fmt(mod) });
23431 return sema.fail(block, operand_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(pt), operand_ty.fmt(pt) });
2322223432 }
2322323433
2322423434 if (dest_scalar_ty.zigTypeTag(mod) == .ComptimeInt) {
......@@ -23239,7 +23449,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2323923449
2324023450 if (operand_info.signedness != dest_info.signedness) {
2324123451 return sema.fail(block, operand_src, "expected {s} integer type, found '{}'", .{
23242 @tagName(dest_info.signedness), operand_ty.fmt(mod),
23452 @tagName(dest_info.signedness), operand_ty.fmt(pt),
2324323453 });
2324423454 }
2324523455 if (operand_info.bits < dest_info.bits) {
......@@ -23247,7 +23457,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2324723457 const msg = try sema.errMsg(
2324823458 src,
2324923459 "destination type '{}' has more bits than source type '{}'",
23250 .{ dest_ty.fmt(mod), operand_ty.fmt(mod) },
23460 .{ dest_ty.fmt(pt), operand_ty.fmt(pt) },
2325123461 );
2325223462 errdefer msg.destroy(sema.gpa);
2325323463 try sema.errNote(src, msg, "destination type has {d} bits", .{
......@@ -23263,20 +23473,20 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2326323473 }
2326423474
2326523475 if (try sema.resolveValueIntable(operand)) |val| {
23266 if (val.isUndef(mod)) return mod.undefRef(dest_ty);
23476 if (val.isUndef(mod)) return pt.undefRef(dest_ty);
2326723477 if (!dest_is_vector) {
23268 return Air.internedToRef((try mod.getCoerced(
23269 try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, mod),
23478 return Air.internedToRef((try pt.getCoerced(
23479 try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, pt),
2327023480 dest_ty,
2327123481 )).toIntern());
2327223482 }
2327323483 const elems = try sema.arena.alloc(InternPool.Index, operand_ty.vectorLen(mod));
2327423484 for (elems, 0..) |*elem, i| {
23275 const elem_val = try val.elemValue(mod, i);
23276 const uncoerced_elem = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, mod);
23277 elem.* = (try mod.getCoerced(uncoerced_elem, dest_scalar_ty)).toIntern();
23485 const elem_val = try val.elemValue(pt, i);
23486 const uncoerced_elem = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, pt);
23487 elem.* = (try pt.getCoerced(uncoerced_elem, dest_scalar_ty)).toIntern();
2327823488 }
23279 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23489 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2328023490 .ty = dest_ty.toIntern(),
2328123491 .storage = .{ .elems = elems },
2328223492 } })));
......@@ -23291,9 +23501,10 @@ fn zirBitCount(
2329123501 block: *Block,
2329223502 inst: Zir.Inst.Index,
2329323503 air_tag: Air.Inst.Tag,
23294 comptime comptimeOp: fn (val: Value, ty: Type, mod: *Module) u64,
23504 comptime comptimeOp: fn (val: Value, ty: Type, pt: Zcu.PerThread) u64,
2329523505) CompileError!Air.Inst.Ref {
23296 const mod = sema.mod;
23506 const pt = sema.pt;
23507 const mod = pt.zcu;
2329723508 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2329823509 const src = block.nodeOffset(inst_data.src_node);
2329923510 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23306,25 +23517,25 @@ fn zirBitCount(
2330623517 return Air.internedToRef(val.toIntern());
2330723518 }
2330823519
23309 const result_scalar_ty = try mod.smallestUnsignedInt(bits);
23520 const result_scalar_ty = try pt.smallestUnsignedInt(bits);
2331023521 switch (operand_ty.zigTypeTag(mod)) {
2331123522 .Vector => {
2331223523 const vec_len = operand_ty.vectorLen(mod);
23313 const result_ty = try mod.vectorType(.{
23524 const result_ty = try pt.vectorType(.{
2331423525 .len = vec_len,
2331523526 .child = result_scalar_ty.toIntern(),
2331623527 });
2331723528 if (try sema.resolveValue(operand)) |val| {
23318 if (val.isUndef(mod)) return mod.undefRef(result_ty);
23529 if (val.isUndef(mod)) return pt.undefRef(result_ty);
2331923530
2332023531 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2332123532 const scalar_ty = operand_ty.scalarType(mod);
2332223533 for (elems, 0..) |*elem, i| {
23323 const elem_val = try val.elemValue(mod, i);
23324 const count = comptimeOp(elem_val, scalar_ty, mod);
23325 elem.* = (try mod.intValue(result_scalar_ty, count)).toIntern();
23534 const elem_val = try val.elemValue(pt, i);
23535 const count = comptimeOp(elem_val, scalar_ty, pt);
23536 elem.* = (try pt.intValue(result_scalar_ty, count)).toIntern();
2332623537 }
23327 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23538 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2332823539 .ty = result_ty.toIntern(),
2332923540 .storage = .{ .elems = elems },
2333023541 } })));
......@@ -23335,8 +23546,8 @@ fn zirBitCount(
2333523546 },
2333623547 .Int => {
2333723548 if (try sema.resolveValueResolveLazy(operand)) |val| {
23338 if (val.isUndef(mod)) return mod.undefRef(result_scalar_ty);
23339 return mod.intRef(result_scalar_ty, comptimeOp(val, operand_ty, mod));
23549 if (val.isUndef(mod)) return pt.undefRef(result_scalar_ty);
23550 return pt.intRef(result_scalar_ty, comptimeOp(val, operand_ty, pt));
2334023551 } else {
2334123552 try sema.requireRuntimeBlock(block, src, operand_src);
2334223553 return block.addTyOp(air_tag, result_scalar_ty, operand);
......@@ -23347,7 +23558,8 @@ fn zirBitCount(
2334723558}
2334823559
2334923560fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
23350 const mod = sema.mod;
23561 const pt = sema.pt;
23562 const mod = pt.zcu;
2335123563 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2335223564 const src = block.nodeOffset(inst_data.src_node);
2335323565 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23360,7 +23572,7 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2336023572 block,
2336123573 operand_src,
2336223574 "@byteSwap requires the number of bits to be evenly divisible by 8, but {} has {} bits",
23363 .{ scalar_ty.fmt(mod), bits },
23575 .{ scalar_ty.fmt(pt), bits },
2336423576 );
2336523577 }
2336623578
......@@ -23371,8 +23583,8 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2337123583 switch (operand_ty.zigTypeTag(mod)) {
2337223584 .Int => {
2337323585 const runtime_src = if (try sema.resolveValue(operand)) |val| {
23374 if (val.isUndef(mod)) return mod.undefRef(operand_ty);
23375 const result_val = try val.byteSwap(operand_ty, mod, sema.arena);
23586 if (val.isUndef(mod)) return pt.undefRef(operand_ty);
23587 const result_val = try val.byteSwap(operand_ty, pt, sema.arena);
2337623588 return Air.internedToRef(result_val.toIntern());
2337723589 } else operand_src;
2337823590
......@@ -23382,15 +23594,15 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2338223594 .Vector => {
2338323595 const runtime_src = if (try sema.resolveValue(operand)) |val| {
2338423596 if (val.isUndef(mod))
23385 return mod.undefRef(operand_ty);
23597 return pt.undefRef(operand_ty);
2338623598
2338723599 const vec_len = operand_ty.vectorLen(mod);
2338823600 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2338923601 for (elems, 0..) |*elem, i| {
23390 const elem_val = try val.elemValue(mod, i);
23391 elem.* = (try elem_val.byteSwap(scalar_ty, mod, sema.arena)).toIntern();
23602 const elem_val = try val.elemValue(pt, i);
23603 elem.* = (try elem_val.byteSwap(scalar_ty, pt, sema.arena)).toIntern();
2339223604 }
23393 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23605 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2339423606 .ty = operand_ty.toIntern(),
2339523607 .storage = .{ .elems = elems },
2339623608 } })));
......@@ -23415,12 +23627,13 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2341523627 return Air.internedToRef(val.toIntern());
2341623628 }
2341723629
23418 const mod = sema.mod;
23630 const pt = sema.pt;
23631 const mod = pt.zcu;
2341923632 switch (operand_ty.zigTypeTag(mod)) {
2342023633 .Int => {
2342123634 const runtime_src = if (try sema.resolveValue(operand)) |val| {
23422 if (val.isUndef(mod)) return mod.undefRef(operand_ty);
23423 const result_val = try val.bitReverse(operand_ty, mod, sema.arena);
23635 if (val.isUndef(mod)) return pt.undefRef(operand_ty);
23636 const result_val = try val.bitReverse(operand_ty, pt, sema.arena);
2342423637 return Air.internedToRef(result_val.toIntern());
2342523638 } else operand_src;
2342623639
......@@ -23430,15 +23643,15 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2343023643 .Vector => {
2343123644 const runtime_src = if (try sema.resolveValue(operand)) |val| {
2343223645 if (val.isUndef(mod))
23433 return mod.undefRef(operand_ty);
23646 return pt.undefRef(operand_ty);
2343423647
2343523648 const vec_len = operand_ty.vectorLen(mod);
2343623649 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2343723650 for (elems, 0..) |*elem, i| {
23438 const elem_val = try val.elemValue(mod, i);
23439 elem.* = (try elem_val.bitReverse(scalar_ty, mod, sema.arena)).toIntern();
23651 const elem_val = try val.elemValue(pt, i);
23652 elem.* = (try elem_val.bitReverse(scalar_ty, pt, sema.arena)).toIntern();
2344023653 }
23441 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23654 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2344223655 .ty = operand_ty.toIntern(),
2344323656 .storage = .{ .elems = elems },
2344423657 } })));
......@@ -23453,13 +23666,13 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2345323666
2345423667fn zirBitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2345523668 const offset = try sema.bitOffsetOf(block, inst);
23456 return sema.mod.intRef(Type.comptime_int, offset);
23669 return sema.pt.intRef(Type.comptime_int, offset);
2345723670}
2345823671
2345923672fn zirOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2346023673 const offset = try sema.bitOffsetOf(block, inst);
2346123674 // TODO reminder to make this a compile error for packed structs
23462 return sema.mod.intRef(Type.comptime_int, offset / 8);
23675 return sema.pt.intRef(Type.comptime_int, offset / 8);
2346323676}
2346423677
2346523678fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u64 {
......@@ -23474,12 +23687,13 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
2347423687 .needed_comptime_reason = "name of field must be comptime-known",
2347523688 });
2347623689
23477 const mod = sema.mod;
23690 const pt = sema.pt;
23691 const mod = pt.zcu;
2347823692 const ip = &mod.intern_pool;
23479 try ty.resolveLayout(mod);
23693 try ty.resolveLayout(pt);
2348023694 switch (ty.zigTypeTag(mod)) {
2348123695 .Struct => {},
23482 else => return sema.fail(block, lhs_src, "expected struct type, found '{}'", .{ty.fmt(mod)}),
23696 else => return sema.fail(block, lhs_src, "expected struct type, found '{}'", .{ty.fmt(pt)}),
2348323697 }
2348423698
2348523699 const field_index = if (ty.isTuple(mod)) blk: {
......@@ -23502,28 +23716,30 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
2350223716 return bit_sum;
2350323717 }
2350423718 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
23505 bit_sum += field_ty.bitSize(mod);
23719 bit_sum += field_ty.bitSize(pt);
2350623720 } else unreachable;
2350723721 },
23508 else => return ty.structFieldOffset(field_index, mod) * 8,
23722 else => return ty.structFieldOffset(field_index, pt) * 8,
2350923723 }
2351023724}
2351123725
2351223726fn checkNamespaceType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
23513 const mod = sema.mod;
23727 const pt = sema.pt;
23728 const mod = pt.zcu;
2351423729 switch (ty.zigTypeTag(mod)) {
2351523730 .Struct, .Enum, .Union, .Opaque => return,
23516 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(mod)}),
23731 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(pt)}),
2351723732 }
2351823733}
2351923734
2352023735/// Returns `true` if the type was a comptime_int.
2352123736fn checkIntType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!bool {
23522 const mod = sema.mod;
23737 const pt = sema.pt;
23738 const mod = pt.zcu;
2352323739 switch (try ty.zigTypeTagOrPoison(mod)) {
2352423740 .ComptimeInt => return true,
2352523741 .Int => return false,
23526 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(mod)}),
23742 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(pt)}),
2352723743 }
2352823744}
2352923745
......@@ -23533,7 +23749,8 @@ fn checkInvalidPtrArithmetic(
2353323749 src: LazySrcLoc,
2353423750 ty: Type,
2353523751) CompileError!void {
23536 const mod = sema.mod;
23752 const pt = sema.pt;
23753 const mod = pt.zcu;
2353723754 switch (try ty.zigTypeTagOrPoison(mod)) {
2353823755 .Pointer => switch (ty.ptrSize(mod)) {
2353923756 .One, .Slice => return,
......@@ -23573,7 +23790,8 @@ fn checkPtrOperand(
2357323790 ty_src: LazySrcLoc,
2357423791 ty: Type,
2357523792) CompileError!void {
23576 const mod = sema.mod;
23793 const pt = sema.pt;
23794 const mod = pt.zcu;
2357723795 switch (ty.zigTypeTag(mod)) {
2357823796 .Pointer => return,
2357923797 .Fn => {
......@@ -23581,7 +23799,7 @@ fn checkPtrOperand(
2358123799 const msg = try sema.errMsg(
2358223800 ty_src,
2358323801 "expected pointer, found '{}'",
23584 .{ty.fmt(mod)},
23802 .{ty.fmt(pt)},
2358523803 );
2358623804 errdefer msg.destroy(sema.gpa);
2358723805
......@@ -23594,7 +23812,7 @@ fn checkPtrOperand(
2359423812 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2359523813 else => {},
2359623814 }
23597 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
23815 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(pt)});
2359823816}
2359923817
2360023818fn checkPtrType(
......@@ -23604,7 +23822,8 @@ fn checkPtrType(
2360423822 ty: Type,
2360523823 allow_slice: bool,
2360623824) CompileError!void {
23607 const mod = sema.mod;
23825 const pt = sema.pt;
23826 const mod = pt.zcu;
2360823827 switch (ty.zigTypeTag(mod)) {
2360923828 .Pointer => if (allow_slice or !ty.isSlice(mod)) return,
2361023829 .Fn => {
......@@ -23612,7 +23831,7 @@ fn checkPtrType(
2361223831 const msg = try sema.errMsg(
2361323832 ty_src,
2361423833 "expected pointer type, found '{}'",
23615 .{ty.fmt(mod)},
23834 .{ty.fmt(pt)},
2361623835 );
2361723836 errdefer msg.destroy(sema.gpa);
2361823837
......@@ -23625,7 +23844,7 @@ fn checkPtrType(
2362523844 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2362623845 else => {},
2362723846 }
23628 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
23847 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(pt)});
2362923848}
2363023849
2363123850fn checkVectorElemType(
......@@ -23634,13 +23853,14 @@ fn checkVectorElemType(
2363423853 ty_src: LazySrcLoc,
2363523854 ty: Type,
2363623855) CompileError!void {
23637 const mod = sema.mod;
23856 const pt = sema.pt;
23857 const mod = pt.zcu;
2363823858 switch (ty.zigTypeTag(mod)) {
2363923859 .Int, .Float, .Bool => return,
2364023860 .Optional, .Pointer => if (ty.isPtrAtRuntime(mod)) return,
2364123861 else => {},
2364223862 }
23643 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(mod)});
23863 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(pt)});
2364423864}
2364523865
2364623866fn checkFloatType(
......@@ -23649,10 +23869,11 @@ fn checkFloatType(
2364923869 ty_src: LazySrcLoc,
2365023870 ty: Type,
2365123871) CompileError!void {
23652 const mod = sema.mod;
23872 const pt = sema.pt;
23873 const mod = pt.zcu;
2365323874 switch (ty.zigTypeTag(mod)) {
2365423875 .ComptimeInt, .ComptimeFloat, .Float => {},
23655 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(mod)}),
23876 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(pt)}),
2365623877 }
2365723878}
2365823879
......@@ -23662,14 +23883,15 @@ fn checkNumericType(
2366223883 ty_src: LazySrcLoc,
2366323884 ty: Type,
2366423885) CompileError!void {
23665 const mod = sema.mod;
23886 const pt = sema.pt;
23887 const mod = pt.zcu;
2366623888 switch (ty.zigTypeTag(mod)) {
2366723889 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
2366823890 .Vector => switch (ty.childType(mod).zigTypeTag(mod)) {
2366923891 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
2367023892 else => |t| return sema.fail(block, ty_src, "expected number, found '{}'", .{t}),
2367123893 },
23672 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(mod)}),
23894 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(pt)}),
2367323895 }
2367423896}
2367523897
......@@ -23683,7 +23905,8 @@ fn checkAtomicPtrOperand(
2368323905 ptr_src: LazySrcLoc,
2368423906 ptr_const: bool,
2368523907) CompileError!Air.Inst.Ref {
23686 const mod = sema.mod;
23908 const pt = sema.pt;
23909 const mod = pt.zcu;
2368723910 var diag: Module.AtomicPtrAlignmentDiagnostics = .{};
2368823911 const alignment = mod.atomicPtrAlignment(elem_ty, &diag) catch |err| switch (err) {
2368923912 error.OutOfMemory => return error.OutOfMemory,
......@@ -23703,7 +23926,7 @@ fn checkAtomicPtrOperand(
2370323926 block,
2370423927 elem_ty_src,
2370523928 "expected bool, integer, float, enum, or pointer type; found '{}'",
23706 .{elem_ty.fmt(mod)},
23929 .{elem_ty.fmt(pt)},
2370723930 ),
2370823931 };
2370923932
......@@ -23719,7 +23942,7 @@ fn checkAtomicPtrOperand(
2371923942 const ptr_data = switch (try ptr_ty.zigTypeTagOrPoison(mod)) {
2372023943 .Pointer => ptr_ty.ptrInfo(mod),
2372123944 else => {
23722 const wanted_ptr_ty = try mod.ptrTypeSema(wanted_ptr_data);
23945 const wanted_ptr_ty = try pt.ptrTypeSema(wanted_ptr_data);
2372323946 _ = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);
2372423947 unreachable;
2372523948 },
......@@ -23729,7 +23952,7 @@ fn checkAtomicPtrOperand(
2372923952 wanted_ptr_data.flags.is_allowzero = ptr_data.flags.is_allowzero;
2373023953 wanted_ptr_data.flags.is_volatile = ptr_data.flags.is_volatile;
2373123954
23732 const wanted_ptr_ty = try mod.ptrTypeSema(wanted_ptr_data);
23955 const wanted_ptr_ty = try pt.ptrTypeSema(wanted_ptr_data);
2373323956 const casted_ptr = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);
2373423957
2373523958 return casted_ptr;
......@@ -23754,7 +23977,8 @@ fn checkIntOrVector(
2375423977 operand: Air.Inst.Ref,
2375523978 operand_src: LazySrcLoc,
2375623979) CompileError!Type {
23757 const mod = sema.mod;
23980 const pt = sema.pt;
23981 const mod = pt.zcu;
2375823982 const operand_ty = sema.typeOf(operand);
2375923983 switch (try operand_ty.zigTypeTagOrPoison(mod)) {
2376023984 .Int => return operand_ty,
......@@ -23763,12 +23987,12 @@ fn checkIntOrVector(
2376323987 switch (try elem_ty.zigTypeTagOrPoison(mod)) {
2376423988 .Int => return elem_ty,
2376523989 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
23766 elem_ty.fmt(mod),
23990 elem_ty.fmt(pt),
2376723991 }),
2376823992 }
2376923993 },
2377023994 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
23771 operand_ty.fmt(mod),
23995 operand_ty.fmt(pt),
2377223996 }),
2377323997 }
2377423998}
......@@ -23779,7 +24003,8 @@ fn checkIntOrVectorAllowComptime(
2377924003 operand_ty: Type,
2378024004 operand_src: LazySrcLoc,
2378124005) CompileError!Type {
23782 const mod = sema.mod;
24006 const pt = sema.pt;
24007 const mod = pt.zcu;
2378324008 switch (try operand_ty.zigTypeTagOrPoison(mod)) {
2378424009 .Int, .ComptimeInt => return operand_ty,
2378524010 .Vector => {
......@@ -23787,12 +24012,12 @@ fn checkIntOrVectorAllowComptime(
2378724012 switch (try elem_ty.zigTypeTagOrPoison(mod)) {
2378824013 .Int, .ComptimeInt => return elem_ty,
2378924014 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
23790 elem_ty.fmt(mod),
24015 elem_ty.fmt(pt),
2379124016 }),
2379224017 }
2379324018 },
2379424019 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
23795 operand_ty.fmt(mod),
24020 operand_ty.fmt(pt),
2379624021 }),
2379724022 }
2379824023}
......@@ -23819,7 +24044,8 @@ fn checkSimdBinOp(
2381924044 lhs_src: LazySrcLoc,
2382024045 rhs_src: LazySrcLoc,
2382124046) CompileError!SimdBinOp {
23822 const mod = sema.mod;
24047 const pt = sema.pt;
24048 const mod = pt.zcu;
2382324049 const lhs_ty = sema.typeOf(uncasted_lhs);
2382424050 const rhs_ty = sema.typeOf(uncasted_rhs);
2382524051
......@@ -23851,7 +24077,8 @@ fn checkVectorizableBinaryOperands(
2385124077 lhs_src: LazySrcLoc,
2385224078 rhs_src: LazySrcLoc,
2385324079) CompileError!void {
23854 const mod = sema.mod;
24080 const pt = sema.pt;
24081 const mod = pt.zcu;
2385524082 const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison(mod);
2385624083 const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison(mod);
2385724084 if (lhs_zig_ty_tag != .Vector and rhs_zig_ty_tag != .Vector) return;
......@@ -23881,7 +24108,7 @@ fn checkVectorizableBinaryOperands(
2388124108 } else {
2388224109 const msg = msg: {
2388324110 const msg = try sema.errMsg(src, "mixed scalar and vector operands: '{}' and '{}'", .{
23884 lhs_ty.fmt(mod), rhs_ty.fmt(mod),
24111 lhs_ty.fmt(pt), rhs_ty.fmt(pt),
2388524112 });
2388624113 errdefer msg.destroy(sema.gpa);
2388724114 if (lhs_is_vector) {
......@@ -23903,10 +24130,11 @@ fn resolveExportOptions(
2390324130 src: LazySrcLoc,
2390424131 zir_ref: Zir.Inst.Ref,
2390524132) CompileError!Module.Export.Options {
23906 const mod = sema.mod;
24133 const pt = sema.pt;
24134 const mod = pt.zcu;
2390724135 const gpa = sema.gpa;
2390824136 const ip = &mod.intern_pool;
23909 const export_options_ty = try mod.getBuiltinType("ExportOptions");
24137 const export_options_ty = try pt.getBuiltinType("ExportOptions");
2391024138 const air_ref = try sema.resolveInst(zir_ref);
2391124139 const options = try sema.coerce(block, export_options_ty, air_ref, src);
2391224140
......@@ -23969,12 +24197,12 @@ fn resolveBuiltinEnum(
2396924197 comptime name: []const u8,
2397024198 reason: NeededComptimeReason,
2397124199) CompileError!@field(std.builtin, name) {
23972 const mod = sema.mod;
23973 const ty = try mod.getBuiltinType(name);
24200 const pt = sema.pt;
24201 const ty = try pt.getBuiltinType(name);
2397424202 const air_ref = try sema.resolveInst(zir_ref);
2397524203 const coerced = try sema.coerce(block, ty, air_ref, src);
2397624204 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
23977 return mod.toEnum(@field(std.builtin, name), val);
24205 return pt.zcu.toEnum(@field(std.builtin, name), val);
2397824206}
2397924207
2398024208fn resolveAtomicOrder(
......@@ -24003,7 +24231,8 @@ fn zirCmpxchg(
2400324231 block: *Block,
2400424232 extended: Zir.Inst.Extended.InstData,
2400524233) CompileError!Air.Inst.Ref {
24006 const mod = sema.mod;
24234 const pt = sema.pt;
24235 const mod = pt.zcu;
2400724236 const extra = sema.code.extraData(Zir.Inst.Cmpxchg, extended.operand).data;
2400824237 const air_tag: Air.Inst.Tag = switch (extended.small) {
2400924238 0 => .cmpxchg_weak,
......@@ -24026,7 +24255,7 @@ fn zirCmpxchg(
2402624255 block,
2402724256 elem_ty_src,
2402824257 "expected bool, integer, enum, or pointer type; found '{}'",
24029 .{elem_ty.fmt(mod)},
24258 .{elem_ty.fmt(pt)},
2403024259 );
2403124260 }
2403224261 const uncasted_ptr = try sema.resolveInst(extra.ptr);
......@@ -24052,11 +24281,11 @@ fn zirCmpxchg(
2405224281 return sema.fail(block, failure_order_src, "failure atomic ordering must not be release or acq_rel", .{});
2405324282 }
2405424283
24055 const result_ty = try mod.optionalType(elem_ty.toIntern());
24284 const result_ty = try pt.optionalType(elem_ty.toIntern());
2405624285
2405724286 // special case zero bit types
2405824287 if ((try sema.typeHasOnePossibleValue(elem_ty)) != null) {
24059 return Air.internedToRef((try mod.intern(.{ .opt = .{
24288 return Air.internedToRef((try pt.intern(.{ .opt = .{
2406024289 .ty = result_ty.toIntern(),
2406124290 .val = .none,
2406224291 } })));
......@@ -24068,11 +24297,11 @@ fn zirCmpxchg(
2406824297 if (expected_val.isUndef(mod) or new_val.isUndef(mod)) {
2406924298 // TODO: this should probably cause the memory stored at the pointer
2407024299 // to become undef as well
24071 return mod.undefRef(result_ty);
24300 return pt.undefRef(result_ty);
2407224301 }
2407324302 const ptr_ty = sema.typeOf(ptr);
2407424303 const stored_val = (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) orelse break :rs ptr_src;
24075 const result_val = try mod.intern(.{ .opt = .{
24304 const result_val = try pt.intern(.{ .opt = .{
2407624305 .ty = result_ty.toIntern(),
2407724306 .val = if (stored_val.eql(expected_val, elem_ty, mod)) blk: {
2407824307 try sema.storePtr(block, src, ptr, new_value);
......@@ -24103,17 +24332,18 @@ fn zirCmpxchg(
2410324332}
2410424333
2410524334fn zirSplat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24106 const mod = sema.mod;
24335 const pt = sema.pt;
24336 const mod = pt.zcu;
2410724337 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2410824338 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
2410924339 const src = block.nodeOffset(inst_data.src_node);
2411024340 const scalar_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2411124341 const dest_ty = try sema.resolveDestType(block, src, extra.lhs, .remove_eu_opt, "@splat");
2411224342
24113 if (!dest_ty.isVector(mod)) return sema.fail(block, src, "expected vector type, found '{}'", .{dest_ty.fmt(mod)});
24343 if (!dest_ty.isVector(mod)) return sema.fail(block, src, "expected vector type, found '{}'", .{dest_ty.fmt(pt)});
2411424344
24115 if (!dest_ty.hasRuntimeBits(mod)) {
24116 const empty_aggregate = try mod.intern(.{ .aggregate = .{
24345 if (!dest_ty.hasRuntimeBits(pt)) {
24346 const empty_aggregate = try pt.intern(.{ .aggregate = .{
2411724347 .ty = dest_ty.toIntern(),
2411824348 .storage = .{ .elems = &[_]InternPool.Index{} },
2411924349 } });
......@@ -24124,7 +24354,7 @@ fn zirSplat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
2412424354 const scalar_ty = dest_ty.childType(mod);
2412524355 const scalar = try sema.coerce(block, scalar_ty, operand, scalar_src);
2412624356 if (try sema.resolveValue(scalar)) |scalar_val| {
24127 if (scalar_val.isUndef(mod)) return mod.undefRef(dest_ty);
24357 if (scalar_val.isUndef(mod)) return pt.undefRef(dest_ty);
2412824358 return Air.internedToRef((try sema.splat(dest_ty, scalar_val)).toIntern());
2412924359 }
2413024360
......@@ -24142,10 +24372,11 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2414224372 });
2414324373 const operand = try sema.resolveInst(extra.rhs);
2414424374 const operand_ty = sema.typeOf(operand);
24145 const mod = sema.mod;
24375 const pt = sema.pt;
24376 const mod = pt.zcu;
2414624377
2414724378 if (operand_ty.zigTypeTag(mod) != .Vector) {
24148 return sema.fail(block, operand_src, "expected vector, found '{}'", .{operand_ty.fmt(mod)});
24379 return sema.fail(block, operand_src, "expected vector, found '{}'", .{operand_ty.fmt(pt)});
2414924380 }
2415024381
2415124382 const scalar_ty = operand_ty.childType(mod);
......@@ -24155,13 +24386,13 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2415524386 .And, .Or, .Xor => switch (scalar_ty.zigTypeTag(mod)) {
2415624387 .Int, .Bool => {},
2415724388 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or boolean operand; found '{}'", .{
24158 @tagName(operation), operand_ty.fmt(mod),
24389 @tagName(operation), operand_ty.fmt(pt),
2415924390 }),
2416024391 },
2416124392 .Min, .Max, .Add, .Mul => switch (scalar_ty.zigTypeTag(mod)) {
2416224393 .Int, .Float => {},
2416324394 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or float operand; found '{}'", .{
24164 @tagName(operation), operand_ty.fmt(mod),
24395 @tagName(operation), operand_ty.fmt(pt),
2416524396 }),
2416624397 },
2416724398 }
......@@ -24174,20 +24405,20 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2417424405 }
2417524406
2417624407 if (try sema.resolveValue(operand)) |operand_val| {
24177 if (operand_val.isUndef(mod)) return mod.undefRef(scalar_ty);
24408 if (operand_val.isUndef(mod)) return pt.undefRef(scalar_ty);
2417824409
24179 var accum: Value = try operand_val.elemValue(mod, 0);
24410 var accum: Value = try operand_val.elemValue(pt, 0);
2418024411 var i: u32 = 1;
2418124412 while (i < vec_len) : (i += 1) {
24182 const elem_val = try operand_val.elemValue(mod, i);
24413 const elem_val = try operand_val.elemValue(pt, i);
2418324414 switch (operation) {
24184 .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, mod),
24185 .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, mod),
24186 .Xor => accum = try accum.bitwiseXor(elem_val, scalar_ty, sema.arena, mod),
24187 .Min => accum = accum.numberMin(elem_val, mod),
24188 .Max => accum = accum.numberMax(elem_val, mod),
24415 .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, pt),
24416 .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, pt),
24417 .Xor => accum = try accum.bitwiseXor(elem_val, scalar_ty, sema.arena, pt),
24418 .Min => accum = accum.numberMin(elem_val, pt),
24419 .Max => accum = accum.numberMax(elem_val, pt),
2418924420 .Add => accum = try sema.numberAddWrapScalar(accum, elem_val, scalar_ty),
24190 .Mul => accum = try accum.numberMulWrap(elem_val, scalar_ty, sema.arena, mod),
24421 .Mul => accum = try accum.numberMulWrap(elem_val, scalar_ty, sema.arena, pt),
2419124422 }
2419224423 }
2419324424 return Air.internedToRef(accum.toIntern());
......@@ -24204,7 +24435,8 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2420424435}
2420524436
2420624437fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24207 const mod = sema.mod;
24438 const pt = sema.pt;
24439 const mod = pt.zcu;
2420824440 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2420924441 const extra = sema.code.extraData(Zir.Inst.Shuffle, inst_data.payload_index).data;
2421024442 const elem_ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -24219,9 +24451,9 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2421924451
2422024452 const mask_len = switch (sema.typeOf(mask).zigTypeTag(mod)) {
2422124453 .Array, .Vector => sema.typeOf(mask).arrayLen(mod),
24222 else => return sema.fail(block, mask_src, "expected vector or array, found '{}'", .{sema.typeOf(mask).fmt(sema.mod)}),
24454 else => return sema.fail(block, mask_src, "expected vector or array, found '{}'", .{sema.typeOf(mask).fmt(pt)}),
2422324455 };
24224 mask_ty = try mod.vectorType(.{
24456 mask_ty = try pt.vectorType(.{
2422524457 .len = @intCast(mask_len),
2422624458 .child = .i32_type,
2422724459 });
......@@ -24242,51 +24474,51 @@ fn analyzeShuffle(
2424224474 mask: Value,
2424324475 mask_len: u32,
2424424476) CompileError!Air.Inst.Ref {
24245 const mod = sema.mod;
24477 const pt = sema.pt;
2424624478 const a_src = block.builtinCallArgSrc(src_node, 1);
2424724479 const b_src = block.builtinCallArgSrc(src_node, 2);
2424824480 const mask_src = block.builtinCallArgSrc(src_node, 3);
2424924481 var a = a_arg;
2425024482 var b = b_arg;
2425124483
24252 const res_ty = try mod.vectorType(.{
24484 const res_ty = try pt.vectorType(.{
2425324485 .len = mask_len,
2425424486 .child = elem_ty.toIntern(),
2425524487 });
2425624488
24257 const maybe_a_len = switch (sema.typeOf(a).zigTypeTag(mod)) {
24258 .Array, .Vector => sema.typeOf(a).arrayLen(mod),
24489 const maybe_a_len = switch (sema.typeOf(a).zigTypeTag(pt.zcu)) {
24490 .Array, .Vector => sema.typeOf(a).arrayLen(pt.zcu),
2425924491 .Undefined => null,
2426024492 else => return sema.fail(block, a_src, "expected vector or array with element type '{}', found '{}'", .{
24261 elem_ty.fmt(sema.mod),
24262 sema.typeOf(a).fmt(sema.mod),
24493 elem_ty.fmt(pt),
24494 sema.typeOf(a).fmt(pt),
2426324495 }),
2426424496 };
24265 const maybe_b_len = switch (sema.typeOf(b).zigTypeTag(mod)) {
24266 .Array, .Vector => sema.typeOf(b).arrayLen(mod),
24497 const maybe_b_len = switch (sema.typeOf(b).zigTypeTag(pt.zcu)) {
24498 .Array, .Vector => sema.typeOf(b).arrayLen(pt.zcu),
2426724499 .Undefined => null,
2426824500 else => return sema.fail(block, b_src, "expected vector or array with element type '{}', found '{}'", .{
24269 elem_ty.fmt(sema.mod),
24270 sema.typeOf(b).fmt(sema.mod),
24501 elem_ty.fmt(pt),
24502 sema.typeOf(b).fmt(pt),
2427124503 }),
2427224504 };
2427324505 if (maybe_a_len == null and maybe_b_len == null) {
24274 return mod.undefRef(res_ty);
24506 return pt.undefRef(res_ty);
2427524507 }
2427624508 const a_len: u32 = @intCast(maybe_a_len orelse maybe_b_len.?);
2427724509 const b_len: u32 = @intCast(maybe_b_len orelse a_len);
2427824510
24279 const a_ty = try mod.vectorType(.{
24511 const a_ty = try pt.vectorType(.{
2428024512 .len = a_len,
2428124513 .child = elem_ty.toIntern(),
2428224514 });
24283 const b_ty = try mod.vectorType(.{
24515 const b_ty = try pt.vectorType(.{
2428424516 .len = b_len,
2428524517 .child = elem_ty.toIntern(),
2428624518 });
2428724519
24288 if (maybe_a_len == null) a = try mod.undefRef(a_ty) else a = try sema.coerce(block, a_ty, a, a_src);
24289 if (maybe_b_len == null) b = try mod.undefRef(b_ty) else b = try sema.coerce(block, b_ty, b, b_src);
24520 if (maybe_a_len == null) a = try pt.undefRef(a_ty) else a = try sema.coerce(block, a_ty, a, a_src);
24521 if (maybe_b_len == null) b = try pt.undefRef(b_ty) else b = try sema.coerce(block, b_ty, b, b_src);
2429024522
2429124523 const operand_info = [2]std.meta.Tuple(&.{ u64, LazySrcLoc, Type }){
2429224524 .{ a_len, a_src, a_ty },
......@@ -24294,10 +24526,10 @@ fn analyzeShuffle(
2429424526 };
2429524527
2429624528 for (0..@intCast(mask_len)) |i| {
24297 const elem = try mask.elemValue(sema.mod, i);
24298 if (elem.isUndef(mod)) continue;
24529 const elem = try mask.elemValue(pt, i);
24530 if (elem.isUndef(pt.zcu)) continue;
2429924531 const elem_resolved = try sema.resolveLazyValue(elem);
24300 const int = elem_resolved.toSignedInt(mod);
24532 const int = elem_resolved.toSignedInt(pt);
2430124533 var unsigned: u32 = undefined;
2430224534 var chosen: u32 = undefined;
2430324535 if (int >= 0) {
......@@ -24314,7 +24546,7 @@ fn analyzeShuffle(
2431424546
2431524547 try sema.errNote(operand_info[chosen][1], msg, "selected index '{d}' out of bounds of '{}'", .{
2431624548 unsigned,
24317 operand_info[chosen][2].fmt(sema.mod),
24549 operand_info[chosen][2].fmt(pt),
2431824550 });
2431924551
2432024552 if (chosen == 0) {
......@@ -24331,16 +24563,16 @@ fn analyzeShuffle(
2433124563 if (try sema.resolveValue(b)) |b_val| {
2433224564 const values = try sema.arena.alloc(InternPool.Index, mask_len);
2433324565 for (values, 0..) |*value, i| {
24334 const mask_elem_val = try mask.elemValue(sema.mod, i);
24335 if (mask_elem_val.isUndef(mod)) {
24336 value.* = try mod.intern(.{ .undef = elem_ty.toIntern() });
24566 const mask_elem_val = try mask.elemValue(pt, i);
24567 if (mask_elem_val.isUndef(pt.zcu)) {
24568 value.* = try pt.intern(.{ .undef = elem_ty.toIntern() });
2433724569 continue;
2433824570 }
24339 const int = mask_elem_val.toSignedInt(mod);
24571 const int = mask_elem_val.toSignedInt(pt);
2434024572 const unsigned: u32 = @intCast(if (int >= 0) int else ~int);
24341 values[i] = (try (if (int >= 0) a_val else b_val).elemValue(mod, unsigned)).toIntern();
24573 values[i] = (try (if (int >= 0) a_val else b_val).elemValue(pt, unsigned)).toIntern();
2434224574 }
24343 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
24575 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2434424576 .ty = res_ty.toIntern(),
2434524577 .storage = .{ .elems = values },
2434624578 } })));
......@@ -24359,21 +24591,21 @@ fn analyzeShuffle(
2435924591
2436024592 const expand_mask_values = try sema.arena.alloc(InternPool.Index, max_len);
2436124593 for (@intCast(0)..@intCast(min_len)) |i| {
24362 expand_mask_values[i] = (try mod.intValue(Type.comptime_int, i)).toIntern();
24594 expand_mask_values[i] = (try pt.intValue(Type.comptime_int, i)).toIntern();
2436324595 }
2436424596 for (@intCast(min_len)..@intCast(max_len)) |i| {
24365 expand_mask_values[i] = (try mod.intValue(Type.comptime_int, -1)).toIntern();
24597 expand_mask_values[i] = (try pt.intValue(Type.comptime_int, -1)).toIntern();
2436624598 }
24367 const expand_mask = try mod.intern(.{ .aggregate = .{
24368 .ty = (try mod.vectorType(.{ .len = @intCast(max_len), .child = .comptime_int_type })).toIntern(),
24599 const expand_mask = try pt.intern(.{ .aggregate = .{
24600 .ty = (try pt.vectorType(.{ .len = @intCast(max_len), .child = .comptime_int_type })).toIntern(),
2436924601 .storage = .{ .elems = expand_mask_values },
2437024602 } });
2437124603
2437224604 if (a_len < b_len) {
24373 const undef = try mod.undefRef(a_ty);
24605 const undef = try pt.undefRef(a_ty);
2437424606 a = try sema.analyzeShuffle(block, src_node, elem_ty, a, undef, Value.fromInterned(expand_mask), @intCast(max_len));
2437524607 } else {
24376 const undef = try mod.undefRef(b_ty);
24608 const undef = try pt.undefRef(b_ty);
2437724609 b = try sema.analyzeShuffle(block, src_node, elem_ty, b, undef, Value.fromInterned(expand_mask), @intCast(max_len));
2437824610 }
2437924611 }
......@@ -24393,7 +24625,8 @@ fn analyzeShuffle(
2439324625}
2439424626
2439524627fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
24396 const mod = sema.mod;
24628 const pt = sema.pt;
24629 const mod = pt.zcu;
2439724630 const extra = sema.code.extraData(Zir.Inst.Select, extended.operand).data;
2439824631
2439924632 const src = block.nodeOffset(extra.node);
......@@ -24409,17 +24642,17 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2440924642
2441024643 const vec_len_u64 = switch (try pred_ty.zigTypeTagOrPoison(mod)) {
2441124644 .Vector, .Array => pred_ty.arrayLen(mod),
24412 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(mod)}),
24645 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(pt)}),
2441324646 };
2441424647 const vec_len: u32 = @intCast(try sema.usizeCast(block, pred_src, vec_len_u64));
2441524648
24416 const bool_vec_ty = try mod.vectorType(.{
24649 const bool_vec_ty = try pt.vectorType(.{
2441724650 .len = vec_len,
2441824651 .child = .bool_type,
2441924652 });
2442024653 const pred = try sema.coerce(block, bool_vec_ty, pred_uncoerced, pred_src);
2442124654
24422 const vec_ty = try mod.vectorType(.{
24655 const vec_ty = try pt.vectorType(.{
2442324656 .len = vec_len,
2442424657 .child = elem_ty.toIntern(),
2442524658 });
......@@ -24431,23 +24664,23 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2443124664 const maybe_b = try sema.resolveValue(b);
2443224665
2443324666 const runtime_src = if (maybe_pred) |pred_val| rs: {
24434 if (pred_val.isUndef(mod)) return mod.undefRef(vec_ty);
24667 if (pred_val.isUndef(mod)) return pt.undefRef(vec_ty);
2443524668
2443624669 if (maybe_a) |a_val| {
24437 if (a_val.isUndef(mod)) return mod.undefRef(vec_ty);
24670 if (a_val.isUndef(mod)) return pt.undefRef(vec_ty);
2443824671
2443924672 if (maybe_b) |b_val| {
24440 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24673 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2444124674
2444224675 const elems = try sema.gpa.alloc(InternPool.Index, vec_len);
2444324676 defer sema.gpa.free(elems);
2444424677 for (elems, 0..) |*elem, i| {
24445 const pred_elem_val = try pred_val.elemValue(mod, i);
24678 const pred_elem_val = try pred_val.elemValue(pt, i);
2444624679 const should_choose_a = pred_elem_val.toBool();
24447 elem.* = (try (if (should_choose_a) a_val else b_val).elemValue(mod, i)).toIntern();
24680 elem.* = (try (if (should_choose_a) a_val else b_val).elemValue(pt, i)).toIntern();
2444824681 }
2444924682
24450 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
24683 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2445124684 .ty = vec_ty.toIntern(),
2445224685 .storage = .{ .elems = elems },
2445324686 } })));
......@@ -24456,16 +24689,16 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2445624689 }
2445724690 } else {
2445824691 if (maybe_b) |b_val| {
24459 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24692 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446024693 }
2446124694 break :rs a_src;
2446224695 }
2446324696 } else rs: {
2446424697 if (maybe_a) |a_val| {
24465 if (a_val.isUndef(mod)) return mod.undefRef(vec_ty);
24698 if (a_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446624699 }
2446724700 if (maybe_b) |b_val| {
24468 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24701 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446924702 }
2447024703 break :rs pred_src;
2447124704 };
......@@ -24531,7 +24764,8 @@ fn zirAtomicLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2453124764}
2453224765
2453324766fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24534 const mod = sema.mod;
24767 const pt = sema.pt;
24768 const mod = pt.zcu;
2453524769 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2453624770 const extra = sema.code.extraData(Zir.Inst.AtomicRmw, inst_data.payload_index).data;
2453724771 const src = block.nodeOffset(inst_data.src_node);
......@@ -24588,12 +24822,12 @@ fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2458824822 .Xchg => operand_val,
2458924823 .Add => try sema.numberAddWrapScalar(stored_val, operand_val, elem_ty),
2459024824 .Sub => try sema.numberSubWrapScalar(stored_val, operand_val, elem_ty),
24591 .And => try stored_val.bitwiseAnd (operand_val, elem_ty, sema.arena, mod),
24592 .Nand => try stored_val.bitwiseNand (operand_val, elem_ty, sema.arena, mod),
24593 .Or => try stored_val.bitwiseOr (operand_val, elem_ty, sema.arena, mod),
24594 .Xor => try stored_val.bitwiseXor (operand_val, elem_ty, sema.arena, mod),
24595 .Max => stored_val.numberMax (operand_val, mod),
24596 .Min => stored_val.numberMin (operand_val, mod),
24825 .And => try stored_val.bitwiseAnd (operand_val, elem_ty, sema.arena, pt),
24826 .Nand => try stored_val.bitwiseNand (operand_val, elem_ty, sema.arena, pt),
24827 .Or => try stored_val.bitwiseOr (operand_val, elem_ty, sema.arena, pt),
24828 .Xor => try stored_val.bitwiseXor (operand_val, elem_ty, sema.arena, pt),
24829 .Max => stored_val.numberMax (operand_val, pt),
24830 .Min => stored_val.numberMin (operand_val, pt),
2459724831 // zig fmt: on
2459824832 };
2459924833 try sema.storePtrVal(block, src, ptr_val, new_val, elem_ty);
......@@ -24669,36 +24903,37 @@ fn zirMulAdd(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2466924903 const maybe_mulend1 = try sema.resolveValue(mulend1);
2467024904 const maybe_mulend2 = try sema.resolveValue(mulend2);
2467124905 const maybe_addend = try sema.resolveValue(addend);
24672 const mod = sema.mod;
24906 const pt = sema.pt;
24907 const mod = pt.zcu;
2467324908
2467424909 switch (ty.scalarType(mod).zigTypeTag(mod)) {
2467524910 .ComptimeFloat, .Float => {},
24676 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(sema.mod)}),
24911 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(pt)}),
2467724912 }
2467824913
2467924914 const runtime_src = if (maybe_mulend1) |mulend1_val| rs: {
2468024915 if (maybe_mulend2) |mulend2_val| {
24681 if (mulend2_val.isUndef(mod)) return mod.undefRef(ty);
24916 if (mulend2_val.isUndef(mod)) return pt.undefRef(ty);
2468224917
2468324918 if (maybe_addend) |addend_val| {
24684 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24685 const result_val = try Value.mulAdd(ty, mulend1_val, mulend2_val, addend_val, sema.arena, sema.mod);
24919 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
24920 const result_val = try Value.mulAdd(ty, mulend1_val, mulend2_val, addend_val, sema.arena, pt);
2468624921 return Air.internedToRef(result_val.toIntern());
2468724922 } else {
2468824923 break :rs addend_src;
2468924924 }
2469024925 } else {
2469124926 if (maybe_addend) |addend_val| {
24692 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24927 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
2469324928 }
2469424929 break :rs mulend2_src;
2469524930 }
2469624931 } else rs: {
2469724932 if (maybe_mulend2) |mulend2_val| {
24698 if (mulend2_val.isUndef(mod)) return mod.undefRef(ty);
24933 if (mulend2_val.isUndef(mod)) return pt.undefRef(ty);
2469924934 }
2470024935 if (maybe_addend) |addend_val| {
24701 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24936 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
2470224937 }
2470324938 break :rs mulend1_src;
2470424939 };
......@@ -24720,7 +24955,8 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2472024955 const tracy = trace(@src());
2472124956 defer tracy.end();
2472224957
24723 const mod = sema.mod;
24958 const pt = sema.pt;
24959 const mod = pt.zcu;
2472424960 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2472524961 const modifier_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2472624962 const func_src = block.builtinCallArgSrc(inst_data.src_node, 1);
......@@ -24730,7 +24966,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2473024966 const extra = sema.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;
2473124967 const func = try sema.resolveInst(extra.callee);
2473224968
24733 const modifier_ty = try mod.getBuiltinType("CallModifier");
24969 const modifier_ty = try pt.getBuiltinType("CallModifier");
2473424970 const air_ref = try sema.resolveInst(extra.modifier);
2473524971 const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);
2473624972 const modifier_val = try sema.resolveConstDefinedValue(block, modifier_src, modifier_ref, .{
......@@ -24783,7 +25019,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2478325019
2478425020 const args_ty = sema.typeOf(args);
2478525021 if (!args_ty.isTuple(mod) and args_ty.toIntern() != .empty_struct_type) {
24786 return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(sema.mod)});
25022 return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(pt)});
2478725023 }
2478825024
2478925025 const resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(mod));
......@@ -24812,7 +25048,8 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2481225048}
2481325049
2481425050fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
24815 const zcu = sema.mod;
25051 const pt = sema.pt;
25052 const zcu = pt.zcu;
2481625053 const ip = &zcu.intern_pool;
2481725054
2481825055 const extra = sema.code.extraData(Zir.Inst.FieldParentPtr, extended.operand).data;
......@@ -24827,14 +25064,14 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2482725064 try sema.checkPtrType(block, inst_src, parent_ptr_ty, true);
2482825065 const parent_ptr_info = parent_ptr_ty.ptrInfo(zcu);
2482925066 if (parent_ptr_info.flags.size != .One) {
24830 return sema.fail(block, inst_src, "expected single pointer type, found '{}'", .{parent_ptr_ty.fmt(zcu)});
25067 return sema.fail(block, inst_src, "expected single pointer type, found '{}'", .{parent_ptr_ty.fmt(pt)});
2483125068 }
2483225069 const parent_ty = Type.fromInterned(parent_ptr_info.child);
2483325070 switch (parent_ty.zigTypeTag(zcu)) {
2483425071 .Struct, .Union => {},
24835 else => return sema.fail(block, inst_src, "expected pointer to struct or union type, found '{}'", .{parent_ptr_ty.fmt(zcu)}),
25072 else => return sema.fail(block, inst_src, "expected pointer to struct or union type, found '{}'", .{parent_ptr_ty.fmt(pt)}),
2483625073 }
24837 try parent_ty.resolveLayout(zcu);
25074 try parent_ty.resolveLayout(pt);
2483825075
2483925076 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{
2484025077 .needed_comptime_reason = "field name must be comptime-known",
......@@ -24865,7 +25102,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2486525102 var actual_parent_ptr_info: InternPool.Key.PtrType = .{
2486625103 .child = parent_ty.toIntern(),
2486725104 .flags = .{
24868 .alignment = try parent_ptr_ty.ptrAlignmentAdvanced(zcu, .sema),
25105 .alignment = try parent_ptr_ty.ptrAlignmentAdvanced(pt, .sema),
2486925106 .is_const = field_ptr_info.flags.is_const,
2487025107 .is_volatile = field_ptr_info.flags.is_volatile,
2487125108 .is_allowzero = field_ptr_info.flags.is_allowzero,
......@@ -24877,7 +25114,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2487725114 var actual_field_ptr_info: InternPool.Key.PtrType = .{
2487825115 .child = field_ty.toIntern(),
2487925116 .flags = .{
24880 .alignment = try field_ptr_ty.ptrAlignmentAdvanced(zcu, .sema),
25117 .alignment = try field_ptr_ty.ptrAlignmentAdvanced(pt, .sema),
2488125118 .is_const = field_ptr_info.flags.is_const,
2488225119 .is_volatile = field_ptr_info.flags.is_volatile,
2488325120 .is_allowzero = field_ptr_info.flags.is_allowzero,
......@@ -24888,13 +25125,13 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2488825125 switch (parent_ty.containerLayout(zcu)) {
2488925126 .auto => {
2489025127 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(
24891 if (zcu.typeToStruct(parent_ty)) |struct_obj| try zcu.structFieldAlignmentAdvanced(
25128 if (zcu.typeToStruct(parent_ty)) |struct_obj| try pt.structFieldAlignmentAdvanced(
2489225129 struct_obj.fieldAlign(ip, field_index),
2489325130 field_ty,
2489425131 struct_obj.layout,
2489525132 .sema,
2489625133 ) else if (zcu.typeToUnion(parent_ty)) |union_obj|
24897 try zcu.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema)
25134 try pt.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema)
2489825135 else
2489925136 actual_field_ptr_info.flags.alignment,
2490025137 );
......@@ -24903,7 +25140,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2490325140 actual_field_ptr_info.packed_offset = .{ .bit_offset = 0, .host_size = 0 };
2490425141 },
2490525142 .@"extern" => {
24906 const field_offset = parent_ty.structFieldOffset(field_index, zcu);
25143 const field_offset = parent_ty.structFieldOffset(field_index, pt);
2490725144 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(if (field_offset > 0)
2490825145 Alignment.fromLog2Units(@ctz(field_offset))
2490925146 else
......@@ -24914,7 +25151,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2491425151 },
2491525152 .@"packed" => {
2491625153 const byte_offset = std.math.divExact(u32, @abs(@as(i32, actual_parent_ptr_info.packed_offset.bit_offset) +
24917 (if (zcu.typeToStruct(parent_ty)) |struct_obj| zcu.structPackedFieldBitOffset(struct_obj, field_index) else 0) -
25154 (if (zcu.typeToStruct(parent_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, field_index) else 0) -
2491825155 actual_field_ptr_info.packed_offset.bit_offset), 8) catch
2491925156 return sema.fail(block, inst_src, "pointer bit-offset mismatch", .{});
2492025157 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(if (byte_offset > 0)
......@@ -24924,16 +25161,16 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2492425161 },
2492525162 }
2492625163
24927 const actual_field_ptr_ty = try zcu.ptrTypeSema(actual_field_ptr_info);
25164 const actual_field_ptr_ty = try pt.ptrTypeSema(actual_field_ptr_info);
2492825165 const casted_field_ptr = try sema.coerce(block, actual_field_ptr_ty, field_ptr, field_ptr_src);
24929 const actual_parent_ptr_ty = try zcu.ptrTypeSema(actual_parent_ptr_info);
25166 const actual_parent_ptr_ty = try pt.ptrTypeSema(actual_parent_ptr_info);
2493025167
2493125168 const result = if (try sema.resolveDefinedValue(block, field_ptr_src, casted_field_ptr)) |field_ptr_val| result: {
2493225169 switch (parent_ty.zigTypeTag(zcu)) {
2493325170 .Struct => switch (parent_ty.containerLayout(zcu)) {
2493425171 .auto => {},
2493525172 .@"extern" => {
24936 const byte_offset = parent_ty.structFieldOffset(field_index, zcu);
25173 const byte_offset = parent_ty.structFieldOffset(field_index, pt);
2493725174 const parent_ptr_val = try sema.ptrSubtract(block, field_ptr_src, field_ptr_val, byte_offset, actual_parent_ptr_ty);
2493825175 break :result Air.internedToRef(parent_ptr_val.toIntern());
2493925176 },
......@@ -24941,7 +25178,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2494125178 // Logic lifted from type computation above - I'm just assuming it's correct.
2494225179 // `catch unreachable` since error case handled above.
2494325180 const byte_offset = std.math.divExact(u32, @abs(@as(i32, actual_parent_ptr_info.packed_offset.bit_offset) +
24944 zcu.structPackedFieldBitOffset(zcu.typeToStruct(parent_ty).?, field_index) -
25181 pt.structPackedFieldBitOffset(zcu.typeToStruct(parent_ty).?, field_index) -
2494525182 actual_field_ptr_info.packed_offset.bit_offset), 8) catch unreachable;
2494625183 const parent_ptr_val = try sema.ptrSubtract(block, field_ptr_src, field_ptr_val, byte_offset, actual_parent_ptr_ty);
2494725184 break :result Air.internedToRef(parent_ptr_val.toIntern());
......@@ -24951,7 +25188,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2495125188 .auto => {},
2495225189 .@"extern", .@"packed" => {
2495325190 // For an extern or packed union, just coerce the pointer.
24954 const parent_ptr_val = try zcu.getCoerced(field_ptr_val, actual_parent_ptr_ty);
25191 const parent_ptr_val = try pt.getCoerced(field_ptr_val, actual_parent_ptr_ty);
2495525192 break :result Air.internedToRef(parent_ptr_val.toIntern());
2495625193 },
2495725194 },
......@@ -24980,7 +25217,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2498025217
2498125218 if (field.index != field_index) {
2498225219 return sema.fail(block, inst_src, "field '{}' has index '{d}' but pointer value is index '{d}' of struct '{}'", .{
24983 field_name.fmt(ip), field_index, field.index, parent_ty.fmt(zcu),
25220 field_name.fmt(ip), field_index, field.index, parent_ty.fmt(pt),
2498425221 });
2498525222 }
2498625223 break :result try sema.coerce(block, actual_parent_ptr_ty, Air.internedToRef(field.base), inst_src);
......@@ -25001,8 +25238,9 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2500125238}
2500225239
2500325240fn ptrSubtract(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, byte_subtract: u64, new_ty: Type) !Value {
25004 const zcu = sema.mod;
25005 if (byte_subtract == 0) return zcu.getCoerced(ptr_val, new_ty);
25241 const pt = sema.pt;
25242 const zcu = pt.zcu;
25243 if (byte_subtract == 0) return pt.getCoerced(ptr_val, new_ty);
2500625244 var ptr = switch (zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
2500725245 .undef => return sema.failWithUseOfUndef(block, src),
2500825246 .ptr => |ptr| ptr,
......@@ -25018,7 +25256,7 @@ fn ptrSubtract(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, byte
2501825256 }
2501925257 ptr.byte_offset -= byte_subtract;
2502025258 ptr.ty = new_ty.toIntern();
25021 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr }));
25259 return Value.fromInterned(try pt.intern(.{ .ptr = ptr }));
2502225260}
2502325261
2502425262fn zirMinMax(
......@@ -25072,7 +25310,8 @@ fn analyzeMinMax(
2507225310) CompileError!Air.Inst.Ref {
2507325311 assert(operands.len == operand_srcs.len);
2507425312 assert(operands.len > 0);
25075 const mod = sema.mod;
25313 const pt = sema.pt;
25314 const mod = pt.zcu;
2507625315
2507725316 if (operands.len == 1) return operands[0];
2507825317
......@@ -25115,15 +25354,15 @@ fn analyzeMinMax(
2511525354 break :refine_bounds;
2511625355 }
2511725356 const scalar_bounds: ?[2]Value = bounds: {
25118 if (!ty.isVector(mod)) break :bounds try uncoerced_val.intValueBounds(mod);
25119 var cur_bounds: [2]Value = try Value.intValueBounds(try uncoerced_val.elemValue(mod, 0), mod) orelse break :bounds null;
25357 if (!ty.isVector(mod)) break :bounds try uncoerced_val.intValueBounds(pt);
25358 var cur_bounds: [2]Value = try Value.intValueBounds(try uncoerced_val.elemValue(pt, 0), pt) orelse break :bounds null;
2512025359 const len = try sema.usizeCast(block, src, ty.vectorLen(mod));
2512125360 for (1..len) |i| {
25122 const elem = try uncoerced_val.elemValue(mod, i);
25123 const elem_bounds = try elem.intValueBounds(mod) orelse break :bounds null;
25361 const elem = try uncoerced_val.elemValue(pt, i);
25362 const elem_bounds = try elem.intValueBounds(pt) orelse break :bounds null;
2512425363 cur_bounds = .{
25125 Value.numberMin(elem_bounds[0], cur_bounds[0], mod),
25126 Value.numberMax(elem_bounds[1], cur_bounds[1], mod),
25364 Value.numberMin(elem_bounds[0], cur_bounds[0], pt),
25365 Value.numberMax(elem_bounds[1], cur_bounds[1], pt),
2512725366 };
2512825367 }
2512925368 break :bounds cur_bounds;
......@@ -25134,8 +25373,8 @@ fn analyzeMinMax(
2513425373 cur_max_scalar = bounds[1];
2513525374 bounds_status = .defined;
2513625375 } else {
25137 cur_min_scalar = opFunc(cur_min_scalar, bounds[0], mod);
25138 cur_max_scalar = opFunc(cur_max_scalar, bounds[1], mod);
25376 cur_min_scalar = opFunc(cur_min_scalar, bounds[0], pt);
25377 cur_max_scalar = opFunc(cur_max_scalar, bounds[1], pt);
2513925378 }
2514025379 }
2514125380 },
......@@ -25153,18 +25392,18 @@ fn analyzeMinMax(
2515325392 const operand_val = try sema.resolveLazyValue(simd_op.rhs_val.?); // we checked the operand was resolvable above
2515425393
2515525394 const vec_len = simd_op.len orelse {
25156 const result_val = opFunc(cur_val, operand_val, mod);
25395 const result_val = opFunc(cur_val, operand_val, pt);
2515725396 cur_minmax = Air.internedToRef(result_val.toIntern());
2515825397 continue;
2515925398 };
2516025399 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2516125400 for (elems, 0..) |*elem, i| {
25162 const lhs_elem_val = try cur_val.elemValue(mod, i);
25163 const rhs_elem_val = try operand_val.elemValue(mod, i);
25164 const uncoerced_elem = opFunc(lhs_elem_val, rhs_elem_val, mod);
25165 elem.* = (try mod.getCoerced(uncoerced_elem, simd_op.scalar_ty)).toIntern();
25401 const lhs_elem_val = try cur_val.elemValue(pt, i);
25402 const rhs_elem_val = try operand_val.elemValue(pt, i);
25403 const uncoerced_elem = opFunc(lhs_elem_val, rhs_elem_val, pt);
25404 elem.* = (try pt.getCoerced(uncoerced_elem, simd_op.scalar_ty)).toIntern();
2516625405 }
25167 cur_minmax = Air.internedToRef((try mod.intern(.{ .aggregate = .{
25406 cur_minmax = Air.internedToRef((try pt.intern(.{ .aggregate = .{
2516825407 .ty = simd_op.result_ty.toIntern(),
2516925408 .storage = .{ .elems = elems },
2517025409 } })));
......@@ -25191,8 +25430,8 @@ fn analyzeMinMax(
2519125430
2519225431 assert(bounds_status == .defined); // there was a non-comptime-int integral comptime-known arg
2519325432
25194 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
25195 const refined_ty = if (orig_ty.isVector(mod)) try mod.vectorType(.{
25433 const refined_scalar_ty = try pt.intFittingRange(cur_min_scalar, cur_max_scalar);
25434 const refined_ty = if (orig_ty.isVector(mod)) try pt.vectorType(.{
2519625435 .len = orig_ty.vectorLen(mod),
2519725436 .child = refined_scalar_ty.toIntern(),
2519825437 }) else refined_scalar_ty;
......@@ -25226,8 +25465,8 @@ fn analyzeMinMax(
2522625465 runtime_known.unset(0); // don't look at this operand in the loop below
2522725466 const scalar_ty = sema.typeOf(cur_minmax.?).scalarType(mod);
2522825467 if (scalar_ty.isInt(mod)) {
25229 cur_min_scalar = try scalar_ty.minInt(mod, scalar_ty);
25230 cur_max_scalar = try scalar_ty.maxInt(mod, scalar_ty);
25468 cur_min_scalar = try scalar_ty.minInt(pt, scalar_ty);
25469 cur_max_scalar = try scalar_ty.maxInt(pt, scalar_ty);
2523125470 bounds_status = .defined;
2523225471 } else {
2523325472 bounds_status = .non_integral;
......@@ -25242,7 +25481,7 @@ fn analyzeMinMax(
2524225481 const rhs_src = operand_srcs[idx];
2524325482 const simd_op = try sema.checkSimdBinOp(block, src, lhs, rhs, lhs_src, rhs_src);
2524425483 if (known_undef) {
25245 cur_minmax = try mod.undefRef(simd_op.result_ty);
25484 cur_minmax = try pt.undefRef(simd_op.result_ty);
2524625485 } else {
2524725486 cur_minmax = try block.addBinOp(air_tag, simd_op.lhs, simd_op.rhs);
2524825487 }
......@@ -25254,15 +25493,15 @@ fn analyzeMinMax(
2525425493 bounds_status = .non_integral;
2525525494 break :refine_bounds;
2525625495 }
25257 const scalar_min = try scalar_ty.minInt(mod, scalar_ty);
25258 const scalar_max = try scalar_ty.maxInt(mod, scalar_ty);
25496 const scalar_min = try scalar_ty.minInt(pt, scalar_ty);
25497 const scalar_max = try scalar_ty.maxInt(pt, scalar_ty);
2525925498 if (bounds_status == .unknown) {
2526025499 cur_min_scalar = scalar_min;
2526125500 cur_max_scalar = scalar_max;
2526225501 bounds_status = .defined;
2526325502 } else {
25264 cur_min_scalar = opFunc(cur_min_scalar, scalar_min, mod);
25265 cur_max_scalar = opFunc(cur_max_scalar, scalar_max, mod);
25503 cur_min_scalar = opFunc(cur_min_scalar, scalar_min, pt);
25504 cur_max_scalar = opFunc(cur_max_scalar, scalar_max, pt);
2526625505 }
2526725506 },
2526825507 .non_integral => {},
......@@ -25276,8 +25515,8 @@ fn analyzeMinMax(
2527625515 return cur_minmax.?;
2527725516 }
2527825517 assert(bounds_status == .defined); // there were integral runtime operands
25279 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
25280 const refined_ty = if (unrefined_ty.isVector(mod)) try mod.vectorType(.{
25518 const refined_scalar_ty = try pt.intFittingRange(cur_min_scalar, cur_max_scalar);
25519 const refined_ty = if (unrefined_ty.isVector(mod)) try pt.vectorType(.{
2528125520 .len = unrefined_ty.vectorLen(mod),
2528225521 .child = refined_scalar_ty.toIntern(),
2528325522 }) else refined_scalar_ty;
......@@ -25291,15 +25530,16 @@ fn analyzeMinMax(
2529125530}
2529225531
2529325532fn upgradeToArrayPtr(sema: *Sema, block: *Block, ptr: Air.Inst.Ref, len: u64) !Air.Inst.Ref {
25294 const mod = sema.mod;
25533 const pt = sema.pt;
25534 const mod = pt.zcu;
2529525535 const ptr_ty = sema.typeOf(ptr);
2529625536 const info = ptr_ty.ptrInfo(mod);
2529725537 if (info.flags.size == .One) {
2529825538 // Already an array pointer.
2529925539 return ptr;
2530025540 }
25301 const new_ty = try mod.ptrTypeSema(.{
25302 .child = (try mod.arrayType(.{
25541 const new_ty = try pt.ptrTypeSema(.{
25542 .child = (try pt.arrayType(.{
2530325543 .len = len,
2530425544 .sentinel = info.sentinel,
2530525545 .child = info.child,
......@@ -25331,8 +25571,9 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2533125571 const src_ty = sema.typeOf(src_ptr);
2533225572 const dest_len = try indexablePtrLenOrNone(sema, block, dest_src, dest_ptr);
2533325573 const src_len = try indexablePtrLenOrNone(sema, block, src_src, src_ptr);
25334 const target = sema.mod.getTarget();
25335 const mod = sema.mod;
25574 const pt = sema.pt;
25575 const mod = pt.zcu;
25576 const target = mod.getTarget();
2533625577
2533725578 if (dest_ty.isConstPtr(mod)) {
2533825579 return sema.fail(block, dest_src, "cannot memcpy to constant pointer", .{});
......@@ -25343,10 +25584,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2534325584 const msg = try sema.errMsg(src, "unknown @memcpy length", .{});
2534425585 errdefer msg.destroy(sema.gpa);
2534525586 try sema.errNote(dest_src, msg, "destination type '{}' provides no length", .{
25346 dest_ty.fmt(sema.mod),
25587 dest_ty.fmt(pt),
2534725588 });
2534825589 try sema.errNote(src_src, msg, "source type '{}' provides no length", .{
25349 src_ty.fmt(sema.mod),
25590 src_ty.fmt(pt),
2535025591 });
2535125592 break :msg msg;
2535225593 };
......@@ -25365,10 +25606,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2536525606 const msg = try sema.errMsg(src, "non-matching @memcpy lengths", .{});
2536625607 errdefer msg.destroy(sema.gpa);
2536725608 try sema.errNote(dest_src, msg, "length {} here", .{
25368 dest_len_val.fmtValue(sema.mod, sema),
25609 dest_len_val.fmtValue(pt, sema),
2536925610 });
2537025611 try sema.errNote(src_src, msg, "length {} here", .{
25371 src_len_val.fmtValue(sema.mod, sema),
25612 src_len_val.fmtValue(pt, sema),
2537225613 });
2537325614 break :msg msg;
2537425615 };
......@@ -25397,10 +25638,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2539725638 const runtime_src = if (try sema.resolveDefinedValue(block, dest_src, dest_ptr)) |dest_ptr_val| rs: {
2539825639 if (!sema.isComptimeMutablePtr(dest_ptr_val)) break :rs dest_src;
2539925640 if (try sema.resolveDefinedValue(block, src_src, src_ptr)) |_| {
25400 const len_u64 = (try len_val.?.getUnsignedIntAdvanced(mod, .sema)).?;
25641 const len_u64 = (try len_val.?.getUnsignedIntAdvanced(pt, .sema)).?;
2540125642 const len = try sema.usizeCast(block, dest_src, len_u64);
2540225643 for (0..len) |i| {
25403 const elem_index = try mod.intRef(Type.usize, i);
25644 const elem_index = try pt.intRef(Type.usize, i);
2540425645 const dest_elem_ptr = try sema.elemPtrOneLayerOnly(
2540525646 block,
2540625647 src,
......@@ -25456,7 +25697,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2545625697 var new_dest_ptr = dest_ptr;
2545725698 var new_src_ptr = src_ptr;
2545825699 if (len_val) |val| {
25459 const len = try val.toUnsignedIntSema(mod);
25700 const len = try val.toUnsignedIntSema(pt);
2546025701 if (len == 0) {
2546125702 // This AIR instruction guarantees length > 0 if it is comptime-known.
2546225703 return;
......@@ -25503,7 +25744,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2550325744 assert(dest_manyptr_ty_key.flags.size == .One);
2550425745 dest_manyptr_ty_key.child = dest_elem_ty.toIntern();
2550525746 dest_manyptr_ty_key.flags.size = .Many;
25506 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(dest_manyptr_ty_key), new_dest_ptr, dest_src);
25747 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(dest_manyptr_ty_key), new_dest_ptr, dest_src);
2550725748 } else new_dest_ptr;
2550825749
2550925750 const new_src_ptr_ty = sema.typeOf(new_src_ptr);
......@@ -25514,7 +25755,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2551425755 assert(src_manyptr_ty_key.flags.size == .One);
2551525756 src_manyptr_ty_key.child = src_elem_ty.toIntern();
2551625757 src_manyptr_ty_key.flags.size = .Many;
25517 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(src_manyptr_ty_key), new_src_ptr, src_src);
25758 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(src_manyptr_ty_key), new_src_ptr, src_src);
2551825759 } else new_src_ptr;
2551925760
2552025761 // ok1: dest >= src + len
......@@ -25537,7 +25778,8 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2553725778}
2553825779
2553925780fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
25540 const mod = sema.mod;
25781 const pt = sema.pt;
25782 const mod = pt.zcu;
2554125783 const gpa = sema.gpa;
2554225784 const ip = &mod.intern_pool;
2554325785 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -25569,7 +25811,7 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2556925811 const msg = try sema.errMsg(src, "unknown @memset length", .{});
2557025812 errdefer msg.destroy(sema.gpa);
2557125813 try sema.errNote(dest_src, msg, "destination type '{}' provides no length", .{
25572 dest_ptr_ty.fmt(mod),
25814 dest_ptr_ty.fmt(pt),
2557325815 });
2557425816 break :msg msg;
2557525817 });
......@@ -25581,7 +25823,7 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2558125823 const ptr_val = try sema.resolveDefinedValue(block, dest_src, dest_ptr) orelse break :rs dest_src;
2558225824 const len_air_ref = try sema.fieldVal(block, src, dest_ptr, try ip.getOrPutString(gpa, "len", .no_embedded_nulls), dest_src);
2558325825 const len_val = (try sema.resolveDefinedValue(block, dest_src, len_air_ref)) orelse break :rs dest_src;
25584 const len_u64 = (try len_val.getUnsignedIntAdvanced(mod, .sema)).?;
25826 const len_u64 = (try len_val.getUnsignedIntAdvanced(pt, .sema)).?;
2558525827 const len = try sema.usizeCast(block, dest_src, len_u64);
2558625828 if (len == 0) {
2558725829 // This AIR instruction guarantees length > 0 if it is comptime-known.
......@@ -25590,22 +25832,22 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2559025832
2559125833 if (!sema.isComptimeMutablePtr(ptr_val)) break :rs dest_src;
2559225834 const elem_val = try sema.resolveValue(elem) orelse break :rs value_src;
25593 const array_ty = try mod.arrayType(.{
25835 const array_ty = try pt.arrayType(.{
2559425836 .child = dest_elem_ty.toIntern(),
2559525837 .len = len_u64,
2559625838 });
25597 const array_val = Value.fromInterned((try mod.intern(.{ .aggregate = .{
25839 const array_val = Value.fromInterned(try pt.intern(.{ .aggregate = .{
2559825840 .ty = array_ty.toIntern(),
2559925841 .storage = .{ .repeated_elem = elem_val.toIntern() },
25600 } })));
25842 } }));
2560125843 const array_ptr_ty = ty: {
2560225844 var info = dest_ptr_ty.ptrInfo(mod);
2560325845 info.flags.size = .One;
2560425846 info.child = array_ty.toIntern();
25605 break :ty try mod.ptrType(info);
25847 break :ty try pt.ptrType(info);
2560625848 };
2560725849 const raw_ptr_val = if (dest_ptr_ty.isSlice(mod)) ptr_val.slicePtr(mod) else ptr_val;
25608 const array_ptr_val = try mod.getCoerced(raw_ptr_val, array_ptr_ty);
25850 const array_ptr_val = try pt.getCoerced(raw_ptr_val, array_ptr_ty);
2560925851 return sema.storePtrVal(block, src, array_ptr_val, array_val, array_ty);
2561025852 };
2561125853
......@@ -25658,7 +25900,8 @@ fn zirVarExtended(
2565825900 block: *Block,
2565925901 extended: Zir.Inst.Extended.InstData,
2566025902) CompileError!Air.Inst.Ref {
25661 const mod = sema.mod;
25903 const pt = sema.pt;
25904 const mod = pt.zcu;
2566225905 const extra = sema.code.extraData(Zir.Inst.ExtendedVar, extended.operand);
2566325906 const ty_src = block.src(.{ .node_offset_var_decl_ty = 0 });
2566425907 const init_src = block.src(.{ .node_offset_var_decl_init = 0 });
......@@ -25705,7 +25948,7 @@ fn zirVarExtended(
2570525948
2570625949 try sema.validateVarType(block, ty_src, var_ty, small.is_extern);
2570725950
25708 return Air.internedToRef((try mod.intern(.{ .variable = .{
25951 return Air.internedToRef((try pt.intern(.{ .variable = .{
2570925952 .ty = var_ty.toIntern(),
2571025953 .init = init_val,
2571125954 .decl = sema.owner_decl_index,
......@@ -25721,7 +25964,8 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2572125964 const tracy = trace(@src());
2572225965 defer tracy.end();
2572325966
25724 const mod = sema.mod;
25967 const pt = sema.pt;
25968 const mod = pt.zcu;
2572525969 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2572625970 const extra = sema.code.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);
2572725971 const target = mod.getTarget();
......@@ -25761,7 +26005,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2576126005 if (val.isGenericPoison()) {
2576226006 break :blk null;
2576326007 }
25764 const alignment = try sema.validateAlignAllowZero(block, align_src, try val.toUnsignedIntSema(mod));
26008 const alignment = try sema.validateAlignAllowZero(block, align_src, try val.toUnsignedIntSema(pt));
2576526009 const default = target_util.defaultFunctionAlignment(target);
2576626010 break :blk if (alignment == default) .none else alignment;
2576726011 } else if (extra.data.bits.has_align_ref) blk: {
......@@ -25781,7 +26025,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2578126025 error.GenericPoison => break :blk null,
2578226026 else => |e| return e,
2578326027 };
25784 const alignment = try sema.validateAlignAllowZero(block, align_src, try align_val.toUnsignedIntSema(mod));
26028 const alignment = try sema.validateAlignAllowZero(block, align_src, try align_val.toUnsignedIntSema(pt));
2578526029 const default = target_util.defaultFunctionAlignment(target);
2578626030 break :blk if (alignment == default) .none else alignment;
2578726031 } else .none;
......@@ -25857,7 +26101,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2585726101 const body = sema.code.bodySlice(extra_index, body_len);
2585826102 extra_index += body.len;
2585926103
25860 const cc_ty = try mod.getBuiltinType("CallingConvention");
26104 const cc_ty = try pt.getBuiltinType("CallingConvention");
2586126105 const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, .{
2586226106 .needed_comptime_reason = "calling convention must be comptime-known",
2586326107 });
......@@ -25986,7 +26230,8 @@ fn zirCDefine(
2598626230 block: *Block,
2598726231 extended: Zir.Inst.Extended.InstData,
2598826232) CompileError!Air.Inst.Ref {
25989 const mod = sema.mod;
26233 const pt = sema.pt;
26234 const mod = pt.zcu;
2599026235 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2599126236 const name_src = block.builtinCallArgSrc(extra.node, 0);
2599226237 const val_src = block.builtinCallArgSrc(extra.node, 1);
......@@ -26014,7 +26259,7 @@ fn zirWasmMemorySize(
2601426259 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
2601526260 const index_src = block.builtinCallArgSrc(extra.node, 0);
2601626261 const builtin_src = block.nodeOffset(extra.node);
26017 const target = sema.mod.getTarget();
26262 const target = sema.pt.zcu.getTarget();
2601826263 if (!target.isWasm()) {
2601926264 return sema.fail(block, builtin_src, "builtin @wasmMemorySize is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
2602026265 }
......@@ -26041,7 +26286,7 @@ fn zirWasmMemoryGrow(
2604126286 const builtin_src = block.nodeOffset(extra.node);
2604226287 const index_src = block.builtinCallArgSrc(extra.node, 0);
2604326288 const delta_src = block.builtinCallArgSrc(extra.node, 1);
26044 const target = sema.mod.getTarget();
26289 const target = sema.pt.zcu.getTarget();
2604526290 if (!target.isWasm()) {
2604626291 return sema.fail(block, builtin_src, "builtin @wasmMemoryGrow is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
2604726292 }
......@@ -26067,10 +26312,11 @@ fn resolvePrefetchOptions(
2606726312 src: LazySrcLoc,
2606826313 zir_ref: Zir.Inst.Ref,
2606926314) CompileError!std.builtin.PrefetchOptions {
26070 const mod = sema.mod;
26315 const pt = sema.pt;
26316 const mod = pt.zcu;
2607126317 const gpa = sema.gpa;
2607226318 const ip = &mod.intern_pool;
26073 const options_ty = try mod.getBuiltinType("PrefetchOptions");
26319 const options_ty = try pt.getBuiltinType("PrefetchOptions");
2607426320 const options = try sema.coerce(block, options_ty, try sema.resolveInst(zir_ref), src);
2607526321
2607626322 const rw_src = block.src(.{ .init_field_rw = src.offset.node_offset_builtin_call_arg.builtin_call_node });
......@@ -26094,7 +26340,7 @@ fn resolvePrefetchOptions(
2609426340
2609526341 return std.builtin.PrefetchOptions{
2609626342 .rw = mod.toEnum(std.builtin.PrefetchOptions.Rw, rw_val),
26097 .locality = @intCast(try locality_val.toUnsignedIntSema(mod)),
26343 .locality = @intCast(try locality_val.toUnsignedIntSema(pt)),
2609826344 .cache = mod.toEnum(std.builtin.PrefetchOptions.Cache, cache_val),
2609926345 };
2610026346}
......@@ -26138,11 +26384,12 @@ fn resolveExternOptions(
2613826384 linkage: std.builtin.GlobalLinkage = .strong,
2613926385 is_thread_local: bool = false,
2614026386} {
26141 const mod = sema.mod;
26387 const pt = sema.pt;
26388 const mod = pt.zcu;
2614226389 const gpa = sema.gpa;
2614326390 const ip = &mod.intern_pool;
2614426391 const options_inst = try sema.resolveInst(zir_ref);
26145 const extern_options_ty = try mod.getBuiltinType("ExternOptions");
26392 const extern_options_ty = try pt.getBuiltinType("ExternOptions");
2614626393 const options = try sema.coerce(block, extern_options_ty, options_inst, src);
2614726394
2614826395 const name_src = block.src(.{ .init_field_name = src.offset.node_offset_builtin_call_arg.builtin_call_node });
......@@ -26203,7 +26450,8 @@ fn zirBuiltinExtern(
2620326450 block: *Block,
2620426451 extended: Zir.Inst.Extended.InstData,
2620526452) CompileError!Air.Inst.Ref {
26206 const mod = sema.mod;
26453 const pt = sema.pt;
26454 const mod = pt.zcu;
2620726455 const ip = &mod.intern_pool;
2620826456 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2620926457 const ty_src = block.builtinCallArgSrc(extra.node, 0);
......@@ -26215,7 +26463,7 @@ fn zirBuiltinExtern(
2621526463 }
2621626464 if (!try sema.validateExternType(ty, .other)) {
2621726465 const msg = msg: {
26218 const msg = try sema.errMsg(ty_src, "extern symbol cannot have type '{}'", .{ty.fmt(mod)});
26466 const msg = try sema.errMsg(ty_src, "extern symbol cannot have type '{}'", .{ty.fmt(pt)});
2621926467 errdefer msg.destroy(sema.gpa);
2622026468 try sema.explainWhyTypeIsNotExtern(msg, ty_src, ty, .other);
2622126469 break :msg msg;
......@@ -26226,7 +26474,7 @@ fn zirBuiltinExtern(
2622626474 const options = try sema.resolveExternOptions(block, options_src, extra.rhs);
2622726475
2622826476 if (options.linkage == .weak and !ty.ptrAllowsZero(mod)) {
26229 ty = try mod.optionalType(ty.toIntern());
26477 ty = try pt.optionalType(ty.toIntern());
2623026478 }
2623126479 const ptr_info = ty.ptrInfo(mod);
2623226480
......@@ -26237,13 +26485,13 @@ fn zirBuiltinExtern(
2623726485 new_decl_index,
2623826486 Value.fromInterned(
2623926487 if (Type.fromInterned(ptr_info.child).zigTypeTag(mod) == .Fn)
26240 try ip.getExternFunc(sema.gpa, .{
26488 try ip.getExternFunc(sema.gpa, pt.tid, .{
2624126489 .ty = ptr_info.child,
2624226490 .decl = new_decl_index,
2624326491 .lib_name = options.library_name,
2624426492 })
2624526493 else
26246 try mod.intern(.{ .variable = .{
26494 try pt.intern(.{ .variable = .{
2624726495 .ty = ptr_info.child,
2624826496 .init = .none,
2624926497 .decl = new_decl_index,
......@@ -26259,9 +26507,9 @@ fn zirBuiltinExtern(
2625926507 new_decl.owns_tv = true;
2626026508 // Note that this will queue the anon decl for codegen, so that the backend can
2626126509 // correctly handle the extern, including duplicate detection.
26262 try mod.finalizeAnonDecl(new_decl_index);
26510 try pt.finalizeAnonDecl(new_decl_index);
2626326511
26264 return Air.internedToRef((try mod.getCoerced(Value.fromInterned((try mod.intern(.{ .ptr = .{
26512 return Air.internedToRef((try pt.getCoerced(Value.fromInterned(try pt.intern(.{ .ptr = .{
2626526513 .ty = switch (ip.indexToKey(ty.toIntern())) {
2626626514 .ptr_type => ty.toIntern(),
2626726515 .opt_type => |child_type| child_type,
......@@ -26269,7 +26517,7 @@ fn zirBuiltinExtern(
2626926517 },
2627026518 .base_addr = .{ .decl = new_decl_index },
2627126519 .byte_offset = 0,
26272 } }))), ty)).toIntern());
26520 } })), ty)).toIntern());
2627326521}
2627426522
2627526523fn zirWorkItem(
......@@ -26281,7 +26529,7 @@ fn zirWorkItem(
2628126529 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
2628226530 const dimension_src = block.builtinCallArgSrc(extra.node, 0);
2628326531 const builtin_src = block.nodeOffset(extra.node);
26284 const target = sema.mod.getTarget();
26532 const target = sema.pt.zcu.getTarget();
2628526533
2628626534 switch (target.cpu.arch) {
2628726535 // TODO: Allow for other GPU targets.
......@@ -26344,11 +26592,12 @@ fn validateVarType(
2634426592 var_ty: Type,
2634526593 is_extern: bool,
2634626594) CompileError!void {
26347 const mod = sema.mod;
26595 const pt = sema.pt;
26596 const mod = pt.zcu;
2634826597 if (is_extern) {
2634926598 if (!try sema.validateExternType(var_ty, .other)) {
2635026599 const msg = msg: {
26351 const msg = try sema.errMsg(src, "extern variable cannot have type '{}'", .{var_ty.fmt(mod)});
26600 const msg = try sema.errMsg(src, "extern variable cannot have type '{}'", .{var_ty.fmt(pt)});
2635226601 errdefer msg.destroy(sema.gpa);
2635326602 try sema.explainWhyTypeIsNotExtern(msg, src, var_ty, .other);
2635426603 break :msg msg;
......@@ -26361,7 +26610,7 @@ fn validateVarType(
2636126610 block,
2636226611 src,
2636326612 "non-extern variable with opaque type '{}'",
26364 .{var_ty.fmt(mod)},
26613 .{var_ty.fmt(pt)},
2636526614 );
2636626615 }
2636726616 }
......@@ -26369,7 +26618,7 @@ fn validateVarType(
2636926618 if (!try sema.typeRequiresComptime(var_ty)) return;
2637026619
2637126620 const msg = msg: {
26372 const msg = try sema.errMsg(src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(mod)});
26621 const msg = try sema.errMsg(src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(pt)});
2637326622 errdefer msg.destroy(sema.gpa);
2637426623
2637526624 try sema.explainWhyTypeIsComptime(msg, src, var_ty);
......@@ -26393,7 +26642,7 @@ fn explainWhyTypeIsComptime(
2639326642 var type_set = TypeSet{};
2639426643 defer type_set.deinit(sema.gpa);
2639526644
26396 try ty.resolveFully(sema.mod);
26645 try ty.resolveFully(sema.pt);
2639726646 return sema.explainWhyTypeIsComptimeInner(msg, src_loc, ty, &type_set);
2639826647}
2639926648
......@@ -26404,7 +26653,8 @@ fn explainWhyTypeIsComptimeInner(
2640426653 ty: Type,
2640526654 type_set: *TypeSet,
2640626655) CompileError!void {
26407 const mod = sema.mod;
26656 const pt = sema.pt;
26657 const mod = pt.zcu;
2640826658 const ip = &mod.intern_pool;
2640926659 switch (ty.zigTypeTag(mod)) {
2641026660 .Bool,
......@@ -26418,9 +26668,7 @@ fn explainWhyTypeIsComptimeInner(
2641826668 => return,
2641926669
2642026670 .Fn => {
26421 try sema.errNote(src_loc, msg, "use '*const {}' for a function pointer type", .{
26422 ty.fmt(sema.mod),
26423 });
26671 try sema.errNote(src_loc, msg, "use '*const {}' for a function pointer type", .{ty.fmt(pt)});
2642426672 },
2642526673
2642626674 .Type => {
......@@ -26436,7 +26684,7 @@ fn explainWhyTypeIsComptimeInner(
2643626684 => return,
2643726685
2643826686 .Opaque => {
26439 try sema.errNote(src_loc, msg, "opaque type '{}' has undefined size", .{ty.fmt(sema.mod)});
26687 try sema.errNote(src_loc, msg, "opaque type '{}' has undefined size", .{ty.fmt(pt)});
2644026688 },
2644126689
2644226690 .Array, .Vector => {
......@@ -26453,7 +26701,7 @@ fn explainWhyTypeIsComptimeInner(
2645326701 .Inline => try sema.errNote(src_loc, msg, "function has inline calling convention", .{}),
2645426702 else => {},
2645526703 }
26456 if (Type.fromInterned(fn_info.return_type).comptimeOnly(mod)) {
26704 if (Type.fromInterned(fn_info.return_type).comptimeOnly(pt)) {
2645726705 try sema.errNote(src_loc, msg, "function has a comptime-only return type", .{});
2645826706 }
2645926707 return;
......@@ -26526,7 +26774,8 @@ fn validateExternType(
2652626774 ty: Type,
2652726775 position: ExternPosition,
2652826776) !bool {
26529 const mod = sema.mod;
26777 const pt = sema.pt;
26778 const mod = pt.zcu;
2653026779 switch (ty.zigTypeTag(mod)) {
2653126780 .Type,
2653226781 .ComptimeFloat,
......@@ -26557,7 +26806,7 @@ fn validateExternType(
2655726806 },
2655826807 .Fn => {
2655926808 if (position != .other) return false;
26560 const target = sema.mod.getTarget();
26809 const target = mod.getTarget();
2656126810 // For now we want to authorize PTX kernel to use zig objects, even if we end up exposing the ABI.
2656226811 // The goal is to experiment with more integrated CPU/GPU code.
2656326812 if (ty.fnCallingConvention(mod) == .Kernel and (target.cpu.arch == .nvptx or target.cpu.arch == .nvptx64)) {
......@@ -26571,7 +26820,7 @@ fn validateExternType(
2657126820 .Struct, .Union => switch (ty.containerLayout(mod)) {
2657226821 .@"extern" => return true,
2657326822 .@"packed" => {
26574 const bit_size = try ty.bitSizeAdvanced(mod, .sema);
26823 const bit_size = try ty.bitSizeAdvanced(pt, .sema);
2657526824 switch (bit_size) {
2657626825 0, 8, 16, 32, 64, 128 => return true,
2657726826 else => return false,
......@@ -26595,7 +26844,8 @@ fn explainWhyTypeIsNotExtern(
2659526844 ty: Type,
2659626845 position: ExternPosition,
2659726846) CompileError!void {
26598 const mod = sema.mod;
26847 const pt = sema.pt;
26848 const mod = pt.zcu;
2659926849 switch (ty.zigTypeTag(mod)) {
2660026850 .Opaque,
2660126851 .Bool,
......@@ -26622,7 +26872,7 @@ fn explainWhyTypeIsNotExtern(
2662226872 if (!ty.isConstPtr(mod) and pointee_ty.zigTypeTag(mod) == .Fn) {
2662326873 try sema.errNote(src_loc, msg, "pointer to extern function must be 'const'", .{});
2662426874 } else if (try sema.typeRequiresComptime(ty)) {
26625 try sema.errNote(src_loc, msg, "pointer to comptime-only type '{}'", .{pointee_ty.fmt(sema.mod)});
26875 try sema.errNote(src_loc, msg, "pointer to comptime-only type '{}'", .{pointee_ty.fmt(pt)});
2662626876 try sema.explainWhyTypeIsComptime(msg, src_loc, ty);
2662726877 }
2662826878 try sema.explainWhyTypeIsNotExtern(msg, src_loc, pointee_ty, .other);
......@@ -26650,7 +26900,7 @@ fn explainWhyTypeIsNotExtern(
2665026900 },
2665126901 .Enum => {
2665226902 const tag_ty = ty.intTagType(mod);
26653 try sema.errNote(src_loc, msg, "enum tag type '{}' is not extern compatible", .{tag_ty.fmt(sema.mod)});
26903 try sema.errNote(src_loc, msg, "enum tag type '{}' is not extern compatible", .{tag_ty.fmt(pt)});
2665426904 try sema.explainWhyTypeIsNotExtern(msg, src_loc, tag_ty, position);
2665526905 },
2665626906 .Struct => try sema.errNote(src_loc, msg, "only extern structs and ABI sized packed structs are extern compatible", .{}),
......@@ -26671,7 +26921,8 @@ fn explainWhyTypeIsNotExtern(
2667126921/// Returns true if `ty` is allowed in packed types.
2667226922/// Does not require `ty` to be resolved in any way, but may resolve whether it is comptime-only.
2667326923fn validatePackedType(sema: *Sema, ty: Type) !bool {
26674 const zcu = sema.mod;
26924 const pt = sema.pt;
26925 const zcu = pt.zcu;
2667526926 return switch (ty.zigTypeTag(zcu)) {
2667626927 .Type,
2667726928 .ComptimeFloat,
......@@ -26710,7 +26961,8 @@ fn explainWhyTypeIsNotPacked(
2671026961 src_loc: LazySrcLoc,
2671126962 ty: Type,
2671226963) CompileError!void {
26713 const mod = sema.mod;
26964 const pt = sema.pt;
26965 const mod = pt.zcu;
2671426966 switch (ty.zigTypeTag(mod)) {
2671526967 .Void,
2671626968 .Bool,
......@@ -26750,10 +27002,11 @@ fn explainWhyTypeIsNotPacked(
2675027002}
2675127003
2675227004fn prepareSimplePanic(sema: *Sema) !void {
26753 const mod = sema.mod;
27005 const pt = sema.pt;
27006 const mod = pt.zcu;
2675427007
2675527008 if (mod.panic_func_index == .none) {
26756 const decl_index = (try mod.getBuiltinDecl("panic"));
27009 const decl_index = (try pt.getBuiltinDecl("panic"));
2675727010 // decl_index may be an alias; we must find the decl that actually
2675827011 // owns the function.
2675927012 try sema.ensureDeclAnalyzed(decl_index);
......@@ -26766,17 +27019,17 @@ fn prepareSimplePanic(sema: *Sema) !void {
2676627019 }
2676727020
2676827021 if (mod.null_stack_trace == .none) {
26769 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
26770 try stack_trace_ty.resolveFields(mod);
27022 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
27023 try stack_trace_ty.resolveFields(pt);
2677127024 const target = mod.getTarget();
26772 const ptr_stack_trace_ty = try mod.ptrTypeSema(.{
27025 const ptr_stack_trace_ty = try pt.ptrTypeSema(.{
2677327026 .child = stack_trace_ty.toIntern(),
2677427027 .flags = .{
2677527028 .address_space = target_util.defaultAddressSpace(target, .global_constant),
2677627029 },
2677727030 });
26778 const opt_ptr_stack_trace_ty = try mod.optionalType(ptr_stack_trace_ty.toIntern());
26779 mod.null_stack_trace = try mod.intern(.{ .opt = .{
27031 const opt_ptr_stack_trace_ty = try pt.optionalType(ptr_stack_trace_ty.toIntern());
27032 mod.null_stack_trace = try pt.intern(.{ .opt = .{
2678027033 .ty = opt_ptr_stack_trace_ty.toIntern(),
2678127034 .val = .none,
2678227035 } });
......@@ -26787,13 +27040,14 @@ fn prepareSimplePanic(sema: *Sema) !void {
2678727040/// instructions. This function ensures the panic function will be available to
2678827041/// be called during that time.
2678927042fn preparePanicId(sema: *Sema, block: *Block, panic_id: Module.PanicId) !InternPool.DeclIndex {
26790 const mod = sema.mod;
27043 const pt = sema.pt;
27044 const mod = pt.zcu;
2679127045 const gpa = sema.gpa;
2679227046 if (mod.panic_messages[@intFromEnum(panic_id)].unwrap()) |x| return x;
2679327047
2679427048 try sema.prepareSimplePanic();
2679527049
26796 const panic_messages_ty = try mod.getBuiltinType("panic_messages");
27050 const panic_messages_ty = try pt.getBuiltinType("panic_messages");
2679727051 const msg_decl_index = (sema.namespaceLookup(
2679827052 block,
2679927053 LazySrcLoc.unneeded,
......@@ -26892,7 +27146,8 @@ fn addSafetyCheckExtra(
2689227146}
2689327147
2689427148fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.Ref, operation: CallOperation) !void {
26895 const mod = sema.mod;
27149 const pt = sema.pt;
27150 const mod = pt.zcu;
2689627151
2689727152 if (!mod.backendSupportsFeature(.panic_fn)) {
2689827153 _ = try block.addNoOp(.trap);
......@@ -26905,8 +27160,8 @@ fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.
2690527160 const panic_fn = try sema.analyzeDeclVal(block, src, panic_func.owner_decl);
2690627161 const null_stack_trace = Air.internedToRef(mod.null_stack_trace);
2690727162
26908 const opt_usize_ty = try mod.optionalType(.usize_type);
26909 const null_ret_addr = Air.internedToRef((try mod.intern(.{ .opt = .{
27163 const opt_usize_ty = try pt.optionalType(.usize_type);
27164 const null_ret_addr = Air.internedToRef((try pt.intern(.{ .opt = .{
2691027165 .ty = opt_usize_ty.toIntern(),
2691127166 .val = .none,
2691227167 } })));
......@@ -26921,9 +27176,10 @@ fn panicUnwrapError(
2692127176 unwrap_err_tag: Air.Inst.Tag,
2692227177 is_non_err_tag: Air.Inst.Tag,
2692327178) !void {
27179 const pt = sema.pt;
2692427180 assert(!parent_block.is_comptime);
2692527181 const ok = try parent_block.addUnOp(is_non_err_tag, operand);
26926 if (!sema.mod.comp.formatted_panics) {
27182 if (!pt.zcu.comp.formatted_panics) {
2692727183 return sema.addSafetyCheck(parent_block, src, ok, .unwrap_error);
2692827184 }
2692927185 const gpa = sema.gpa;
......@@ -26942,10 +27198,10 @@ fn panicUnwrapError(
2694227198 defer fail_block.instructions.deinit(gpa);
2694327199
2694427200 {
26945 if (!sema.mod.backendSupportsFeature(.panic_unwrap_error)) {
27201 if (!pt.zcu.backendSupportsFeature(.panic_unwrap_error)) {
2694627202 _ = try fail_block.addNoOp(.trap);
2694727203 } else {
26948 const panic_fn = try sema.mod.getBuiltin("panicUnwrapError");
27204 const panic_fn = try sema.pt.getBuiltin("panicUnwrapError");
2694927205 const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
2695027206 const err_return_trace = try sema.getErrorReturnTrace(&fail_block);
2695127207 const args: [2]Air.Inst.Ref = .{ err_return_trace, err };
......@@ -26965,7 +27221,7 @@ fn panicIndexOutOfBounds(
2696527221) !void {
2696627222 assert(!parent_block.is_comptime);
2696727223 const ok = try parent_block.addBinOp(cmp_op, index, len);
26968 if (!sema.mod.comp.formatted_panics) {
27224 if (!sema.pt.zcu.comp.formatted_panics) {
2696927225 return sema.addSafetyCheck(parent_block, src, ok, .index_out_of_bounds);
2697027226 }
2697127227 try sema.safetyCheckFormatted(parent_block, src, ok, "panicOutOfBounds", &.{ index, len });
......@@ -26980,7 +27236,7 @@ fn panicInactiveUnionField(
2698027236) !void {
2698127237 assert(!parent_block.is_comptime);
2698227238 const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);
26983 if (!sema.mod.comp.formatted_panics) {
27239 if (!sema.pt.zcu.comp.formatted_panics) {
2698427240 return sema.addSafetyCheck(parent_block, src, ok, .inactive_union_field);
2698527241 }
2698627242 try sema.safetyCheckFormatted(parent_block, src, ok, "panicInactiveUnionField", &.{ active_tag, wanted_tag });
......@@ -26996,7 +27252,8 @@ fn panicSentinelMismatch(
2699627252 sentinel_index: Air.Inst.Ref,
2699727253) !void {
2699827254 assert(!parent_block.is_comptime);
26999 const mod = sema.mod;
27255 const pt = sema.pt;
27256 const mod = pt.zcu;
2700027257 const expected_sentinel_val = maybe_sentinel orelse return;
2700127258 const expected_sentinel = Air.internedToRef(expected_sentinel_val.toIntern());
2700227259
......@@ -27004,7 +27261,7 @@ fn panicSentinelMismatch(
2700427261 const actual_sentinel = if (ptr_ty.isSlice(mod))
2700527262 try parent_block.addBinOp(.slice_elem_val, ptr, sentinel_index)
2700627263 else blk: {
27007 const elem_ptr_ty = try ptr_ty.elemPtrType(null, mod);
27264 const elem_ptr_ty = try ptr_ty.elemPtrType(null, pt);
2700827265 const sentinel_ptr = try parent_block.addPtrElemPtr(ptr, sentinel_index, elem_ptr_ty);
2700927266 break :blk try parent_block.addTyOp(.load, sentinel_ty, sentinel_ptr);
2701027267 };
......@@ -27022,13 +27279,13 @@ fn panicSentinelMismatch(
2702227279 } else if (sentinel_ty.isSelfComparable(mod, true))
2702327280 try parent_block.addBinOp(.cmp_eq, expected_sentinel, actual_sentinel)
2702427281 else {
27025 const panic_fn = try mod.getBuiltin("checkNonScalarSentinel");
27282 const panic_fn = try pt.getBuiltin("checkNonScalarSentinel");
2702627283 const args: [2]Air.Inst.Ref = .{ expected_sentinel, actual_sentinel };
2702727284 try sema.callBuiltin(parent_block, src, panic_fn, .auto, &args, .@"safety check");
2702827285 return;
2702927286 };
2703027287
27031 if (!sema.mod.comp.formatted_panics) {
27288 if (!pt.zcu.comp.formatted_panics) {
2703227289 return sema.addSafetyCheck(parent_block, src, ok, .sentinel_mismatch);
2703327290 }
2703427291 try sema.safetyCheckFormatted(parent_block, src, ok, "panicSentinelMismatch", &.{ expected_sentinel, actual_sentinel });
......@@ -27042,7 +27299,9 @@ fn safetyCheckFormatted(
2704227299 func: []const u8,
2704327300 args: []const Air.Inst.Ref,
2704427301) CompileError!void {
27045 assert(sema.mod.comp.formatted_panics);
27302 const pt = sema.pt;
27303 const zcu = pt.zcu;
27304 assert(zcu.comp.formatted_panics);
2704627305 const gpa = sema.gpa;
2704727306
2704827307 var fail_block: Block = .{
......@@ -27058,10 +27317,10 @@ fn safetyCheckFormatted(
2705827317
2705927318 defer fail_block.instructions.deinit(gpa);
2706027319
27061 if (!sema.mod.backendSupportsFeature(.safety_check_formatted)) {
27320 if (!zcu.backendSupportsFeature(.safety_check_formatted)) {
2706227321 _ = try fail_block.addNoOp(.trap);
2706327322 } else {
27064 const panic_fn = try sema.mod.getBuiltin(func);
27323 const panic_fn = try pt.getBuiltin(func);
2706527324 try sema.callBuiltin(&fail_block, src, panic_fn, .auto, args, .@"safety check");
2706627325 }
2706727326 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
......@@ -27102,7 +27361,8 @@ fn fieldVal(
2710227361 // When editing this function, note that there is corresponding logic to be edited
2710327362 // in `fieldPtr`. This function takes a value and returns a value.
2710427363
27105 const mod = sema.mod;
27364 const pt = sema.pt;
27365 const mod = pt.zcu;
2710627366 const ip = &mod.intern_pool;
2710727367 const object_src = src; // TODO better source location
2710827368 const object_ty = sema.typeOf(object);
......@@ -27120,10 +27380,10 @@ fn fieldVal(
2712027380 switch (inner_ty.zigTypeTag(mod)) {
2712127381 .Array => {
2712227382 if (field_name.eqlSlice("len", ip)) {
27123 return Air.internedToRef((try mod.intValue(Type.usize, inner_ty.arrayLen(mod))).toIntern());
27383 return Air.internedToRef((try pt.intValue(Type.usize, inner_ty.arrayLen(mod))).toIntern());
2712427384 } else if (field_name.eqlSlice("ptr", ip) and is_pointer_to) {
2712527385 const ptr_info = object_ty.ptrInfo(mod);
27126 const result_ty = try mod.ptrTypeSema(.{
27386 const result_ty = try pt.ptrTypeSema(.{
2712727387 .child = Type.fromInterned(ptr_info.child).childType(mod).toIntern(),
2712827388 .sentinel = if (inner_ty.sentinel(mod)) |s| s.toIntern() else .none,
2712927389 .flags = .{
......@@ -27143,7 +27403,7 @@ fn fieldVal(
2714327403 block,
2714427404 field_name_src,
2714527405 "no member named '{}' in '{}'",
27146 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27406 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2714727407 );
2714827408 }
2714927409 },
......@@ -27167,7 +27427,7 @@ fn fieldVal(
2716727427 block,
2716827428 field_name_src,
2716927429 "no member named '{}' in '{}'",
27170 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27430 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2717127431 );
2717227432 }
2717327433 }
......@@ -27194,7 +27454,7 @@ fn fieldVal(
2719427454 .error_set_type => |error_set_type| blk: {
2719527455 if (error_set_type.nameIndex(ip, field_name) != null) break :blk;
2719627456 return sema.fail(block, src, "no error named '{}' in '{}'", .{
27197 field_name.fmt(ip), child_type.fmt(mod),
27457 field_name.fmt(ip), child_type.fmt(pt),
2719827458 });
2719927459 },
2720027460 .inferred_error_set_type => {
......@@ -27210,8 +27470,8 @@ fn fieldVal(
2721027470 const error_set_type = if (!child_type.isAnyError(mod))
2721127471 child_type
2721227472 else
27213 try mod.singleErrorSetType(field_name);
27214 return Air.internedToRef((try mod.intern(.{ .err = .{
27473 try pt.singleErrorSetType(field_name);
27474 return Air.internedToRef((try pt.intern(.{ .err = .{
2721527475 .ty = error_set_type.toIntern(),
2721627476 .name = field_name,
2721727477 } })));
......@@ -27220,11 +27480,11 @@ fn fieldVal(
2722027480 if (try sema.namespaceLookupVal(block, src, child_type.getNamespaceIndex(mod), field_name)) |inst| {
2722127481 return inst;
2722227482 }
27223 try child_type.resolveFields(mod);
27483 try child_type.resolveFields(pt);
2722427484 if (child_type.unionTagType(mod)) |enum_ty| {
2722527485 if (enum_ty.enumFieldIndex(field_name, mod)) |field_index_usize| {
2722627486 const field_index: u32 = @intCast(field_index_usize);
27227 return Air.internedToRef((try mod.enumValueFieldIndex(enum_ty, field_index)).toIntern());
27487 return Air.internedToRef((try pt.enumValueFieldIndex(enum_ty, field_index)).toIntern());
2722827488 }
2722927489 }
2723027490 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
......@@ -27236,7 +27496,7 @@ fn fieldVal(
2723627496 const field_index_usize = child_type.enumFieldIndex(field_name, mod) orelse
2723727497 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2723827498 const field_index: u32 = @intCast(field_index_usize);
27239 const enum_val = try mod.enumValueFieldIndex(child_type, field_index);
27499 const enum_val = try pt.enumValueFieldIndex(child_type, field_index);
2724027500 return Air.internedToRef(enum_val.toIntern());
2724127501 },
2724227502 .Struct, .Opaque => {
......@@ -27247,7 +27507,7 @@ fn fieldVal(
2724727507 },
2724827508 else => {
2724927509 const msg = msg: {
27250 const msg = try sema.errMsg(src, "type '{}' has no members", .{child_type.fmt(mod)});
27510 const msg = try sema.errMsg(src, "type '{}' has no members", .{child_type.fmt(pt)});
2725127511 errdefer msg.destroy(sema.gpa);
2725227512 if (child_type.isSlice(mod)) try sema.errNote(src, msg, "slice values have 'len' and 'ptr' members", .{});
2725327513 if (child_type.zigTypeTag(mod) == .Array) try sema.errNote(src, msg, "array values have 'len' member", .{});
......@@ -27288,13 +27548,14 @@ fn fieldPtr(
2728827548 // When editing this function, note that there is corresponding logic to be edited
2728927549 // in `fieldVal`. This function takes a pointer and returns a pointer.
2729027550
27291 const mod = sema.mod;
27551 const pt = sema.pt;
27552 const mod = pt.zcu;
2729227553 const ip = &mod.intern_pool;
2729327554 const object_ptr_src = src; // TODO better source location
2729427555 const object_ptr_ty = sema.typeOf(object_ptr);
2729527556 const object_ty = switch (object_ptr_ty.zigTypeTag(mod)) {
2729627557 .Pointer => object_ptr_ty.childType(mod),
27297 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(mod)}),
27558 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(pt)}),
2729827559 };
2729927560
2730027561 // Zig allows dereferencing a single pointer during field lookup. Note that
......@@ -27310,11 +27571,11 @@ fn fieldPtr(
2731027571 switch (inner_ty.zigTypeTag(mod)) {
2731127572 .Array => {
2731227573 if (field_name.eqlSlice("len", ip)) {
27313 const int_val = try mod.intValue(Type.usize, inner_ty.arrayLen(mod));
27574 const int_val = try pt.intValue(Type.usize, inner_ty.arrayLen(mod));
2731427575 return anonDeclRef(sema, int_val.toIntern());
2731527576 } else if (field_name.eqlSlice("ptr", ip) and is_pointer_to) {
2731627577 const ptr_info = object_ty.ptrInfo(mod);
27317 const new_ptr_ty = try mod.ptrTypeSema(.{
27578 const new_ptr_ty = try pt.ptrTypeSema(.{
2731827579 .child = Type.fromInterned(ptr_info.child).childType(mod).toIntern(),
2731927580 .sentinel = if (object_ty.sentinel(mod)) |s| s.toIntern() else .none,
2732027581 .flags = .{
......@@ -27329,7 +27590,7 @@ fn fieldPtr(
2732927590 .packed_offset = ptr_info.packed_offset,
2733027591 });
2733127592 const ptr_ptr_info = object_ptr_ty.ptrInfo(mod);
27332 const result_ty = try mod.ptrTypeSema(.{
27593 const result_ty = try pt.ptrTypeSema(.{
2733327594 .child = new_ptr_ty.toIntern(),
2733427595 .sentinel = if (object_ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
2733527596 .flags = .{
......@@ -27348,7 +27609,7 @@ fn fieldPtr(
2734827609 block,
2734927610 field_name_src,
2735027611 "no member named '{}' in '{}'",
27351 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27612 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2735227613 );
2735327614 }
2735427615 },
......@@ -27363,7 +27624,7 @@ fn fieldPtr(
2736327624 if (field_name.eqlSlice("ptr", ip)) {
2736427625 const slice_ptr_ty = inner_ty.slicePtrFieldType(mod);
2736527626
27366 const result_ty = try mod.ptrTypeSema(.{
27627 const result_ty = try pt.ptrTypeSema(.{
2736727628 .child = slice_ptr_ty.toIntern(),
2736827629 .flags = .{
2736927630 .is_const = !attr_ptr_ty.ptrIsMutable(mod),
......@@ -27373,7 +27634,7 @@ fn fieldPtr(
2737327634 });
2737427635
2737527636 if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
27376 return Air.internedToRef((try val.ptrField(Value.slice_ptr_index, mod)).toIntern());
27637 return Air.internedToRef((try val.ptrField(Value.slice_ptr_index, pt)).toIntern());
2737727638 }
2737827639 try sema.requireRuntimeBlock(block, src, null);
2737927640
......@@ -27381,7 +27642,7 @@ fn fieldPtr(
2738127642 try sema.checkKnownAllocPtr(block, inner_ptr, field_ptr);
2738227643 return field_ptr;
2738327644 } else if (field_name.eqlSlice("len", ip)) {
27384 const result_ty = try mod.ptrTypeSema(.{
27645 const result_ty = try pt.ptrTypeSema(.{
2738527646 .child = .usize_type,
2738627647 .flags = .{
2738727648 .is_const = !attr_ptr_ty.ptrIsMutable(mod),
......@@ -27391,7 +27652,7 @@ fn fieldPtr(
2739127652 });
2739227653
2739327654 if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
27394 return Air.internedToRef((try val.ptrField(Value.slice_len_index, mod)).toIntern());
27655 return Air.internedToRef((try val.ptrField(Value.slice_len_index, pt)).toIntern());
2739527656 }
2739627657 try sema.requireRuntimeBlock(block, src, null);
2739727658
......@@ -27403,7 +27664,7 @@ fn fieldPtr(
2740327664 block,
2740427665 field_name_src,
2740527666 "no member named '{}' in '{}'",
27406 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27667 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2740727668 );
2740827669 }
2740927670 },
......@@ -27433,7 +27694,7 @@ fn fieldPtr(
2743327694 break :blk;
2743427695 }
2743527696 return sema.fail(block, src, "no error named '{}' in '{}'", .{
27436 field_name.fmt(ip), child_type.fmt(mod),
27697 field_name.fmt(ip), child_type.fmt(pt),
2743727698 });
2743827699 },
2743927700 .inferred_error_set_type => {
......@@ -27449,8 +27710,8 @@ fn fieldPtr(
2744927710 const error_set_type = if (!child_type.isAnyError(mod))
2745027711 child_type
2745127712 else
27452 try mod.singleErrorSetType(field_name);
27453 return anonDeclRef(sema, try mod.intern(.{ .err = .{
27713 try pt.singleErrorSetType(field_name);
27714 return anonDeclRef(sema, try pt.intern(.{ .err = .{
2745427715 .ty = error_set_type.toIntern(),
2745527716 .name = field_name,
2745627717 } }));
......@@ -27459,11 +27720,11 @@ fn fieldPtr(
2745927720 if (try sema.namespaceLookupRef(block, src, child_type.getNamespaceIndex(mod), field_name)) |inst| {
2746027721 return inst;
2746127722 }
27462 try child_type.resolveFields(mod);
27723 try child_type.resolveFields(pt);
2746327724 if (child_type.unionTagType(mod)) |enum_ty| {
2746427725 if (enum_ty.enumFieldIndex(field_name, mod)) |field_index| {
2746527726 const field_index_u32: u32 = @intCast(field_index);
27466 const idx_val = try mod.enumValueFieldIndex(enum_ty, field_index_u32);
27727 const idx_val = try pt.enumValueFieldIndex(enum_ty, field_index_u32);
2746727728 return anonDeclRef(sema, idx_val.toIntern());
2746827729 }
2746927730 }
......@@ -27477,7 +27738,7 @@ fn fieldPtr(
2747727738 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2747827739 };
2747927740 const field_index_u32: u32 = @intCast(field_index);
27480 const idx_val = try mod.enumValueFieldIndex(child_type, field_index_u32);
27741 const idx_val = try pt.enumValueFieldIndex(child_type, field_index_u32);
2748127742 return anonDeclRef(sema, idx_val.toIntern());
2748227743 },
2748327744 .Struct, .Opaque => {
......@@ -27486,7 +27747,7 @@ fn fieldPtr(
2748627747 }
2748727748 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2748827749 },
27489 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(mod)}),
27750 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(pt)}),
2749027751 }
2749127752 },
2749227753 .Struct => {
......@@ -27533,14 +27794,15 @@ fn fieldCallBind(
2753327794 // When editing this function, note that there is corresponding logic to be edited
2753427795 // in `fieldVal`. This function takes a pointer and returns a pointer.
2753527796
27536 const mod = sema.mod;
27797 const pt = sema.pt;
27798 const mod = pt.zcu;
2753727799 const ip = &mod.intern_pool;
2753827800 const raw_ptr_src = src; // TODO better source location
2753927801 const raw_ptr_ty = sema.typeOf(raw_ptr);
2754027802 const inner_ty = if (raw_ptr_ty.zigTypeTag(mod) == .Pointer and (raw_ptr_ty.ptrSize(mod) == .One or raw_ptr_ty.ptrSize(mod) == .C))
2754127803 raw_ptr_ty.childType(mod)
2754227804 else
27543 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(mod)});
27805 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(pt)});
2754427806
2754527807 // Optionally dereference a second pointer to get the concrete type.
2754627808 const is_double_ptr = inner_ty.zigTypeTag(mod) == .Pointer and inner_ty.ptrSize(mod) == .One;
......@@ -27554,7 +27816,7 @@ fn fieldCallBind(
2755427816 find_field: {
2755527817 switch (concrete_ty.zigTypeTag(mod)) {
2755627818 .Struct => {
27557 try concrete_ty.resolveFields(mod);
27819 try concrete_ty.resolveFields(pt);
2755827820 if (mod.typeToStruct(concrete_ty)) |struct_type| {
2755927821 const field_index = struct_type.nameIndex(ip, field_name) orelse
2756027822 break :find_field;
......@@ -27563,7 +27825,7 @@ fn fieldCallBind(
2756327825 return sema.finishFieldCallBind(block, src, ptr_ty, field_ty, field_index, object_ptr);
2756427826 } else if (concrete_ty.isTuple(mod)) {
2756527827 if (field_name.eqlSlice("len", ip)) {
27566 return .{ .direct = try mod.intRef(Type.usize, concrete_ty.structFieldCount(mod)) };
27828 return .{ .direct = try pt.intRef(Type.usize, concrete_ty.structFieldCount(mod)) };
2756727829 }
2756827830 if (field_name.toUnsigned(ip)) |field_index| {
2756927831 if (field_index >= concrete_ty.structFieldCount(mod)) break :find_field;
......@@ -27580,7 +27842,7 @@ fn fieldCallBind(
2758027842 }
2758127843 },
2758227844 .Union => {
27583 try concrete_ty.resolveFields(mod);
27845 try concrete_ty.resolveFields(pt);
2758427846 const union_obj = mod.typeToUnion(concrete_ty).?;
2758527847 _ = union_obj.loadTagType(ip).nameIndex(ip, field_name) orelse break :find_field;
2758627848 const field_ptr = try unionFieldPtr(sema, block, src, object_ptr, field_name, field_name_src, concrete_ty, false);
......@@ -27661,7 +27923,7 @@ fn fieldCallBind(
2766127923 const msg = msg: {
2766227924 const msg = try sema.errMsg(src, "no field or member function named '{}' in '{}'", .{
2766327925 field_name.fmt(ip),
27664 concrete_ty.fmt(mod),
27926 concrete_ty.fmt(pt),
2766527927 });
2766627928 errdefer msg.destroy(sema.gpa);
2766727929 try sema.addDeclaredHereNote(msg, concrete_ty);
......@@ -27689,8 +27951,9 @@ fn finishFieldCallBind(
2768927951 field_index: u32,
2769027952 object_ptr: Air.Inst.Ref,
2769127953) CompileError!ResolvedFieldCallee {
27692 const mod = sema.mod;
27693 const ptr_field_ty = try mod.ptrTypeSema(.{
27954 const pt = sema.pt;
27955 const mod = pt.zcu;
27956 const ptr_field_ty = try pt.ptrTypeSema(.{
2769427957 .child = field_ty.toIntern(),
2769527958 .flags = .{
2769627959 .is_const = !ptr_ty.ptrIsMutable(mod),
......@@ -27701,14 +27964,14 @@ fn finishFieldCallBind(
2770127964 const container_ty = ptr_ty.childType(mod);
2770227965 if (container_ty.zigTypeTag(mod) == .Struct) {
2770327966 if (container_ty.structFieldIsComptime(field_index, mod)) {
27704 try container_ty.resolveStructFieldInits(mod);
27705 const default_val = (try container_ty.structFieldValueComptime(mod, field_index)).?;
27967 try container_ty.resolveStructFieldInits(pt);
27968 const default_val = (try container_ty.structFieldValueComptime(pt, field_index)).?;
2770627969 return .{ .direct = Air.internedToRef(default_val.toIntern()) };
2770727970 }
2770827971 }
2770927972
2771027973 if (try sema.resolveDefinedValue(block, src, object_ptr)) |struct_ptr_val| {
27711 const ptr_val = try struct_ptr_val.ptrField(field_index, mod);
27974 const ptr_val = try struct_ptr_val.ptrField(field_index, pt);
2771227975 const pointer = Air.internedToRef(ptr_val.toIntern());
2771327976 return .{ .direct = try sema.analyzeLoad(block, src, pointer, src) };
2771427977 }
......@@ -27725,7 +27988,8 @@ fn namespaceLookup(
2772527988 opt_namespace: InternPool.OptionalNamespaceIndex,
2772627989 decl_name: InternPool.NullTerminatedString,
2772727990) CompileError!?InternPool.DeclIndex {
27728 const mod = sema.mod;
27991 const pt = sema.pt;
27992 const mod = pt.zcu;
2772927993 const gpa = sema.gpa;
2773027994 if (try sema.lookupInNamespace(block, src, opt_namespace, decl_name, true)) |decl_index| {
2773127995 const decl = mod.declPtr(decl_index);
......@@ -27780,16 +28044,17 @@ fn structFieldPtr(
2778028044 struct_ty: Type,
2778128045 initializing: bool,
2778228046) CompileError!Air.Inst.Ref {
27783 const mod = sema.mod;
28047 const pt = sema.pt;
28048 const mod = pt.zcu;
2778428049 const ip = &mod.intern_pool;
2778528050 assert(struct_ty.zigTypeTag(mod) == .Struct);
2778628051
27787 try struct_ty.resolveFields(mod);
27788 try struct_ty.resolveLayout(mod);
28052 try struct_ty.resolveFields(pt);
28053 try struct_ty.resolveLayout(pt);
2778928054
2779028055 if (struct_ty.isTuple(mod)) {
2779128056 if (field_name.eqlSlice("len", ip)) {
27792 const len_inst = try mod.intRef(Type.usize, struct_ty.structFieldCount(mod));
28057 const len_inst = try pt.intRef(Type.usize, struct_ty.structFieldCount(mod));
2779328058 return sema.analyzeRef(block, src, len_inst);
2779428059 }
2779528060 const field_index = try sema.tupleFieldIndex(block, struct_ty, field_name, field_name_src);
......@@ -27817,14 +28082,15 @@ fn structFieldPtrByIndex(
2781728082 struct_ty: Type,
2781828083 initializing: bool,
2781928084) CompileError!Air.Inst.Ref {
27820 const mod = sema.mod;
28085 const pt = sema.pt;
28086 const mod = pt.zcu;
2782128087 const ip = &mod.intern_pool;
2782228088 if (struct_ty.isAnonStruct(mod)) {
2782328089 return sema.tupleFieldPtr(block, src, struct_ptr, field_src, field_index, initializing);
2782428090 }
2782528091
2782628092 if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| {
27827 const val = try struct_ptr_val.ptrField(field_index, mod);
28093 const val = try struct_ptr_val.ptrField(field_index, pt);
2782828094 return Air.internedToRef(val.toIntern());
2782928095 }
2783028096
......@@ -27848,7 +28114,7 @@ fn structFieldPtrByIndex(
2784828114 try sema.typeAbiAlignment(Type.fromInterned(struct_ptr_ty_info.child));
2784928115
2785028116 if (struct_type.layout == .@"packed") {
27851 switch (struct_ty.packedStructFieldPtrInfo(struct_ptr_ty, field_index, mod)) {
28117 switch (struct_ty.packedStructFieldPtrInfo(struct_ptr_ty, field_index, pt)) {
2785228118 .bit_ptr => |packed_offset| {
2785328119 ptr_ty_data.flags.alignment = parent_align;
2785428120 ptr_ty_data.packed_offset = packed_offset;
......@@ -27861,14 +28127,14 @@ fn structFieldPtrByIndex(
2786128127 // For extern structs, field alignment might be bigger than type's
2786228128 // natural alignment. Eg, in `extern struct { x: u32, y: u16 }` the
2786328129 // second field is aligned as u32.
27864 const field_offset = struct_ty.structFieldOffset(field_index, mod);
28130 const field_offset = struct_ty.structFieldOffset(field_index, pt);
2786528131 ptr_ty_data.flags.alignment = if (parent_align == .none)
2786628132 .none
2786728133 else
2786828134 @enumFromInt(@min(@intFromEnum(parent_align), @ctz(field_offset)));
2786928135 } else {
2787028136 // Our alignment is capped at the field alignment.
27871 const field_align = try mod.structFieldAlignmentAdvanced(
28137 const field_align = try pt.structFieldAlignmentAdvanced(
2787228138 struct_type.fieldAlign(ip, field_index),
2787328139 Type.fromInterned(field_ty),
2787428140 struct_type.layout,
......@@ -27880,11 +28146,11 @@ fn structFieldPtrByIndex(
2788028146 field_align.min(parent_align);
2788128147 }
2788228148
27883 const ptr_field_ty = try mod.ptrTypeSema(ptr_ty_data);
28149 const ptr_field_ty = try pt.ptrTypeSema(ptr_ty_data);
2788428150
2788528151 if (struct_type.fieldIsComptime(ip, field_index)) {
27886 try struct_ty.resolveStructFieldInits(mod);
27887 const val = try mod.intern(.{ .ptr = .{
28152 try struct_ty.resolveStructFieldInits(pt);
28153 const val = try pt.intern(.{ .ptr = .{
2788828154 .ty = ptr_field_ty.toIntern(),
2788928155 .base_addr = .{ .comptime_field = struct_type.field_inits.get(ip)[field_index] },
2789028156 .byte_offset = 0,
......@@ -27905,11 +28171,12 @@ fn structFieldVal(
2790528171 field_name_src: LazySrcLoc,
2790628172 struct_ty: Type,
2790728173) CompileError!Air.Inst.Ref {
27908 const mod = sema.mod;
28174 const pt = sema.pt;
28175 const mod = pt.zcu;
2790928176 const ip = &mod.intern_pool;
2791028177 assert(struct_ty.zigTypeTag(mod) == .Struct);
2791128178
27912 try struct_ty.resolveFields(mod);
28179 try struct_ty.resolveFields(pt);
2791328180
2791428181 switch (ip.indexToKey(struct_ty.toIntern())) {
2791528182 .struct_type => {
......@@ -27920,7 +28187,7 @@ fn structFieldVal(
2792028187 const field_index = struct_type.nameIndex(ip, field_name) orelse
2792128188 return sema.failWithBadStructFieldAccess(block, struct_ty, struct_type, field_name_src, field_name);
2792228189 if (struct_type.fieldIsComptime(ip, field_index)) {
27923 try struct_ty.resolveStructFieldInits(mod);
28190 try struct_ty.resolveStructFieldInits(pt);
2792428191 return Air.internedToRef(struct_type.field_inits.get(ip)[field_index]);
2792528192 }
2792628193
......@@ -27929,15 +28196,15 @@ fn structFieldVal(
2792928196 return Air.internedToRef(field_val.toIntern());
2793028197
2793128198 if (try sema.resolveValue(struct_byval)) |struct_val| {
27932 if (struct_val.isUndef(mod)) return mod.undefRef(field_ty);
28199 if (struct_val.isUndef(mod)) return pt.undefRef(field_ty);
2793328200 if ((try sema.typeHasOnePossibleValue(field_ty))) |opv| {
2793428201 return Air.internedToRef(opv.toIntern());
2793528202 }
27936 return Air.internedToRef((try struct_val.fieldValue(mod, field_index)).toIntern());
28203 return Air.internedToRef((try struct_val.fieldValue(pt, field_index)).toIntern());
2793728204 }
2793828205
2793928206 try sema.requireRuntimeBlock(block, src, null);
27940 try field_ty.resolveLayout(mod);
28207 try field_ty.resolveLayout(pt);
2794128208 return block.addStructFieldVal(struct_byval, field_index, field_ty);
2794228209 },
2794328210 .anon_struct_type => |anon_struct| {
......@@ -27961,9 +28228,10 @@ fn tupleFieldVal(
2796128228 field_name_src: LazySrcLoc,
2796228229 tuple_ty: Type,
2796328230) CompileError!Air.Inst.Ref {
27964 const mod = sema.mod;
28231 const pt = sema.pt;
28232 const mod = pt.zcu;
2796528233 if (field_name.eqlSlice("len", &mod.intern_pool)) {
27966 return mod.intRef(Type.usize, tuple_ty.structFieldCount(mod));
28234 return pt.intRef(Type.usize, tuple_ty.structFieldCount(mod));
2796728235 }
2796828236 const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_name_src);
2796928237 return sema.tupleFieldValByIndex(block, src, tuple_byval, field_index, tuple_ty);
......@@ -27977,18 +28245,18 @@ fn tupleFieldIndex(
2797728245 field_name: InternPool.NullTerminatedString,
2797828246 field_name_src: LazySrcLoc,
2797928247) CompileError!u32 {
27980 const mod = sema.mod;
27981 const ip = &mod.intern_pool;
28248 const pt = sema.pt;
28249 const ip = &pt.zcu.intern_pool;
2798228250 assert(!field_name.eqlSlice("len", ip));
2798328251 if (field_name.toUnsigned(ip)) |field_index| {
27984 if (field_index < tuple_ty.structFieldCount(mod)) return field_index;
28252 if (field_index < tuple_ty.structFieldCount(pt.zcu)) return field_index;
2798528253 return sema.fail(block, field_name_src, "index '{}' out of bounds of tuple '{}'", .{
27986 field_name.fmt(ip), tuple_ty.fmt(mod),
28254 field_name.fmt(ip), tuple_ty.fmt(pt),
2798728255 });
2798828256 }
2798928257
2799028258 return sema.fail(block, field_name_src, "no field named '{}' in tuple '{}'", .{
27991 field_name.fmt(ip), tuple_ty.fmt(mod),
28259 field_name.fmt(ip), tuple_ty.fmt(pt),
2799228260 });
2799328261}
2799428262
......@@ -28000,12 +28268,13 @@ fn tupleFieldValByIndex(
2800028268 field_index: u32,
2800128269 tuple_ty: Type,
2800228270) CompileError!Air.Inst.Ref {
28003 const mod = sema.mod;
28271 const pt = sema.pt;
28272 const mod = pt.zcu;
2800428273 const field_ty = tuple_ty.structFieldType(field_index, mod);
2800528274
2800628275 if (tuple_ty.structFieldIsComptime(field_index, mod))
28007 try tuple_ty.resolveStructFieldInits(mod);
28008 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_value| {
28276 try tuple_ty.resolveStructFieldInits(pt);
28277 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2800928278 return Air.internedToRef(default_value.toIntern());
2801028279 }
2801128280
......@@ -28014,9 +28283,9 @@ fn tupleFieldValByIndex(
2801428283 return Air.internedToRef(opv.toIntern());
2801528284 }
2801628285 return switch (mod.intern_pool.indexToKey(tuple_val.toIntern())) {
28017 .undef => mod.undefRef(field_ty),
28286 .undef => pt.undefRef(field_ty),
2801828287 .aggregate => |aggregate| Air.internedToRef(switch (aggregate.storage) {
28019 .bytes => |bytes| try mod.intValue(Type.u8, bytes.at(field_index, &mod.intern_pool)),
28288 .bytes => |bytes| try pt.intValue(Type.u8, bytes.at(field_index, &mod.intern_pool)),
2802028289 .elems => |elems| Value.fromInterned(elems[field_index]),
2802128290 .repeated_elem => |elem| Value.fromInterned(elem),
2802228291 }.toIntern()),
......@@ -28025,7 +28294,7 @@ fn tupleFieldValByIndex(
2802528294 }
2802628295
2802728296 try sema.requireRuntimeBlock(block, src, null);
28028 try field_ty.resolveLayout(mod);
28297 try field_ty.resolveLayout(pt);
2802928298 return block.addStructFieldVal(tuple_byval, field_index, field_ty);
2803028299}
2803128300
......@@ -28039,18 +28308,19 @@ fn unionFieldPtr(
2803928308 union_ty: Type,
2804028309 initializing: bool,
2804128310) CompileError!Air.Inst.Ref {
28042 const mod = sema.mod;
28311 const pt = sema.pt;
28312 const mod = pt.zcu;
2804328313 const ip = &mod.intern_pool;
2804428314
2804528315 assert(union_ty.zigTypeTag(mod) == .Union);
2804628316
2804728317 const union_ptr_ty = sema.typeOf(union_ptr);
2804828318 const union_ptr_info = union_ptr_ty.ptrInfo(mod);
28049 try union_ty.resolveFields(mod);
28319 try union_ty.resolveFields(pt);
2805028320 const union_obj = mod.typeToUnion(union_ty).?;
2805128321 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
2805228322 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
28053 const ptr_field_ty = try mod.ptrTypeSema(.{
28323 const ptr_field_ty = try pt.ptrTypeSema(.{
2805428324 .child = field_ty.toIntern(),
2805528325 .flags = .{
2805628326 .is_const = union_ptr_info.flags.is_const,
......@@ -28061,7 +28331,7 @@ fn unionFieldPtr(
2806128331 union_ptr_info.flags.alignment
2806228332 else
2806328333 try sema.typeAbiAlignment(union_ty);
28064 const field_align = try mod.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema);
28334 const field_align = try pt.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema);
2806528335 break :blk union_align.min(field_align);
2806628336 } else union_ptr_info.flags.alignment,
2806728337 },
......@@ -28087,9 +28357,9 @@ fn unionFieldPtr(
2808728357 switch (union_obj.getLayout(ip)) {
2808828358 .auto => if (initializing) {
2808928359 // Store to the union to initialize the tag.
28090 const field_tag = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28360 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2809128361 const payload_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
28092 const new_union_val = try mod.unionValue(union_ty, field_tag, try mod.undefValue(payload_ty));
28362 const new_union_val = try pt.unionValue(union_ty, field_tag, try pt.undefValue(payload_ty));
2809328363 try sema.storePtrVal(block, src, union_ptr_val, new_union_val, union_ty);
2809428364 } else {
2809528365 const union_val = (try sema.pointerDeref(block, src, union_ptr_val, union_ptr_ty)) orelse
......@@ -28098,7 +28368,7 @@ fn unionFieldPtr(
2809828368 return sema.failWithUseOfUndef(block, src);
2809928369 }
2810028370 const un = ip.indexToKey(union_val.toIntern()).un;
28101 const field_tag = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28371 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2810228372 const tag_matches = un.tag == field_tag.toIntern();
2810328373 if (!tag_matches) {
2810428374 const msg = msg: {
......@@ -28117,7 +28387,7 @@ fn unionFieldPtr(
2811728387 },
2811828388 .@"packed", .@"extern" => {},
2811928389 }
28120 const field_ptr_val = try union_ptr_val.ptrField(field_index, mod);
28390 const field_ptr_val = try union_ptr_val.ptrField(field_index, pt);
2812128391 return Air.internedToRef(field_ptr_val.toIntern());
2812228392 }
2812328393
......@@ -28125,7 +28395,7 @@ fn unionFieldPtr(
2812528395 if (!initializing and union_obj.getLayout(ip) == .auto and block.wantSafety() and
2812628396 union_ty.unionTagTypeSafety(mod) != null and union_obj.field_types.len > 1)
2812728397 {
28128 const wanted_tag_val = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28398 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2812928399 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2813028400 // TODO would it be better if get_union_tag supported pointers to unions?
2813128401 const union_val = try block.addTyOp(.load, union_ty, union_ptr);
......@@ -28148,21 +28418,22 @@ fn unionFieldVal(
2814828418 field_name_src: LazySrcLoc,
2814928419 union_ty: Type,
2815028420) CompileError!Air.Inst.Ref {
28151 const zcu = sema.mod;
28421 const pt = sema.pt;
28422 const zcu = pt.zcu;
2815228423 const ip = &zcu.intern_pool;
2815328424 assert(union_ty.zigTypeTag(zcu) == .Union);
2815428425
28155 try union_ty.resolveFields(zcu);
28426 try union_ty.resolveFields(pt);
2815628427 const union_obj = zcu.typeToUnion(union_ty).?;
2815728428 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
2815828429 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
2815928430 const enum_field_index: u32 = @intCast(Type.fromInterned(union_obj.enum_tag_ty).enumFieldIndex(field_name, zcu).?);
2816028431
2816128432 if (try sema.resolveValue(union_byval)) |union_val| {
28162 if (union_val.isUndef(zcu)) return zcu.undefRef(field_ty);
28433 if (union_val.isUndef(zcu)) return pt.undefRef(field_ty);
2816328434
2816428435 const un = ip.indexToKey(union_val.toIntern()).un;
28165 const field_tag = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28436 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2816628437 const tag_matches = un.tag == field_tag.toIntern();
2816728438 switch (union_obj.getLayout(ip)) {
2816828439 .auto => {
......@@ -28191,7 +28462,7 @@ fn unionFieldVal(
2819128462 .@"packed" => if (tag_matches) {
2819228463 // Fast path - no need to use bitcast logic.
2819328464 return Air.internedToRef(un.val);
28194 } else if (try sema.bitCastVal(union_val, field_ty, 0, try union_ty.bitSizeAdvanced(zcu, .sema), 0)) |field_val| {
28465 } else if (try sema.bitCastVal(union_val, field_ty, 0, try union_ty.bitSizeAdvanced(pt, .sema), 0)) |field_val| {
2819528466 return Air.internedToRef(field_val.toIntern());
2819628467 },
2819728468 }
......@@ -28201,7 +28472,7 @@ fn unionFieldVal(
2820128472 if (union_obj.getLayout(ip) == .auto and block.wantSafety() and
2820228473 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)
2820328474 {
28204 const wanted_tag_val = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28475 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2820528476 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2820628477 const active_tag = try block.addTyOp(.get_union_tag, Type.fromInterned(union_obj.enum_tag_ty), union_byval);
2820728478 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
......@@ -28210,7 +28481,7 @@ fn unionFieldVal(
2821028481 _ = try block.addNoOp(.unreach);
2821128482 return .unreachable_value;
2821228483 }
28213 try field_ty.resolveLayout(zcu);
28484 try field_ty.resolveLayout(pt);
2821428485 return block.addStructFieldVal(union_byval, field_index, field_ty);
2821528486}
2821628487
......@@ -28224,13 +28495,14 @@ fn elemPtr(
2822428495 init: bool,
2822528496 oob_safety: bool,
2822628497) CompileError!Air.Inst.Ref {
28227 const mod = sema.mod;
28498 const pt = sema.pt;
28499 const mod = pt.zcu;
2822828500 const indexable_ptr_src = src; // TODO better source location
2822928501 const indexable_ptr_ty = sema.typeOf(indexable_ptr);
2823028502
2823128503 const indexable_ty = switch (indexable_ptr_ty.zigTypeTag(mod)) {
2823228504 .Pointer => indexable_ptr_ty.childType(mod),
28233 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(mod)}),
28505 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(pt)}),
2823428506 };
2823528507 try checkIndexable(sema, block, src, indexable_ty);
2823628508
......@@ -28241,7 +28513,7 @@ fn elemPtr(
2824128513 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2824228514 .needed_comptime_reason = "tuple field access index must be comptime-known",
2824328515 });
28244 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28516 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2824528517 break :blk try sema.tupleFieldPtr(block, src, indexable_ptr, elem_index_src, index, init);
2824628518 },
2824728519 else => {
......@@ -28267,7 +28539,8 @@ fn elemPtrOneLayerOnly(
2826728539) CompileError!Air.Inst.Ref {
2826828540 const indexable_src = src; // TODO better source location
2826928541 const indexable_ty = sema.typeOf(indexable);
28270 const mod = sema.mod;
28542 const pt = sema.pt;
28543 const mod = pt.zcu;
2827128544
2827228545 try checkIndexable(sema, block, src, indexable_ty);
2827328546
......@@ -28279,11 +28552,11 @@ fn elemPtrOneLayerOnly(
2827928552 const runtime_src = rs: {
2828028553 const ptr_val = maybe_ptr_val orelse break :rs indexable_src;
2828128554 const index_val = maybe_index_val orelse break :rs elem_index_src;
28282 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28283 const elem_ptr = try ptr_val.ptrElem(index, mod);
28555 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
28556 const elem_ptr = try ptr_val.ptrElem(index, pt);
2828428557 return Air.internedToRef(elem_ptr.toIntern());
2828528558 };
28286 const result_ty = try indexable_ty.elemPtrType(null, mod);
28559 const result_ty = try indexable_ty.elemPtrType(null, pt);
2828728560
2828828561 try sema.requireRuntimeBlock(block, src, runtime_src);
2828928562 return block.addPtrElemPtr(indexable, elem_index, result_ty);
......@@ -28297,7 +28570,7 @@ fn elemPtrOneLayerOnly(
2829728570 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2829828571 .needed_comptime_reason = "tuple field access index must be comptime-known",
2829928572 });
28300 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28573 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2830128574 break :blk try sema.tupleFieldPtr(block, indexable_src, indexable, elem_index_src, index, false);
2830228575 },
2830328576 else => unreachable, // Guaranteed by checkIndexable
......@@ -28319,7 +28592,8 @@ fn elemVal(
2831928592) CompileError!Air.Inst.Ref {
2832028593 const indexable_src = src; // TODO better source location
2832128594 const indexable_ty = sema.typeOf(indexable);
28322 const mod = sema.mod;
28595 const pt = sema.pt;
28596 const mod = pt.zcu;
2832328597
2832428598 try checkIndexable(sema, block, src, indexable_ty);
2832528599
......@@ -28337,14 +28611,14 @@ fn elemVal(
2833728611 const runtime_src = rs: {
2833828612 const indexable_val = maybe_indexable_val orelse break :rs indexable_src;
2833928613 const index_val = maybe_index_val orelse break :rs elem_index_src;
28340 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28614 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2834128615 const elem_ty = indexable_ty.elemType2(mod);
28342 const many_ptr_ty = try mod.manyConstPtrType(elem_ty);
28343 const many_ptr_val = try mod.getCoerced(indexable_val, many_ptr_ty);
28344 const elem_ptr_ty = try mod.singleConstPtrType(elem_ty);
28345 const elem_ptr_val = try many_ptr_val.ptrElem(index, mod);
28616 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);
28617 const many_ptr_val = try pt.getCoerced(indexable_val, many_ptr_ty);
28618 const elem_ptr_ty = try pt.singleConstPtrType(elem_ty);
28619 const elem_ptr_val = try many_ptr_val.ptrElem(index, pt);
2834628620 if (try sema.pointerDeref(block, indexable_src, elem_ptr_val, elem_ptr_ty)) |elem_val| {
28347 return Air.internedToRef((try mod.getCoerced(elem_val, elem_ty)).toIntern());
28621 return Air.internedToRef((try pt.getCoerced(elem_val, elem_ty)).toIntern());
2834828622 }
2834928623 break :rs indexable_src;
2835028624 };
......@@ -28358,7 +28632,7 @@ fn elemVal(
2835828632 if (inner_ty.zigTypeTag(mod) != .Array) break :arr_sent;
2835928633 const sentinel = inner_ty.sentinel(mod) orelse break :arr_sent;
2836028634 const index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index) orelse break :arr_sent;
28361 const index = try sema.usizeCast(block, src, try index_val.toUnsignedIntSema(mod));
28635 const index = try sema.usizeCast(block, src, try index_val.toUnsignedIntSema(pt));
2836228636 if (index != inner_ty.arrayLen(mod)) break :arr_sent;
2836328637 return Air.internedToRef(sentinel.toIntern());
2836428638 }
......@@ -28376,7 +28650,7 @@ fn elemVal(
2837628650 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2837728651 .needed_comptime_reason = "tuple field access index must be comptime-known",
2837828652 });
28379 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28653 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2838028654 return sema.tupleField(block, indexable_src, indexable, elem_index_src, index);
2838128655 },
2838228656 else => unreachable,
......@@ -28391,13 +28665,12 @@ fn validateRuntimeElemAccess(
2839128665 parent_ty: Type,
2839228666 parent_src: LazySrcLoc,
2839328667) CompileError!void {
28394 const mod = sema.mod;
2839528668 if (try sema.typeRequiresComptime(elem_ty)) {
2839628669 const msg = msg: {
2839728670 const msg = try sema.errMsg(
2839828671 elem_index_src,
2839928672 "values of type '{}' must be comptime-known, but index value is runtime-known",
28400 .{parent_ty.fmt(mod)},
28673 .{parent_ty.fmt(sema.pt)},
2840128674 );
2840228675 errdefer msg.destroy(sema.gpa);
2840328676
......@@ -28418,10 +28691,11 @@ fn tupleFieldPtr(
2841828691 field_index: u32,
2841928692 init: bool,
2842028693) CompileError!Air.Inst.Ref {
28421 const mod = sema.mod;
28694 const pt = sema.pt;
28695 const mod = pt.zcu;
2842228696 const tuple_ptr_ty = sema.typeOf(tuple_ptr);
2842328697 const tuple_ty = tuple_ptr_ty.childType(mod);
28424 try tuple_ty.resolveFields(mod);
28698 try tuple_ty.resolveFields(pt);
2842528699 const field_count = tuple_ty.structFieldCount(mod);
2842628700
2842728701 if (field_count == 0) {
......@@ -28435,7 +28709,7 @@ fn tupleFieldPtr(
2843528709 }
2843628710
2843728711 const field_ty = tuple_ty.structFieldType(field_index, mod);
28438 const ptr_field_ty = try mod.ptrTypeSema(.{
28712 const ptr_field_ty = try pt.ptrTypeSema(.{
2843928713 .child = field_ty.toIntern(),
2844028714 .flags = .{
2844128715 .is_const = !tuple_ptr_ty.ptrIsMutable(mod),
......@@ -28445,10 +28719,10 @@ fn tupleFieldPtr(
2844528719 });
2844628720
2844728721 if (tuple_ty.structFieldIsComptime(field_index, mod))
28448 try tuple_ty.resolveStructFieldInits(mod);
28722 try tuple_ty.resolveStructFieldInits(pt);
2844928723
28450 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_val| {
28451 return Air.internedToRef((try mod.intern(.{ .ptr = .{
28724 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_val| {
28725 return Air.internedToRef((try pt.intern(.{ .ptr = .{
2845228726 .ty = ptr_field_ty.toIntern(),
2845328727 .base_addr = .{ .comptime_field = default_val.toIntern() },
2845428728 .byte_offset = 0,
......@@ -28456,7 +28730,7 @@ fn tupleFieldPtr(
2845628730 }
2845728731
2845828732 if (try sema.resolveValue(tuple_ptr)) |tuple_ptr_val| {
28459 const field_ptr_val = try tuple_ptr_val.ptrField(field_index, mod);
28733 const field_ptr_val = try tuple_ptr_val.ptrField(field_index, pt);
2846028734 return Air.internedToRef(field_ptr_val.toIntern());
2846128735 }
2846228736
......@@ -28476,9 +28750,10 @@ fn tupleField(
2847628750 field_index_src: LazySrcLoc,
2847728751 field_index: u32,
2847828752) CompileError!Air.Inst.Ref {
28479 const mod = sema.mod;
28753 const pt = sema.pt;
28754 const mod = pt.zcu;
2848028755 const tuple_ty = sema.typeOf(tuple);
28481 try tuple_ty.resolveFields(mod);
28756 try tuple_ty.resolveFields(pt);
2848228757 const field_count = tuple_ty.structFieldCount(mod);
2848328758
2848428759 if (field_count == 0) {
......@@ -28494,20 +28769,20 @@ fn tupleField(
2849428769 const field_ty = tuple_ty.structFieldType(field_index, mod);
2849528770
2849628771 if (tuple_ty.structFieldIsComptime(field_index, mod))
28497 try tuple_ty.resolveStructFieldInits(mod);
28498 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_value| {
28772 try tuple_ty.resolveStructFieldInits(pt);
28773 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2849928774 return Air.internedToRef(default_value.toIntern()); // comptime field
2850028775 }
2850128776
2850228777 if (try sema.resolveValue(tuple)) |tuple_val| {
28503 if (tuple_val.isUndef(mod)) return mod.undefRef(field_ty);
28504 return Air.internedToRef((try tuple_val.fieldValue(mod, field_index)).toIntern());
28778 if (tuple_val.isUndef(mod)) return pt.undefRef(field_ty);
28779 return Air.internedToRef((try tuple_val.fieldValue(pt, field_index)).toIntern());
2850528780 }
2850628781
2850728782 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_src);
2850828783
2850928784 try sema.requireRuntimeBlock(block, tuple_src, null);
28510 try field_ty.resolveLayout(mod);
28785 try field_ty.resolveLayout(pt);
2851128786 return block.addStructFieldVal(tuple, field_index, field_ty);
2851228787}
2851328788
......@@ -28521,7 +28796,8 @@ fn elemValArray(
2852128796 elem_index: Air.Inst.Ref,
2852228797 oob_safety: bool,
2852328798) CompileError!Air.Inst.Ref {
28524 const mod = sema.mod;
28799 const pt = sema.pt;
28800 const mod = pt.zcu;
2852528801 const array_ty = sema.typeOf(array);
2852628802 const array_sent = array_ty.sentinel(mod);
2852728803 const array_len = array_ty.arrayLen(mod);
......@@ -28537,7 +28813,7 @@ fn elemValArray(
2853728813 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
2853828814
2853928815 if (maybe_index_val) |index_val| {
28540 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28816 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2854128817 if (array_sent) |s| {
2854228818 if (index == array_len) {
2854328819 return Air.internedToRef(s.toIntern());
......@@ -28550,11 +28826,11 @@ fn elemValArray(
2855028826 }
2855128827 if (maybe_undef_array_val) |array_val| {
2855228828 if (array_val.isUndef(mod)) {
28553 return mod.undefRef(elem_ty);
28829 return pt.undefRef(elem_ty);
2855428830 }
2855528831 if (maybe_index_val) |index_val| {
28556 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28557 const elem_val = try array_val.elemValue(mod, index);
28832 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
28833 const elem_val = try array_val.elemValue(pt, index);
2855828834 return Air.internedToRef(elem_val.toIntern());
2855928835 }
2856028836 }
......@@ -28565,7 +28841,7 @@ fn elemValArray(
2856528841 if (oob_safety and block.wantSafety()) {
2856628842 // Runtime check is only needed if unable to comptime check
2856728843 if (maybe_index_val == null) {
28568 const len_inst = try mod.intRef(Type.usize, array_len);
28844 const len_inst = try pt.intRef(Type.usize, array_len);
2856928845 const cmp_op: Air.Inst.Tag = if (array_sent != null) .cmp_lte else .cmp_lt;
2857028846 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
2857128847 }
......@@ -28589,7 +28865,8 @@ fn elemPtrArray(
2858928865 init: bool,
2859028866 oob_safety: bool,
2859128867) CompileError!Air.Inst.Ref {
28592 const mod = sema.mod;
28868 const pt = sema.pt;
28869 const mod = pt.zcu;
2859328870 const array_ptr_ty = sema.typeOf(array_ptr);
2859428871 const array_ty = array_ptr_ty.childType(mod);
2859528872 const array_sent = array_ty.sentinel(mod) != null;
......@@ -28603,7 +28880,7 @@ fn elemPtrArray(
2860328880 const maybe_undef_array_ptr_val = try sema.resolveValue(array_ptr);
2860428881 // The index must not be undefined since it can be out of bounds.
2860528882 const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
28606 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(mod));
28883 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(pt));
2860728884 if (index >= array_len_s) {
2860828885 const sentinel_label: []const u8 = if (array_sent) " +1 (sentinel)" else "";
2860928886 return sema.fail(block, elem_index_src, "index {d} outside array of length {d}{s}", .{ index, array_len, sentinel_label });
......@@ -28611,14 +28888,14 @@ fn elemPtrArray(
2861128888 break :o index;
2861228889 } else null;
2861328890
28614 const elem_ptr_ty = try array_ptr_ty.elemPtrType(offset, mod);
28891 const elem_ptr_ty = try array_ptr_ty.elemPtrType(offset, pt);
2861528892
2861628893 if (maybe_undef_array_ptr_val) |array_ptr_val| {
2861728894 if (array_ptr_val.isUndef(mod)) {
28618 return mod.undefRef(elem_ptr_ty);
28895 return pt.undefRef(elem_ptr_ty);
2861928896 }
2862028897 if (offset) |index| {
28621 const elem_ptr = try array_ptr_val.ptrElem(index, mod);
28898 const elem_ptr = try array_ptr_val.ptrElem(index, pt);
2862228899 return Air.internedToRef(elem_ptr.toIntern());
2862328900 }
2862428901 }
......@@ -28632,7 +28909,7 @@ fn elemPtrArray(
2863228909
2863328910 // Runtime check is only needed if unable to comptime check.
2863428911 if (oob_safety and block.wantSafety() and offset == null) {
28635 const len_inst = try mod.intRef(Type.usize, array_len);
28912 const len_inst = try pt.intRef(Type.usize, array_len);
2863628913 const cmp_op: Air.Inst.Tag = if (array_sent) .cmp_lte else .cmp_lt;
2863728914 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
2863828915 }
......@@ -28650,7 +28927,8 @@ fn elemValSlice(
2865028927 elem_index: Air.Inst.Ref,
2865128928 oob_safety: bool,
2865228929) CompileError!Air.Inst.Ref {
28653 const mod = sema.mod;
28930 const pt = sema.pt;
28931 const mod = pt.zcu;
2865428932 const slice_ty = sema.typeOf(slice);
2865528933 const slice_sent = slice_ty.sentinel(mod) != null;
2865628934 const elem_ty = slice_ty.elemType2(mod);
......@@ -28663,19 +28941,19 @@ fn elemValSlice(
2866328941
2866428942 if (maybe_slice_val) |slice_val| {
2866528943 runtime_src = elem_index_src;
28666 const slice_len = try slice_val.sliceLen(mod);
28944 const slice_len = try slice_val.sliceLen(pt);
2866728945 const slice_len_s = slice_len + @intFromBool(slice_sent);
2866828946 if (slice_len_s == 0) {
2866928947 return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
2867028948 }
2867128949 if (maybe_index_val) |index_val| {
28672 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28950 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2867328951 if (index >= slice_len_s) {
2867428952 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
2867528953 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
2867628954 }
28677 const elem_ptr_ty = try slice_ty.elemPtrType(index, mod);
28678 const elem_ptr_val = try slice_val.ptrElem(index, mod);
28955 const elem_ptr_ty = try slice_ty.elemPtrType(index, pt);
28956 const elem_ptr_val = try slice_val.ptrElem(index, pt);
2867928957 if (try sema.pointerDeref(block, slice_src, elem_ptr_val, elem_ptr_ty)) |elem_val| {
2868028958 return Air.internedToRef(elem_val.toIntern());
2868128959 }
......@@ -28688,7 +28966,7 @@ fn elemValSlice(
2868828966 try sema.requireRuntimeBlock(block, src, runtime_src);
2868928967 if (oob_safety and block.wantSafety()) {
2869028968 const len_inst = if (maybe_slice_val) |slice_val|
28691 try mod.intRef(Type.usize, try slice_val.sliceLen(mod))
28969 try pt.intRef(Type.usize, try slice_val.sliceLen(pt))
2869228970 else
2869328971 try block.addTyOp(.slice_len, Type.usize, slice);
2869428972 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -28707,24 +28985,25 @@ fn elemPtrSlice(
2870728985 elem_index: Air.Inst.Ref,
2870828986 oob_safety: bool,
2870928987) CompileError!Air.Inst.Ref {
28710 const mod = sema.mod;
28988 const pt = sema.pt;
28989 const mod = pt.zcu;
2871128990 const slice_ty = sema.typeOf(slice);
2871228991 const slice_sent = slice_ty.sentinel(mod) != null;
2871328992
2871428993 const maybe_undef_slice_val = try sema.resolveValue(slice);
2871528994 // The index must not be undefined since it can be out of bounds.
2871628995 const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
28717 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(mod));
28996 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(pt));
2871828997 break :o index;
2871928998 } else null;
2872028999
28721 const elem_ptr_ty = try slice_ty.elemPtrType(offset, mod);
29000 const elem_ptr_ty = try slice_ty.elemPtrType(offset, pt);
2872229001
2872329002 if (maybe_undef_slice_val) |slice_val| {
2872429003 if (slice_val.isUndef(mod)) {
28725 return mod.undefRef(elem_ptr_ty);
29004 return pt.undefRef(elem_ptr_ty);
2872629005 }
28727 const slice_len = try slice_val.sliceLen(mod);
29006 const slice_len = try slice_val.sliceLen(pt);
2872829007 const slice_len_s = slice_len + @intFromBool(slice_sent);
2872929008 if (slice_len_s == 0) {
2873029009 return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
......@@ -28734,7 +29013,7 @@ fn elemPtrSlice(
2873429013 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
2873529014 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
2873629015 }
28737 const elem_ptr_val = try slice_val.ptrElem(index, mod);
29016 const elem_ptr_val = try slice_val.ptrElem(index, pt);
2873829017 return Air.internedToRef(elem_ptr_val.toIntern());
2873929018 }
2874029019 }
......@@ -28747,7 +29026,7 @@ fn elemPtrSlice(
2874729026 const len_inst = len: {
2874829027 if (maybe_undef_slice_val) |slice_val|
2874929028 if (!slice_val.isUndef(mod))
28750 break :len try mod.intRef(Type.usize, try slice_val.sliceLen(mod));
29029 break :len try pt.intRef(Type.usize, try slice_val.sliceLen(pt));
2875129030 break :len try block.addTyOp(.slice_len, Type.usize, slice);
2875229031 };
2875329032 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -28810,11 +29089,12 @@ fn coerceExtra(
2881029089 opts: CoerceOpts,
2881129090) CoersionError!Air.Inst.Ref {
2881229091 if (dest_ty.isGenericPoison()) return inst;
28813 const zcu = sema.mod;
29092 const pt = sema.pt;
29093 const zcu = pt.zcu;
2881429094 const dest_ty_src = inst_src; // TODO better source location
28815 try dest_ty.resolveFields(zcu);
29095 try dest_ty.resolveFields(pt);
2881629096 const inst_ty = sema.typeOf(inst);
28817 try inst_ty.resolveFields(zcu);
29097 try inst_ty.resolveFields(pt);
2881829098 const target = zcu.getTarget();
2881929099 // If the types are the same, we can return the operand.
2882029100 if (dest_ty.eql(inst_ty, zcu))
......@@ -28838,12 +29118,12 @@ fn coerceExtra(
2883829118 if (maybe_inst_val) |val| {
2883929119 // undefined sets the optional bit also to undefined.
2884029120 if (val.toIntern() == .undef) {
28841 return zcu.undefRef(dest_ty);
29121 return pt.undefRef(dest_ty);
2884229122 }
2884329123
2884429124 // null to ?T
2884529125 if (val.toIntern() == .null_value) {
28846 return Air.internedToRef((try zcu.intern(.{ .opt = .{
29126 return Air.internedToRef((try pt.intern(.{ .opt = .{
2884729127 .ty = dest_ty.toIntern(),
2884829128 .val = .none,
2884929129 } })));
......@@ -29018,7 +29298,7 @@ fn coerceExtra(
2901829298 switch (dest_info.flags.size) {
2901929299 // coercion to C pointer
2902029300 .C => switch (inst_ty.zigTypeTag(zcu)) {
29021 .Null => return Air.internedToRef(try zcu.intern(.{ .ptr = .{
29301 .Null => return Air.internedToRef(try pt.intern(.{ .ptr = .{
2902229302 .ty = dest_ty.toIntern(),
2902329303 .base_addr = .int,
2902429304 .byte_offset = 0,
......@@ -29063,7 +29343,7 @@ fn coerceExtra(
2906329343 if (inst_info.flags.size == .Slice) {
2906429344 assert(dest_info.sentinel == .none);
2906529345 if (inst_info.sentinel == .none or
29066 inst_info.sentinel != (try zcu.intValue(Type.fromInterned(inst_info.child), 0)).toIntern())
29346 inst_info.sentinel != (try pt.intValue(Type.fromInterned(inst_info.child), 0)).toIntern())
2906729347 break :p;
2906829348
2906929349 const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
......@@ -29112,7 +29392,7 @@ fn coerceExtra(
2911229392 block,
2911329393 inst_src,
2911429394 "array literal requires address-of operator (&) to coerce to slice type '{}'",
29115 .{dest_ty.fmt(zcu)},
29395 .{dest_ty.fmt(pt)},
2911629396 );
2911729397 }
2911829398
......@@ -29123,10 +29403,10 @@ fn coerceExtra(
2912329403 // empty tuple to zero-length slice
2912429404 // note that this allows coercing to a mutable slice.
2912529405 if (inst_child_ty.structFieldCount(zcu) == 0) {
29126 const align_val = try dest_ty.ptrAlignmentAdvanced(zcu, .sema);
29127 return Air.internedToRef(try zcu.intern(.{ .slice = .{
29406 const align_val = try dest_ty.ptrAlignmentAdvanced(pt, .sema);
29407 return Air.internedToRef(try pt.intern(.{ .slice = .{
2912829408 .ty = dest_ty.toIntern(),
29129 .ptr = try zcu.intern(.{ .ptr = .{
29409 .ptr = try pt.intern(.{ .ptr = .{
2913029410 .ty = dest_ty.slicePtrFieldType(zcu).toIntern(),
2913129411 .base_addr = .int,
2913229412 .byte_offset = align_val.toByteUnits().?,
......@@ -29138,7 +29418,7 @@ fn coerceExtra(
2913829418 // pointer to tuple to slice
2913929419 if (!dest_info.flags.is_const) {
2914029420 const err_msg = err_msg: {
29141 const err_msg = try sema.errMsg(inst_src, "cannot cast pointer to tuple to '{}'", .{dest_ty.fmt(zcu)});
29421 const err_msg = try sema.errMsg(inst_src, "cannot cast pointer to tuple to '{}'", .{dest_ty.fmt(pt)});
2914229422 errdefer err_msg.destroy(sema.gpa);
2914329423 try sema.errNote(dest_ty_src, err_msg, "pointers to tuples can only coerce to constant pointers", .{});
2914429424 break :err_msg err_msg;
......@@ -29194,12 +29474,12 @@ fn coerceExtra(
2919429474 // comptime-known integer to other number
2919529475 if (!(try sema.intFitsInType(val, dest_ty, null))) {
2919629476 if (!opts.report_err) return error.NotCoercible;
29197 return sema.fail(block, inst_src, "type '{}' cannot represent integer value '{}'", .{ dest_ty.fmt(zcu), val.fmtValue(zcu, sema) });
29477 return sema.fail(block, inst_src, "type '{}' cannot represent integer value '{}'", .{ dest_ty.fmt(pt), val.fmtValue(pt, sema) });
2919829478 }
2919929479 return switch (zcu.intern_pool.indexToKey(val.toIntern())) {
29200 .undef => try zcu.undefRef(dest_ty),
29480 .undef => try pt.undefRef(dest_ty),
2920129481 .int => |int| Air.internedToRef(
29202 try zcu.intern_pool.getCoercedInts(zcu.gpa, int, dest_ty.toIntern()),
29482 try zcu.intern_pool.getCoercedInts(zcu.gpa, pt.tid, int, dest_ty.toIntern()),
2920329483 ),
2920429484 else => unreachable,
2920529485 };
......@@ -29228,18 +29508,18 @@ fn coerceExtra(
2922829508 .Float, .ComptimeFloat => switch (inst_ty.zigTypeTag(zcu)) {
2922929509 .ComptimeFloat => {
2923029510 const val = try sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, inst, undefined);
29231 const result_val = try val.floatCast(dest_ty, zcu);
29511 const result_val = try val.floatCast(dest_ty, pt);
2923229512 return Air.internedToRef(result_val.toIntern());
2923329513 },
2923429514 .Float => {
2923529515 if (maybe_inst_val) |val| {
29236 const result_val = try val.floatCast(dest_ty, zcu);
29237 if (!val.eql(try result_val.floatCast(inst_ty, zcu), inst_ty, zcu)) {
29516 const result_val = try val.floatCast(dest_ty, pt);
29517 if (!val.eql(try result_val.floatCast(inst_ty, pt), inst_ty, zcu)) {
2923829518 return sema.fail(
2923929519 block,
2924029520 inst_src,
2924129521 "type '{}' cannot represent float value '{}'",
29242 .{ dest_ty.fmt(zcu), val.fmtValue(zcu, sema) },
29522 .{ dest_ty.fmt(pt), val.fmtValue(pt, sema) },
2924329523 );
2924429524 }
2924529525 return Air.internedToRef(result_val.toIntern());
......@@ -29268,7 +29548,7 @@ fn coerceExtra(
2926829548 }
2926929549 break :int;
2927029550 };
29271 const result_val = try val.floatFromIntAdvanced(sema.arena, inst_ty, dest_ty, zcu, .sema);
29551 const result_val = try val.floatFromIntAdvanced(sema.arena, inst_ty, dest_ty, pt, .sema);
2927229552 // TODO implement this compile error
2927329553 //const int_again_val = try result_val.intFromFloat(sema.arena, inst_ty);
2927429554 //if (!int_again_val.eql(val, inst_ty, zcu)) {
......@@ -29276,7 +29556,7 @@ fn coerceExtra(
2927629556 // block,
2927729557 // inst_src,
2927829558 // "type '{}' cannot represent integer value '{}'",
29279 // .{ dest_ty.fmt(zcu), val },
29559 // .{ dest_ty.fmt(pt), val },
2928029560 // );
2928129561 //}
2928229562 return Air.internedToRef(result_val.toIntern());
......@@ -29290,10 +29570,10 @@ fn coerceExtra(
2929029570 const string = zcu.intern_pool.indexToKey(val.toIntern()).enum_literal;
2929129571 const field_index = dest_ty.enumFieldIndex(string, zcu) orelse {
2929229572 return sema.fail(block, inst_src, "no field named '{}' in enum '{}'", .{
29293 string.fmt(&zcu.intern_pool), dest_ty.fmt(zcu),
29573 string.fmt(&zcu.intern_pool), dest_ty.fmt(pt),
2929429574 });
2929529575 };
29296 return Air.internedToRef((try zcu.enumValueFieldIndex(dest_ty, @intCast(field_index))).toIntern());
29576 return Air.internedToRef((try pt.enumValueFieldIndex(dest_ty, @intCast(field_index))).toIntern());
2929729577 },
2929829578 .Union => blk: {
2929929579 // union to its own tag type
......@@ -29308,12 +29588,12 @@ fn coerceExtra(
2930829588 .ErrorUnion => eu: {
2930929589 if (maybe_inst_val) |inst_val| {
2931029590 switch (inst_val.toIntern()) {
29311 .undef => return zcu.undefRef(dest_ty),
29591 .undef => return pt.undefRef(dest_ty),
2931229592 else => switch (zcu.intern_pool.indexToKey(inst_val.toIntern())) {
2931329593 .error_union => |error_union| switch (error_union.val) {
2931429594 .err_name => |err_name| {
2931529595 const error_set_ty = inst_ty.errorUnionSet(zcu);
29316 const error_set_val = Air.internedToRef((try zcu.intern(.{ .err = .{
29596 const error_set_val = Air.internedToRef((try pt.intern(.{ .err = .{
2931729597 .ty = error_set_ty.toIntern(),
2931829598 .name = err_name,
2931929599 } })));
......@@ -29370,7 +29650,7 @@ fn coerceExtra(
2937029650
2937129651 if (dest_ty.sentinel(zcu)) |dest_sent| {
2937229652 const src_sent = inst_ty.sentinel(zcu) orelse break :array_to_array;
29373 if (dest_sent.toIntern() != (try zcu.getCoerced(src_sent, dest_ty.childType(zcu))).toIntern()) {
29653 if (dest_sent.toIntern() != (try pt.getCoerced(src_sent, dest_ty.childType(zcu))).toIntern()) {
2937429654 break :array_to_array;
2937529655 }
2937629656 }
......@@ -29414,7 +29694,7 @@ fn coerceExtra(
2941429694 // undefined to anything. We do this after the big switch above so that
2941529695 // special logic has a chance to run first, such as `*[N]T` to `[]T` which
2941629696 // should initialize the length field of the slice.
29417 if (maybe_inst_val) |val| if (val.toIntern() == .undef) return zcu.undefRef(dest_ty);
29697 if (maybe_inst_val) |val| if (val.toIntern() == .undef) return pt.undefRef(dest_ty);
2941829698
2941929699 if (!opts.report_err) return error.NotCoercible;
2942029700
......@@ -29434,7 +29714,7 @@ fn coerceExtra(
2943429714 }
2943529715
2943629716 const msg = msg: {
29437 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(zcu), inst_ty.fmt(zcu) });
29717 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(pt), inst_ty.fmt(pt) });
2943829718 errdefer msg.destroy(sema.gpa);
2943929719
2944029720 // E!T to T
......@@ -29486,7 +29766,7 @@ fn coerceInMemory(
2948629766 val: Value,
2948729767 dst_ty: Type,
2948829768) CompileError!Air.Inst.Ref {
29489 return Air.internedToRef((try sema.mod.getCoerced(val, dst_ty)).toIntern());
29769 return Air.internedToRef((try sema.pt.getCoerced(val, dst_ty)).toIntern());
2949029770}
2949129771
2949229772const InMemoryCoercionResult = union(enum) {
......@@ -29607,7 +29887,7 @@ const InMemoryCoercionResult = union(enum) {
2960729887 }
2960829888
2960929889 fn report(res: *const InMemoryCoercionResult, sema: *Sema, src: LazySrcLoc, msg: *Module.ErrorMsg) !void {
29610 const mod = sema.mod;
29890 const pt = sema.pt;
2961129891 var cur = res;
2961229892 while (true) switch (cur.*) {
2961329893 .ok => unreachable,
......@@ -29624,7 +29904,7 @@ const InMemoryCoercionResult = union(enum) {
2962429904 },
2962529905 .error_union_payload => |pair| {
2962629906 try sema.errNote(src, msg, "error union payload '{}' cannot cast into error union payload '{}'", .{
29627 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29907 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2962829908 });
2962929909 cur = pair.child;
2963029910 },
......@@ -29637,18 +29917,18 @@ const InMemoryCoercionResult = union(enum) {
2963729917 .array_sentinel => |sentinel| {
2963829918 if (sentinel.actual.toIntern() != .unreachable_value) {
2963929919 try sema.errNote(src, msg, "array sentinel '{}' cannot cast into array sentinel '{}'", .{
29640 sentinel.actual.fmtValue(mod, sema), sentinel.wanted.fmtValue(mod, sema),
29920 sentinel.actual.fmtValue(pt, sema), sentinel.wanted.fmtValue(pt, sema),
2964129921 });
2964229922 } else {
2964329923 try sema.errNote(src, msg, "destination array requires '{}' sentinel", .{
29644 sentinel.wanted.fmtValue(mod, sema),
29924 sentinel.wanted.fmtValue(pt, sema),
2964529925 });
2964629926 }
2964729927 break;
2964829928 },
2964929929 .array_elem => |pair| {
2965029930 try sema.errNote(src, msg, "array element type '{}' cannot cast into array element type '{}'", .{
29651 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29931 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2965229932 });
2965329933 cur = pair.child;
2965429934 },
......@@ -29660,19 +29940,19 @@ const InMemoryCoercionResult = union(enum) {
2966029940 },
2966129941 .vector_elem => |pair| {
2966229942 try sema.errNote(src, msg, "vector element type '{}' cannot cast into vector element type '{}'", .{
29663 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29943 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2966429944 });
2966529945 cur = pair.child;
2966629946 },
2966729947 .optional_shape => |pair| {
2966829948 try sema.errNote(src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
29669 pair.actual.optionalChild(mod).fmt(mod), pair.wanted.optionalChild(mod).fmt(mod),
29949 pair.actual.optionalChild(pt.zcu).fmt(pt), pair.wanted.optionalChild(pt.zcu).fmt(pt),
2967029950 });
2967129951 break;
2967229952 },
2967329953 .optional_child => |pair| {
2967429954 try sema.errNote(src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
29675 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29955 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2967629956 });
2967729957 cur = pair.child;
2967829958 },
......@@ -29682,7 +29962,7 @@ const InMemoryCoercionResult = union(enum) {
2968229962 },
2968329963 .missing_error => |missing_errors| {
2968429964 for (missing_errors) |err| {
29685 try sema.errNote(src, msg, "'error.{}' not a member of destination error set", .{err.fmt(&mod.intern_pool)});
29965 try sema.errNote(src, msg, "'error.{}' not a member of destination error set", .{err.fmt(&pt.zcu.intern_pool)});
2968629966 }
2968729967 break;
2968829968 },
......@@ -29736,7 +30016,7 @@ const InMemoryCoercionResult = union(enum) {
2973630016 },
2973730017 .fn_param => |param| {
2973830018 try sema.errNote(src, msg, "parameter {d} '{}' cannot cast into '{}'", .{
29739 param.index, param.actual.fmt(mod), param.wanted.fmt(mod),
30019 param.index, param.actual.fmt(pt), param.wanted.fmt(pt),
2974030020 });
2974130021 cur = param.child;
2974230022 },
......@@ -29746,13 +30026,13 @@ const InMemoryCoercionResult = union(enum) {
2974630026 },
2974730027 .fn_return_type => |pair| {
2974830028 try sema.errNote(src, msg, "return type '{}' cannot cast into return type '{}'", .{
29749 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30029 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2975030030 });
2975130031 cur = pair.child;
2975230032 },
2975330033 .ptr_child => |pair| {
2975430034 try sema.errNote(src, msg, "pointer type child '{}' cannot cast into pointer type child '{}'", .{
29755 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30035 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2975630036 });
2975730037 cur = pair.child;
2975830038 },
......@@ -29763,11 +30043,11 @@ const InMemoryCoercionResult = union(enum) {
2976330043 .ptr_sentinel => |sentinel| {
2976430044 if (sentinel.actual.toIntern() != .unreachable_value) {
2976530045 try sema.errNote(src, msg, "pointer sentinel '{}' cannot cast into pointer sentinel '{}'", .{
29766 sentinel.actual.fmtValue(mod, sema), sentinel.wanted.fmtValue(mod, sema),
30046 sentinel.actual.fmtValue(pt, sema), sentinel.wanted.fmtValue(pt, sema),
2976730047 });
2976830048 } else {
2976930049 try sema.errNote(src, msg, "destination pointer requires '{}' sentinel", .{
29770 sentinel.wanted.fmtValue(mod, sema),
30050 sentinel.wanted.fmtValue(pt, sema),
2977130051 });
2977230052 }
2977330053 break;
......@@ -29787,15 +30067,15 @@ const InMemoryCoercionResult = union(enum) {
2978730067 break;
2978830068 },
2978930069 .ptr_allowzero => |pair| {
29790 const wanted_allow_zero = pair.wanted.ptrAllowsZero(mod);
29791 const actual_allow_zero = pair.actual.ptrAllowsZero(mod);
30070 const wanted_allow_zero = pair.wanted.ptrAllowsZero(pt.zcu);
30071 const actual_allow_zero = pair.actual.ptrAllowsZero(pt.zcu);
2979230072 if (actual_allow_zero and !wanted_allow_zero) {
2979330073 try sema.errNote(src, msg, "'{}' could have null values which are illegal in type '{}'", .{
29794 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30074 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2979530075 });
2979630076 } else {
2979730077 try sema.errNote(src, msg, "mutable '{}' allows illegal null values stored to type '{}'", .{
29798 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30078 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2979930079 });
2980030080 }
2980130081 break;
......@@ -29821,13 +30101,13 @@ const InMemoryCoercionResult = union(enum) {
2982130101 },
2982230102 .double_ptr_to_anyopaque => |pair| {
2982330103 try sema.errNote(src, msg, "cannot implicitly cast double pointer '{}' to anyopaque pointer '{}'", .{
29824 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30104 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2982530105 });
2982630106 break;
2982730107 },
2982830108 .slice_to_anyopaque => |pair| {
2982930109 try sema.errNote(src, msg, "cannot implicitly cast slice '{}' to anyopaque pointer '{}'", .{
29830 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30110 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2983130111 });
2983230112 try sema.errNote(src, msg, "consider using '.ptr'", .{});
2983330113 break;
......@@ -29864,7 +30144,8 @@ pub fn coerceInMemoryAllowed(
2986430144 dest_src: LazySrcLoc,
2986530145 src_src: LazySrcLoc,
2986630146) CompileError!InMemoryCoercionResult {
29867 const mod = sema.mod;
30147 const pt = sema.pt;
30148 const mod = pt.zcu;
2986830149
2986930150 if (dest_ty.eql(src_ty, mod))
2987030151 return .ok;
......@@ -29968,7 +30249,7 @@ pub fn coerceInMemoryAllowed(
2996830249 (src_info.sentinel != null and
2996930250 dest_info.sentinel != null and
2997030251 dest_info.sentinel.?.eql(
29971 try mod.getCoerced(src_info.sentinel.?, dest_info.elem_type),
30252 try pt.getCoerced(src_info.sentinel.?, dest_info.elem_type),
2997230253 dest_info.elem_type,
2997330254 mod,
2997430255 ));
......@@ -30045,8 +30326,8 @@ pub fn coerceInMemoryAllowed(
3004530326 // The memory layout of @Vector(N, iM) is the same as the integer type i(N*M),
3004630327 // that is to say, the padding bits are not in the same place as the array [N]iM.
3004730328 // If there's no padding, the bitcast is possible.
30048 const elem_bit_size = dest_elem_ty.bitSize(mod);
30049 const elem_abi_byte_size = dest_elem_ty.abiSize(mod);
30329 const elem_bit_size = dest_elem_ty.bitSize(pt);
30330 const elem_abi_byte_size = dest_elem_ty.abiSize(pt);
3005030331 if (elem_abi_byte_size * 8 == elem_bit_size)
3005130332 return .ok;
3005230333 }
......@@ -30081,7 +30362,7 @@ pub fn coerceInMemoryAllowed(
3008130362 const field_count = dest_ty.structFieldCount(mod);
3008230363 for (0..field_count) |field_idx| {
3008330364 if (dest_ty.structFieldIsComptime(field_idx, mod) != src_ty.structFieldIsComptime(field_idx, mod)) break :tuple;
30084 if (dest_ty.structFieldAlign(field_idx, mod) != src_ty.structFieldAlign(field_idx, mod)) break :tuple;
30365 if (dest_ty.structFieldAlign(field_idx, pt) != src_ty.structFieldAlign(field_idx, pt)) break :tuple;
3008530366 const dest_field_ty = dest_ty.structFieldType(field_idx, mod);
3008630367 const src_field_ty = src_ty.structFieldType(field_idx, mod);
3008730368 const field = try sema.coerceInMemoryAllowed(block, dest_field_ty, src_field_ty, dest_is_mut, target, dest_src, src_src);
......@@ -30104,7 +30385,8 @@ fn coerceInMemoryAllowedErrorSets(
3010430385 dest_src: LazySrcLoc,
3010530386 src_src: LazySrcLoc,
3010630387) !InMemoryCoercionResult {
30107 const mod = sema.mod;
30388 const pt = sema.pt;
30389 const mod = pt.zcu;
3010830390 const gpa = sema.gpa;
3010930391 const ip = &mod.intern_pool;
3011030392
......@@ -30202,7 +30484,8 @@ fn coerceInMemoryAllowedFns(
3020230484 dest_src: LazySrcLoc,
3020330485 src_src: LazySrcLoc,
3020430486) !InMemoryCoercionResult {
30205 const mod = sema.mod;
30487 const pt = sema.pt;
30488 const mod = pt.zcu;
3020630489 const ip = &mod.intern_pool;
3020730490
3020830491 const dest_info = mod.typeToFunc(dest_ty).?;
......@@ -30303,7 +30586,8 @@ fn coerceInMemoryAllowedPtrs(
3030330586 dest_src: LazySrcLoc,
3030430587 src_src: LazySrcLoc,
3030530588) !InMemoryCoercionResult {
30306 const zcu = sema.mod;
30589 const pt = sema.pt;
30590 const zcu = pt.zcu;
3030730591 const dest_info = dest_ptr_ty.ptrInfo(zcu);
3030830592 const src_info = src_ptr_ty.ptrInfo(zcu);
3030930593
......@@ -30381,7 +30665,7 @@ fn coerceInMemoryAllowedPtrs(
3038130665
3038230666 const ok_sent = dest_info.sentinel == .none or src_info.flags.size == .C or
3038330667 (src_info.sentinel != .none and
30384 dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, src_info.sentinel, dest_info.child));
30668 dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child));
3038530669 if (!ok_sent) {
3038630670 return InMemoryCoercionResult{ .ptr_sentinel = .{
3038730671 .actual = switch (src_info.sentinel) {
......@@ -30432,7 +30716,8 @@ fn coerceVarArgParam(
3043230716) !Air.Inst.Ref {
3043330717 if (block.is_typeof) return inst;
3043430718
30435 const mod = sema.mod;
30719 const pt = sema.pt;
30720 const mod = pt.zcu;
3043630721 const uncasted_ty = sema.typeOf(inst);
3043730722 const coerced = switch (uncasted_ty.zigTypeTag(mod)) {
3043830723 // TODO consider casting to c_int/f64 if they fit
......@@ -30449,9 +30734,9 @@ fn coerceVarArgParam(
3044930734 },
3045030735 .Array => return sema.fail(block, inst_src, "arrays must be passed by reference to variadic function", .{}),
3045130736 .Float => float: {
30452 const target = sema.mod.getTarget();
30737 const target = mod.getTarget();
3045330738 const double_bits = target.c_type_bit_size(.double);
30454 const inst_bits = uncasted_ty.floatBits(sema.mod.getTarget());
30739 const inst_bits = uncasted_ty.floatBits(target);
3045530740 if (inst_bits >= double_bits) break :float inst;
3045630741 switch (double_bits) {
3045730742 32 => break :float try sema.coerce(block, Type.f32, inst, inst_src),
......@@ -30461,7 +30746,7 @@ fn coerceVarArgParam(
3046130746 },
3046230747 else => if (uncasted_ty.isAbiInt(mod)) int: {
3046330748 if (!try sema.validateExternType(uncasted_ty, .param_ty)) break :int inst;
30464 const target = sema.mod.getTarget();
30749 const target = mod.getTarget();
3046530750 const uncasted_info = uncasted_ty.intInfo(mod);
3046630751 if (uncasted_info.bits <= target.c_type_bit_size(switch (uncasted_info.signedness) {
3046730752 .signed => .int,
......@@ -30491,7 +30776,7 @@ fn coerceVarArgParam(
3049130776 const coerced_ty = sema.typeOf(coerced);
3049230777 if (!try sema.validateExternType(coerced_ty, .param_ty)) {
3049330778 const msg = msg: {
30494 const msg = try sema.errMsg(inst_src, "cannot pass '{}' to variadic function", .{coerced_ty.fmt(sema.mod)});
30779 const msg = try sema.errMsg(inst_src, "cannot pass '{}' to variadic function", .{coerced_ty.fmt(pt)});
3049530780 errdefer msg.destroy(sema.gpa);
3049630781
3049730782 try sema.explainWhyTypeIsNotExtern(msg, inst_src, coerced_ty, .param_ty);
......@@ -30526,7 +30811,8 @@ fn storePtr2(
3052630811 operand_src: LazySrcLoc,
3052730812 air_tag: Air.Inst.Tag,
3052830813) CompileError!void {
30529 const mod = sema.mod;
30814 const pt = sema.pt;
30815 const mod = pt.zcu;
3053030816 const ptr_ty = sema.typeOf(ptr);
3053130817 if (ptr_ty.isConstPtr(mod))
3053230818 return sema.fail(block, ptr_src, "cannot assign to constant", .{});
......@@ -30548,7 +30834,7 @@ fn storePtr2(
3054830834 while (i < field_count) : (i += 1) {
3054930835 const elem_src = operand_src; // TODO better source location
3055030836 const elem = try sema.tupleField(block, operand_src, uncasted_operand, elem_src, i);
30551 const elem_index = try mod.intRef(Type.usize, i);
30837 const elem_index = try pt.intRef(Type.usize, i);
3055230838 const elem_ptr = try sema.elemPtr(block, ptr_src, ptr, elem_index, elem_src, false, true);
3055330839 try sema.storePtr2(block, src, elem_ptr, elem_src, elem, elem_src, .store);
3055430840 }
......@@ -30620,7 +30906,7 @@ fn storePtr2(
3062030906 return;
3062130907 }
3062230908 return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
30623 ptr_ty.fmt(sema.mod),
30909 ptr_ty.fmt(pt),
3062430910 });
3062530911 }
3062630912
......@@ -30734,7 +31020,8 @@ fn markMaybeComptimeAllocRuntime(sema: *Sema, block: *Block, alloc_inst: Air.Ins
3073431020/// pointer. Only if the final element type matches the vector element type, and the
3073531021/// lengths match.
3073631022fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
30737 const mod = sema.mod;
31023 const pt = sema.pt;
31024 const mod = pt.zcu;
3073831025 const array_ty = sema.typeOf(ptr).childType(mod);
3073931026 if (array_ty.zigTypeTag(mod) != .Array) return null;
3074031027 var ptr_ref = ptr;
......@@ -30751,7 +31038,7 @@ fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
3075131038
3075231039 // We have a pointer-to-array and a pointer-to-vector. If the elements and
3075331040 // lengths match, return the result.
30754 if (array_ty.childType(mod).eql(vector_ty.childType(mod), sema.mod) and
31041 if (array_ty.childType(mod).eql(vector_ty.childType(mod), mod) and
3075531042 array_ty.arrayLen(mod) == vector_ty.vectorLen(mod))
3075631043 {
3075731044 return ptr_ref;
......@@ -30770,17 +31057,18 @@ fn storePtrVal(
3077031057 operand_val: Value,
3077131058 operand_ty: Type,
3077231059) !void {
30773 const zcu = sema.mod;
31060 const pt = sema.pt;
31061 const zcu = pt.zcu;
3077431062 const ip = &zcu.intern_pool;
3077531063 // TODO: audit use sites to eliminate this coercion
30776 const coerced_operand_val = try zcu.getCoerced(operand_val, operand_ty);
31064 const coerced_operand_val = try pt.getCoerced(operand_val, operand_ty);
3077731065 // TODO: audit use sites to eliminate this coercion
30778 const ptr_ty = try zcu.ptrType(info: {
31066 const ptr_ty = try pt.ptrType(info: {
3077931067 var info = ptr_val.typeOf(zcu).ptrInfo(zcu);
3078031068 info.child = operand_ty.toIntern();
3078131069 break :info info;
3078231070 });
30783 const coerced_ptr_val = try zcu.getCoerced(ptr_val, ptr_ty);
31071 const coerced_ptr_val = try pt.getCoerced(ptr_val, ptr_ty);
3078431072
3078531073 switch (try sema.storeComptimePtr(block, src, coerced_ptr_val, coerced_operand_val)) {
3078631074 .success => {},
......@@ -30800,13 +31088,13 @@ fn storePtrVal(
3080031088 block,
3080131089 src,
3080231090 "comptime dereference requires '{}' to have a well-defined layout",
30803 .{ty.fmt(zcu)},
31091 .{ty.fmt(pt)},
3080431092 ),
3080531093 .out_of_bounds => |ty| return sema.fail(
3080631094 block,
3080731095 src,
3080831096 "dereference of '{}' exceeds bounds of containing decl of type '{}'",
30809 .{ ptr_ty.fmt(zcu), ty.fmt(zcu) },
31097 .{ ptr_ty.fmt(pt), ty.fmt(pt) },
3081031098 ),
3081131099 .exceeds_host_size => return sema.fail(block, src, "bit-pointer target exceeds host size", .{}),
3081231100 }
......@@ -30820,31 +31108,32 @@ fn bitCast(
3082031108 inst_src: LazySrcLoc,
3082131109 operand_src: ?LazySrcLoc,
3082231110) CompileError!Air.Inst.Ref {
30823 const zcu = sema.mod;
30824 try dest_ty.resolveLayout(zcu);
31111 const pt = sema.pt;
31112 const zcu = pt.zcu;
31113 try dest_ty.resolveLayout(pt);
3082531114
3082631115 const old_ty = sema.typeOf(inst);
30827 try old_ty.resolveLayout(zcu);
31116 try old_ty.resolveLayout(pt);
3082831117
30829 const dest_bits = dest_ty.bitSize(zcu);
30830 const old_bits = old_ty.bitSize(zcu);
31118 const dest_bits = dest_ty.bitSize(pt);
31119 const old_bits = old_ty.bitSize(pt);
3083131120
3083231121 if (old_bits != dest_bits) {
3083331122 return sema.fail(block, inst_src, "@bitCast size mismatch: destination type '{}' has {d} bits but source type '{}' has {d} bits", .{
30834 dest_ty.fmt(zcu),
31123 dest_ty.fmt(pt),
3083531124 dest_bits,
30836 old_ty.fmt(zcu),
31125 old_ty.fmt(pt),
3083731126 old_bits,
3083831127 });
3083931128 }
3084031129
3084131130 if (try sema.resolveValue(inst)) |val| {
3084231131 if (val.isUndef(zcu))
30843 return zcu.undefRef(dest_ty);
31132 return pt.undefRef(dest_ty);
3084431133 if (old_ty.zigTypeTag(zcu) == .ErrorSet and dest_ty.zigTypeTag(zcu) == .ErrorSet) {
3084531134 // Special case: we sometimes call `bitCast` on error set values, but they
3084631135 // don't have a well-defined layout, so we can't use `bitCastVal` on them.
30847 return Air.internedToRef((try zcu.getCoerced(val, dest_ty)).toIntern());
31136 return Air.internedToRef((try pt.getCoerced(val, dest_ty)).toIntern());
3084831137 }
3084931138 if (try sema.bitCastVal(val, dest_ty, 0, 0, 0)) |result_val| {
3085031139 return Air.internedToRef(result_val.toIntern());
......@@ -30862,16 +31151,17 @@ fn coerceArrayPtrToSlice(
3086231151 inst: Air.Inst.Ref,
3086331152 inst_src: LazySrcLoc,
3086431153) CompileError!Air.Inst.Ref {
30865 const mod = sema.mod;
31154 const pt = sema.pt;
31155 const mod = pt.zcu;
3086631156 if (try sema.resolveValue(inst)) |val| {
3086731157 const ptr_array_ty = sema.typeOf(inst);
3086831158 const array_ty = ptr_array_ty.childType(mod);
3086931159 const slice_ptr_ty = dest_ty.slicePtrFieldType(mod);
30870 const slice_ptr = try mod.getCoerced(val, slice_ptr_ty);
30871 const slice_val = try mod.intern(.{ .slice = .{
31160 const slice_ptr = try pt.getCoerced(val, slice_ptr_ty);
31161 const slice_val = try pt.intern(.{ .slice = .{
3087231162 .ty = dest_ty.toIntern(),
3087331163 .ptr = slice_ptr.toIntern(),
30874 .len = (try mod.intValue(Type.usize, array_ty.arrayLen(mod))).toIntern(),
31164 .len = (try pt.intValue(Type.usize, array_ty.arrayLen(mod))).toIntern(),
3087531165 } });
3087631166 return Air.internedToRef(slice_val);
3087731167 }
......@@ -30880,7 +31170,8 @@ fn coerceArrayPtrToSlice(
3088031170}
3088131171
3088231172fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_result: *InMemoryCoercionResult) bool {
30883 const mod = sema.mod;
31173 const pt = sema.pt;
31174 const mod = pt.zcu;
3088431175 const dest_info = dest_ty.ptrInfo(mod);
3088531176 const inst_info = inst_ty.ptrInfo(mod);
3088631177 const len0 = (Type.fromInterned(inst_info.child).zigTypeTag(mod) == .Array and (Type.fromInterned(inst_info.child).arrayLenIncludingSentinel(mod) == 0 or
......@@ -30913,12 +31204,12 @@ fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_resul
3091331204 const inst_align = if (inst_info.flags.alignment != .none)
3091431205 inst_info.flags.alignment
3091531206 else
30916 Type.fromInterned(inst_info.child).abiAlignment(mod);
31207 Type.fromInterned(inst_info.child).abiAlignment(pt);
3091731208
3091831209 const dest_align = if (dest_info.flags.alignment != .none)
3091931210 dest_info.flags.alignment
3092031211 else
30921 Type.fromInterned(dest_info.child).abiAlignment(mod);
31212 Type.fromInterned(dest_info.child).abiAlignment(pt);
3092231213
3092331214 if (dest_align.compare(.gt, inst_align)) {
3092431215 in_memory_result.* = .{ .ptr_alignment = .{
......@@ -30937,15 +31228,16 @@ fn coerceCompatiblePtrs(
3093731228 inst: Air.Inst.Ref,
3093831229 inst_src: LazySrcLoc,
3093931230) !Air.Inst.Ref {
30940 const mod = sema.mod;
31231 const pt = sema.pt;
31232 const mod = pt.zcu;
3094131233 const inst_ty = sema.typeOf(inst);
3094231234 if (try sema.resolveValue(inst)) |val| {
3094331235 if (!val.isUndef(mod) and val.isNull(mod) and !dest_ty.isAllowzeroPtr(mod)) {
30944 return sema.fail(block, inst_src, "null pointer casted to type '{}'", .{dest_ty.fmt(sema.mod)});
31236 return sema.fail(block, inst_src, "null pointer casted to type '{}'", .{dest_ty.fmt(pt)});
3094531237 }
3094631238 // The comptime Value representation is compatible with both types.
3094731239 return Air.internedToRef(
30948 (try mod.getCoerced(val, dest_ty)).toIntern(),
31240 (try pt.getCoerced(val, dest_ty)).toIntern(),
3094931241 );
3095031242 }
3095131243 try sema.requireRuntimeBlock(block, inst_src, null);
......@@ -30979,14 +31271,15 @@ fn coerceEnumToUnion(
3097931271 inst: Air.Inst.Ref,
3098031272 inst_src: LazySrcLoc,
3098131273) !Air.Inst.Ref {
30982 const mod = sema.mod;
31274 const pt = sema.pt;
31275 const mod = pt.zcu;
3098331276 const ip = &mod.intern_pool;
3098431277 const inst_ty = sema.typeOf(inst);
3098531278
3098631279 const tag_ty = union_ty.unionTagType(mod) orelse {
3098731280 const msg = msg: {
3098831281 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
30989 union_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
31282 union_ty.fmt(pt), inst_ty.fmt(pt),
3099031283 });
3099131284 errdefer msg.destroy(sema.gpa);
3099231285 try sema.errNote(union_ty_src, msg, "cannot coerce enum to untagged union", .{});
......@@ -30998,15 +31291,15 @@ fn coerceEnumToUnion(
3099831291
3099931292 const enum_tag = try sema.coerce(block, tag_ty, inst, inst_src);
3100031293 if (try sema.resolveDefinedValue(block, inst_src, enum_tag)) |val| {
31001 const field_index = union_ty.unionTagFieldIndex(val, sema.mod) orelse {
31294 const field_index = union_ty.unionTagFieldIndex(val, pt.zcu) orelse {
3100231295 return sema.fail(block, inst_src, "union '{}' has no tag with value '{}'", .{
31003 union_ty.fmt(sema.mod), val.fmtValue(sema.mod, sema),
31296 union_ty.fmt(pt), val.fmtValue(pt, sema),
3100431297 });
3100531298 };
3100631299
3100731300 const union_obj = mod.typeToUnion(union_ty).?;
3100831301 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
31009 try field_ty.resolveFields(mod);
31302 try field_ty.resolveFields(pt);
3101031303 if (field_ty.zigTypeTag(mod) == .NoReturn) {
3101131304 const msg = msg: {
3101231305 const msg = try sema.errMsg(inst_src, "cannot initialize 'noreturn' field of union", .{});
......@@ -31025,8 +31318,8 @@ fn coerceEnumToUnion(
3102531318 const msg = msg: {
3102631319 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];
3102731320 const msg = try sema.errMsg(inst_src, "coercion from enum '{}' to union '{}' must initialize '{}' field '{}'", .{
31028 inst_ty.fmt(sema.mod), union_ty.fmt(sema.mod),
31029 field_ty.fmt(sema.mod), field_name.fmt(ip),
31321 inst_ty.fmt(pt), union_ty.fmt(pt),
31322 field_ty.fmt(pt), field_name.fmt(ip),
3103031323 });
3103131324 errdefer msg.destroy(sema.gpa);
3103231325
......@@ -31039,7 +31332,7 @@ fn coerceEnumToUnion(
3103931332 return sema.failWithOwnedErrorMsg(block, msg);
3104031333 };
3104131334
31042 return Air.internedToRef((try mod.unionValue(union_ty, val, opv)).toIntern());
31335 return Air.internedToRef((try pt.unionValue(union_ty, val, opv)).toIntern());
3104331336 }
3104431337
3104531338 try sema.requireRuntimeBlock(block, inst_src, null);
......@@ -31047,7 +31340,7 @@ fn coerceEnumToUnion(
3104731340 if (tag_ty.isNonexhaustiveEnum(mod)) {
3104831341 const msg = msg: {
3104931342 const msg = try sema.errMsg(inst_src, "runtime coercion to union '{}' from non-exhaustive enum", .{
31050 union_ty.fmt(sema.mod),
31343 union_ty.fmt(pt),
3105131344 });
3105231345 errdefer msg.destroy(sema.gpa);
3105331346 try sema.addDeclaredHereNote(msg, tag_ty);
......@@ -31066,7 +31359,7 @@ fn coerceEnumToUnion(
3106631359 const err_msg = msg orelse try sema.errMsg(
3106731360 inst_src,
3106831361 "runtime coercion from enum '{}' to union '{}' which has a 'noreturn' field",
31069 .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
31362 .{ tag_ty.fmt(pt), union_ty.fmt(pt) },
3107031363 );
3107131364 msg = err_msg;
3107231365
......@@ -31081,7 +31374,7 @@ fn coerceEnumToUnion(
3108131374 }
3108231375
3108331376 // If the union has all fields 0 bits, the union value is just the enum value.
31084 if (union_ty.unionHasAllZeroBitFieldTypes(mod)) {
31377 if (union_ty.unionHasAllZeroBitFieldTypes(pt)) {
3108531378 return block.addBitCast(union_ty, enum_tag);
3108631379 }
3108731380
......@@ -31089,7 +31382,7 @@ fn coerceEnumToUnion(
3108931382 const msg = try sema.errMsg(
3109031383 inst_src,
3109131384 "runtime coercion from enum '{}' to union '{}' which has non-void fields",
31092 .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
31385 .{ tag_ty.fmt(pt), union_ty.fmt(pt) },
3109331386 );
3109431387 errdefer msg.destroy(sema.gpa);
3109531388
......@@ -31099,7 +31392,7 @@ fn coerceEnumToUnion(
3109931392 if (!(try sema.typeHasRuntimeBits(field_ty))) continue;
3110031393 try sema.addFieldErrNote(union_ty, field_index, msg, "field '{}' has type '{}'", .{
3110131394 field_name.fmt(ip),
31102 field_ty.fmt(sema.mod),
31395 field_ty.fmt(pt),
3110331396 });
3110431397 }
3110531398 try sema.addDeclaredHereNote(msg, union_ty);
......@@ -31116,7 +31409,8 @@ fn coerceAnonStructToUnion(
3111631409 inst: Air.Inst.Ref,
3111731410 inst_src: LazySrcLoc,
3111831411) !Air.Inst.Ref {
31119 const mod = sema.mod;
31412 const pt = sema.pt;
31413 const mod = pt.zcu;
3112031414 const ip = &mod.intern_pool;
3112131415 const inst_ty = sema.typeOf(inst);
3112231416 const field_info: union(enum) {
......@@ -31174,7 +31468,8 @@ fn coerceAnonStructToUnionPtrs(
3117431468 ptr_anon_struct: Air.Inst.Ref,
3117531469 anon_struct_src: LazySrcLoc,
3117631470) !Air.Inst.Ref {
31177 const mod = sema.mod;
31471 const pt = sema.pt;
31472 const mod = pt.zcu;
3117831473 const union_ty = ptr_union_ty.childType(mod);
3117931474 const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
3118031475 const union_inst = try sema.coerceAnonStructToUnion(block, union_ty, union_ty_src, anon_struct, anon_struct_src);
......@@ -31189,7 +31484,8 @@ fn coerceAnonStructToStructPtrs(
3118931484 ptr_anon_struct: Air.Inst.Ref,
3119031485 anon_struct_src: LazySrcLoc,
3119131486) !Air.Inst.Ref {
31192 const mod = sema.mod;
31487 const pt = sema.pt;
31488 const mod = pt.zcu;
3119331489 const struct_ty = ptr_struct_ty.childType(mod);
3119431490 const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
3119531491 const struct_inst = try sema.coerceTupleToStruct(block, struct_ty, anon_struct, anon_struct_src);
......@@ -31205,7 +31501,8 @@ fn coerceArrayLike(
3120531501 inst: Air.Inst.Ref,
3120631502 inst_src: LazySrcLoc,
3120731503) !Air.Inst.Ref {
31208 const mod = sema.mod;
31504 const pt = sema.pt;
31505 const mod = pt.zcu;
3120931506 const inst_ty = sema.typeOf(inst);
3121031507 const target = mod.getTarget();
3121131508
......@@ -31226,7 +31523,7 @@ fn coerceArrayLike(
3122631523 if (dest_len != inst_len) {
3122731524 const msg = msg: {
3122831525 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
31229 dest_ty.fmt(mod), inst_ty.fmt(mod),
31526 dest_ty.fmt(pt), inst_ty.fmt(pt),
3123031527 });
3123131528 errdefer msg.destroy(sema.gpa);
3123231529 try sema.errNote(dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -31270,7 +31567,7 @@ fn coerceArrayLike(
3127031567 var runtime_src: ?LazySrcLoc = null;
3127131568
3127231569 for (element_vals, element_refs, 0..) |*val, *ref, i| {
31273 const index_ref = Air.internedToRef((try mod.intValue(Type.usize, i)).toIntern());
31570 const index_ref = Air.internedToRef((try pt.intValue(Type.usize, i)).toIntern());
3127431571 const src = inst_src; // TODO better source location
3127531572 const elem_src = inst_src; // TODO better source location
3127631573 const elem_ref = try sema.elemValArray(block, src, inst_src, inst, elem_src, index_ref, true);
......@@ -31290,7 +31587,7 @@ fn coerceArrayLike(
3129031587 return block.addAggregateInit(dest_ty, element_refs);
3129131588 }
3129231589
31293 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31590 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3129431591 .ty = dest_ty.toIntern(),
3129531592 .storage = .{ .elems = element_vals },
3129631593 } })));
......@@ -31305,7 +31602,8 @@ fn coerceTupleToArray(
3130531602 inst: Air.Inst.Ref,
3130631603 inst_src: LazySrcLoc,
3130731604) !Air.Inst.Ref {
31308 const mod = sema.mod;
31605 const pt = sema.pt;
31606 const mod = pt.zcu;
3130931607 const inst_ty = sema.typeOf(inst);
3131031608 const inst_len = inst_ty.arrayLen(mod);
3131131609 const dest_len = dest_ty.arrayLen(mod);
......@@ -31313,7 +31611,7 @@ fn coerceTupleToArray(
3131331611 if (dest_len != inst_len) {
3131431612 const msg = msg: {
3131531613 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
31316 dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
31614 dest_ty.fmt(pt), inst_ty.fmt(pt),
3131731615 });
3131831616 errdefer msg.destroy(sema.gpa);
3131931617 try sema.errNote(dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -31355,7 +31653,7 @@ fn coerceTupleToArray(
3135531653 return block.addAggregateInit(dest_ty, element_refs);
3135631654 }
3135731655
31358 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31656 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3135931657 .ty = dest_ty.toIntern(),
3136031658 .storage = .{ .elems = element_vals },
3136131659 } })));
......@@ -31370,11 +31668,12 @@ fn coerceTupleToSlicePtrs(
3137031668 ptr_tuple: Air.Inst.Ref,
3137131669 tuple_src: LazySrcLoc,
3137231670) !Air.Inst.Ref {
31373 const mod = sema.mod;
31671 const pt = sema.pt;
31672 const mod = pt.zcu;
3137431673 const tuple_ty = sema.typeOf(ptr_tuple).childType(mod);
3137531674 const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
3137631675 const slice_info = slice_ty.ptrInfo(mod);
31377 const array_ty = try mod.arrayType(.{
31676 const array_ty = try pt.arrayType(.{
3137831677 .len = tuple_ty.structFieldCount(mod),
3137931678 .sentinel = slice_info.sentinel,
3138031679 .child = slice_info.child,
......@@ -31396,7 +31695,8 @@ fn coerceTupleToArrayPtrs(
3139631695 ptr_tuple: Air.Inst.Ref,
3139731696 tuple_src: LazySrcLoc,
3139831697) !Air.Inst.Ref {
31399 const mod = sema.mod;
31698 const pt = sema.pt;
31699 const mod = pt.zcu;
3140031700 const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
3140131701 const ptr_info = ptr_array_ty.ptrInfo(mod);
3140231702 const array_ty = Type.fromInterned(ptr_info.child);
......@@ -31417,10 +31717,11 @@ fn coerceTupleToStruct(
3141731717 inst: Air.Inst.Ref,
3141831718 inst_src: LazySrcLoc,
3141931719) !Air.Inst.Ref {
31420 const mod = sema.mod;
31720 const pt = sema.pt;
31721 const mod = pt.zcu;
3142131722 const ip = &mod.intern_pool;
31422 try struct_ty.resolveFields(mod);
31423 try struct_ty.resolveStructFieldInits(mod);
31723 try struct_ty.resolveFields(pt);
31724 try struct_ty.resolveStructFieldInits(pt);
3142431725
3142531726 if (struct_ty.isTupleOrAnonStruct(mod)) {
3142631727 return sema.coerceTupleToTuple(block, struct_ty, inst, inst_src);
......@@ -31461,7 +31762,7 @@ fn coerceTupleToStruct(
3146131762 };
3146231763
3146331764 const field_init = Value.fromInterned(struct_type.field_inits.get(ip)[struct_field_index]);
31464 if (!init_val.eql(field_init, struct_field_ty, sema.mod)) {
31765 if (!init_val.eql(field_init, struct_field_ty, pt.zcu)) {
3146531766 return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, tuple_field_index);
3146631767 }
3146731768 }
......@@ -31512,7 +31813,7 @@ fn coerceTupleToStruct(
3151231813 return block.addAggregateInit(struct_ty, field_refs);
3151331814 }
3151431815
31515 const struct_val = try mod.intern(.{ .aggregate = .{
31816 const struct_val = try pt.intern(.{ .aggregate = .{
3151631817 .ty = struct_ty.toIntern(),
3151731818 .storage = .{ .elems = field_vals },
3151831819 } });
......@@ -31529,7 +31830,8 @@ fn coerceTupleToTuple(
3152931830 inst: Air.Inst.Ref,
3153031831 inst_src: LazySrcLoc,
3153131832) !Air.Inst.Ref {
31532 const mod = sema.mod;
31833 const pt = sema.pt;
31834 const mod = pt.zcu;
3153331835 const ip = &mod.intern_pool;
3153431836 const dest_field_count = switch (ip.indexToKey(tuple_ty.toIntern())) {
3153531837 .anon_struct_type => |anon_struct_type| anon_struct_type.types.len,
......@@ -31594,7 +31896,7 @@ fn coerceTupleToTuple(
3159431896 });
3159531897 };
3159631898
31597 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), sema.mod)) {
31899 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), pt.zcu)) {
3159831900 return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, field_i);
3159931901 }
3160031902 }
......@@ -31659,7 +31961,7 @@ fn coerceTupleToTuple(
3165931961 return block.addAggregateInit(tuple_ty, field_refs);
3166031962 }
3166131963
31662 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31964 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3166331965 .ty = tuple_ty.toIntern(),
3166431966 .storage = .{ .elems = field_vals },
3166531967 } })));
......@@ -31689,17 +31991,19 @@ fn addReferenceEntry(
3168931991 src: LazySrcLoc,
3169031992 referenced_unit: AnalUnit,
3169131993) !void {
31692 if (sema.mod.comp.reference_trace == 0) return;
31994 const zcu = sema.pt.zcu;
31995 if (zcu.comp.reference_trace == 0) return;
3169331996 const gop = try sema.references.getOrPut(sema.gpa, referenced_unit);
3169431997 if (gop.found_existing) return;
3169531998 // TODO: we need to figure out how to model inline calls here.
3169631999 // They aren't references in the analysis sense, but ought to show up in the reference trace!
3169732000 // Would representing inline calls in the reference table cause excessive memory usage?
31698 try sema.mod.addUnitReference(sema.ownerUnit(), referenced_unit, src);
32001 try zcu.addUnitReference(sema.ownerUnit(), referenced_unit, src);
3169932002}
3170032003
3170132004pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) CompileError!void {
31702 const mod = sema.mod;
32005 const pt = sema.pt;
32006 const mod = pt.zcu;
3170332007 const ip = &mod.intern_pool;
3170432008 const decl = mod.declPtr(decl_index);
3170532009 if (decl.analysis == .in_progress) {
......@@ -31710,7 +32014,7 @@ pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) Compile
3171032014 return sema.failWithOwnedErrorMsg(null, msg);
3171132015 }
3171232016
31713 mod.ensureDeclAnalyzed(decl_index) catch |err| {
32017 pt.ensureDeclAnalyzed(decl_index) catch |err| {
3171432018 if (sema.owner_func_index != .none) {
3171532019 ip.funcAnalysis(sema.owner_func_index).state = .dependency_failure;
3171632020 } else {
......@@ -31721,9 +32025,10 @@ pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) Compile
3172132025}
3172232026
3172332027fn ensureFuncBodyAnalyzed(sema: *Sema, func: InternPool.Index) CompileError!void {
31724 const mod = sema.mod;
32028 const pt = sema.pt;
32029 const mod = pt.zcu;
3172532030 const ip = &mod.intern_pool;
31726 mod.ensureFuncBodyAnalyzed(func) catch |err| {
32031 pt.ensureFuncBodyAnalyzed(func) catch |err| {
3172732032 if (sema.owner_func_index != .none) {
3172832033 ip.funcAnalysis(sema.owner_func_index).state = .dependency_failure;
3172932034 } else {
......@@ -31734,15 +32039,15 @@ fn ensureFuncBodyAnalyzed(sema: *Sema, func: InternPool.Index) CompileError!void
3173432039}
3173532040
3173632041fn optRefValue(sema: *Sema, opt_val: ?Value) !Value {
31737 const mod = sema.mod;
31738 const ptr_anyopaque_ty = try mod.singleConstPtrType(Type.anyopaque);
31739 return Value.fromInterned((try mod.intern(.{ .opt = .{
31740 .ty = (try mod.optionalType(ptr_anyopaque_ty.toIntern())).toIntern(),
31741 .val = if (opt_val) |val| (try mod.getCoerced(
32042 const pt = sema.pt;
32043 const ptr_anyopaque_ty = try pt.singleConstPtrType(Type.anyopaque);
32044 return Value.fromInterned(try pt.intern(.{ .opt = .{
32045 .ty = (try pt.optionalType(ptr_anyopaque_ty.toIntern())).toIntern(),
32046 .val = if (opt_val) |val| (try pt.getCoerced(
3174232047 Value.fromInterned(try sema.refValue(val.toIntern())),
3174332048 ptr_anyopaque_ty,
3174432049 )).toIntern() else .none,
31745 } })));
32050 } }));
3174632051}
3174732052
3174832053fn analyzeDeclRef(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex) CompileError!Air.Inst.Ref {
......@@ -31754,7 +32059,8 @@ fn analyzeDeclRef(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex
3175432059/// decl_ref to end up in runtime code, the function body must be analyzed: `analyzeDeclRef` wraps
3175532060/// this function with `analyze_fn_body` set to true.
3175632061fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex, analyze_fn_body: bool) CompileError!Air.Inst.Ref {
31757 const mod = sema.mod;
32062 const pt = sema.pt;
32063 const mod = pt.zcu;
3175832064 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = decl_index }));
3175932065 try sema.ensureDeclAnalyzed(decl_index);
3176032066
......@@ -31767,7 +32073,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3176732073 });
3176832074 // TODO: if this is a `decl_ref` of a non-variable decl, only depend on decl type
3176932075 try sema.declareDependency(.{ .decl_val = decl_index });
31770 const ptr_ty = try mod.ptrTypeSema(.{
32076 const ptr_ty = try pt.ptrTypeSema(.{
3177132077 .child = decl_val.typeOf(mod).toIntern(),
3177232078 .flags = .{
3177332079 .alignment = owner_decl.alignment,
......@@ -31778,7 +32084,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3177832084 if (analyze_fn_body) {
3177932085 try sema.maybeQueueFuncBodyAnalysis(src, decl_index);
3178032086 }
31781 return Air.internedToRef((try mod.intern(.{ .ptr = .{
32087 return Air.internedToRef((try pt.intern(.{ .ptr = .{
3178232088 .ty = ptr_ty.toIntern(),
3178332089 .base_addr = .{ .decl = decl_index },
3178432090 .byte_offset = 0,
......@@ -31786,7 +32092,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3178632092}
3178732093
3178832094fn maybeQueueFuncBodyAnalysis(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex) !void {
31789 const mod = sema.mod;
32095 const mod = sema.pt.zcu;
3179032096 const decl = mod.declPtr(decl_index);
3179132097 const decl_val = try decl.valueOrFail();
3179232098 if (!mod.intern_pool.isFuncBody(decl_val.toIntern())) return;
......@@ -31801,7 +32107,8 @@ fn analyzeRef(
3180132107 src: LazySrcLoc,
3180232108 operand: Air.Inst.Ref,
3180332109) CompileError!Air.Inst.Ref {
31804 const mod = sema.mod;
32110 const pt = sema.pt;
32111 const mod = pt.zcu;
3180532112 const operand_ty = sema.typeOf(operand);
3180632113
3180732114 if (try sema.resolveValue(operand)) |val| {
......@@ -31814,14 +32121,14 @@ fn analyzeRef(
3181432121
3181532122 try sema.requireRuntimeBlock(block, src, null);
3181632123 const address_space = target_util.defaultAddressSpace(mod.getTarget(), .local);
31817 const ptr_type = try mod.ptrTypeSema(.{
32124 const ptr_type = try pt.ptrTypeSema(.{
3181832125 .child = operand_ty.toIntern(),
3181932126 .flags = .{
3182032127 .is_const = true,
3182132128 .address_space = address_space,
3182232129 },
3182332130 });
31824 const mut_ptr_type = try mod.ptrTypeSema(.{
32131 const mut_ptr_type = try pt.ptrTypeSema(.{
3182532132 .child = operand_ty.toIntern(),
3182632133 .flags = .{ .address_space = address_space },
3182732134 });
......@@ -31839,14 +32146,15 @@ fn analyzeLoad(
3183932146 ptr: Air.Inst.Ref,
3184032147 ptr_src: LazySrcLoc,
3184132148) CompileError!Air.Inst.Ref {
31842 const mod = sema.mod;
32149 const pt = sema.pt;
32150 const mod = pt.zcu;
3184332151 const ptr_ty = sema.typeOf(ptr);
3184432152 const elem_ty = switch (ptr_ty.zigTypeTag(mod)) {
3184532153 .Pointer => ptr_ty.childType(mod),
31846 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)}),
32154 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(pt)}),
3184732155 };
3184832156 if (elem_ty.zigTypeTag(mod) == .Opaque) {
31849 return sema.fail(block, ptr_src, "cannot load opaque type '{}'", .{elem_ty.fmt(mod)});
32157 return sema.fail(block, ptr_src, "cannot load opaque type '{}'", .{elem_ty.fmt(pt)});
3185032158 }
3185132159
3185232160 if (try sema.typeHasOnePossibleValue(elem_ty)) |opv| {
......@@ -31868,7 +32176,7 @@ fn analyzeLoad(
3186832176 return block.addBinOp(.ptr_elem_val, bin_op.lhs, bin_op.rhs);
3186932177 }
3187032178 return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
31871 ptr_ty.fmt(sema.mod),
32179 ptr_ty.fmt(pt),
3187232180 });
3187332181 }
3187432182
......@@ -31882,10 +32190,11 @@ fn analyzeSlicePtr(
3188232190 slice: Air.Inst.Ref,
3188332191 slice_ty: Type,
3188432192) CompileError!Air.Inst.Ref {
31885 const mod = sema.mod;
32193 const pt = sema.pt;
32194 const mod = pt.zcu;
3188632195 const result_ty = slice_ty.slicePtrFieldType(mod);
3188732196 if (try sema.resolveValue(slice)) |val| {
31888 if (val.isUndef(mod)) return mod.undefRef(result_ty);
32197 if (val.isUndef(mod)) return pt.undefRef(result_ty);
3188932198 return Air.internedToRef(val.slicePtr(mod).toIntern());
3189032199 }
3189132200 try sema.requireRuntimeBlock(block, slice_src, null);
......@@ -31899,11 +32208,12 @@ fn analyzeOptionalSlicePtr(
3189932208 opt_slice: Air.Inst.Ref,
3190032209 opt_slice_ty: Type,
3190132210) CompileError!Air.Inst.Ref {
31902 const mod = sema.mod;
32211 const pt = sema.pt;
32212 const mod = pt.zcu;
3190332213 const result_ty = opt_slice_ty.optionalChild(mod).slicePtrFieldType(mod);
3190432214
3190532215 if (try sema.resolveValue(opt_slice)) |opt_val| {
31906 if (opt_val.isUndef(mod)) return mod.undefRef(result_ty);
32216 if (opt_val.isUndef(mod)) return pt.undefRef(result_ty);
3190732217 const slice_ptr: InternPool.Index = if (opt_val.optionalValue(mod)) |val|
3190832218 val.slicePtr(mod).toIntern()
3190932219 else
......@@ -31924,12 +32234,13 @@ fn analyzeSliceLen(
3192432234 src: LazySrcLoc,
3192532235 slice_inst: Air.Inst.Ref,
3192632236) CompileError!Air.Inst.Ref {
31927 const mod = sema.mod;
32237 const pt = sema.pt;
32238 const mod = pt.zcu;
3192832239 if (try sema.resolveValue(slice_inst)) |slice_val| {
3192932240 if (slice_val.isUndef(mod)) {
31930 return mod.undefRef(Type.usize);
32241 return pt.undefRef(Type.usize);
3193132242 }
31932 return mod.intRef(Type.usize, try slice_val.sliceLen(mod));
32243 return pt.intRef(Type.usize, try slice_val.sliceLen(pt));
3193332244 }
3193432245 try sema.requireRuntimeBlock(block, src, null);
3193532246 return block.addTyOp(.slice_len, Type.usize, slice_inst);
......@@ -31942,11 +32253,12 @@ fn analyzeIsNull(
3194232253 operand: Air.Inst.Ref,
3194332254 invert_logic: bool,
3194432255) CompileError!Air.Inst.Ref {
31945 const mod = sema.mod;
32256 const pt = sema.pt;
32257 const mod = pt.zcu;
3194632258 const result_ty = Type.bool;
3194732259 if (try sema.resolveValue(operand)) |opt_val| {
3194832260 if (opt_val.isUndef(mod)) {
31949 return mod.undefRef(result_ty);
32261 return pt.undefRef(result_ty);
3195032262 }
3195132263 const is_null = opt_val.isNull(mod);
3195232264 const bool_value = if (invert_logic) !is_null else is_null;
......@@ -31972,7 +32284,8 @@ fn analyzePtrIsNonErrComptimeOnly(
3197232284 src: LazySrcLoc,
3197332285 operand: Air.Inst.Ref,
3197432286) CompileError!Air.Inst.Ref {
31975 const mod = sema.mod;
32287 const pt = sema.pt;
32288 const mod = pt.zcu;
3197632289 const ptr_ty = sema.typeOf(operand);
3197732290 assert(ptr_ty.zigTypeTag(mod) == .Pointer);
3197832291 const child_ty = ptr_ty.childType(mod);
......@@ -31994,7 +32307,8 @@ fn analyzeIsNonErrComptimeOnly(
3199432307 src: LazySrcLoc,
3199532308 operand: Air.Inst.Ref,
3199632309) CompileError!Air.Inst.Ref {
31997 const mod = sema.mod;
32310 const pt = sema.pt;
32311 const mod = pt.zcu;
3199832312 const ip = &mod.intern_pool;
3199932313 const operand_ty = sema.typeOf(operand);
3200032314 const ot = operand_ty.zigTypeTag(mod);
......@@ -32014,7 +32328,7 @@ fn analyzeIsNonErrComptimeOnly(
3201432328 else => {},
3201532329 }
3201632330 } else if (operand == .undef) {
32017 return mod.undefRef(Type.bool);
32331 return pt.undefRef(Type.bool);
3201832332 } else if (@intFromEnum(operand) < InternPool.static_len) {
3201932333 // None of the ref tags can be errors.
3202032334 return .bool_true;
......@@ -32098,7 +32412,7 @@ fn analyzeIsNonErrComptimeOnly(
3209832412
3209932413 if (maybe_operand_val) |err_union| {
3210032414 if (err_union.isUndef(mod)) {
32101 return mod.undefRef(Type.bool);
32415 return pt.undefRef(Type.bool);
3210232416 }
3210332417 if (err_union.getErrorName(mod) == .none) {
3210432418 return .bool_true;
......@@ -32153,13 +32467,14 @@ fn analyzeSlice(
3215332467 end_src: LazySrcLoc,
3215432468 by_length: bool,
3215532469) CompileError!Air.Inst.Ref {
32156 const mod = sema.mod;
32470 const pt = sema.pt;
32471 const mod = pt.zcu;
3215732472 // Slice expressions can operate on a variable whose type is an array. This requires
3215832473 // the slice operand to be a pointer. In the case of a non-array, it will be a double pointer.
3215932474 const ptr_ptr_ty = sema.typeOf(ptr_ptr);
3216032475 const ptr_ptr_child_ty = switch (ptr_ptr_ty.zigTypeTag(mod)) {
3216132476 .Pointer => ptr_ptr_ty.childType(mod),
32162 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(mod)}),
32477 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(pt)}),
3216332478 };
3216432479
3216532480 var array_ty = ptr_ptr_child_ty;
......@@ -32210,8 +32525,8 @@ fn analyzeSlice(
3221032525 msg,
3221132526 "expected '{}', found '{}'",
3221232527 .{
32213 Value.zero_comptime_int.fmtValue(mod, sema),
32214 start_value.fmtValue(mod, sema),
32528 Value.zero_comptime_int.fmtValue(pt, sema),
32529 start_value.fmtValue(pt, sema),
3221532530 },
3221632531 );
3221732532 break :msg msg;
......@@ -32226,8 +32541,8 @@ fn analyzeSlice(
3222632541 msg,
3222732542 "expected '{}', found '{}'",
3222832543 .{
32229 Value.one_comptime_int.fmtValue(mod, sema),
32230 end_value.fmtValue(mod, sema),
32544 Value.one_comptime_int.fmtValue(pt, sema),
32545 end_value.fmtValue(pt, sema),
3223132546 },
3223232547 );
3223332548 break :msg msg;
......@@ -32240,17 +32555,17 @@ fn analyzeSlice(
3224032555 block,
3224132556 end_src,
3224232557 "end index {} out of bounds for slice of single-item pointer",
32243 .{end_value.fmtValue(mod, sema)},
32558 .{end_value.fmtValue(pt, sema)},
3224432559 );
3224532560 }
3224632561 }
3224732562
32248 array_ty = try mod.arrayType(.{
32563 array_ty = try pt.arrayType(.{
3224932564 .len = 1,
3225032565 .child = double_child_ty.toIntern(),
3225132566 });
3225232567 const ptr_info = ptr_ptr_child_ty.ptrInfo(mod);
32253 slice_ty = try mod.ptrType(.{
32568 slice_ty = try pt.ptrType(.{
3225432569 .child = array_ty.toIntern(),
3225532570 .flags = .{
3225632571 .alignment = ptr_info.flags.alignment,
......@@ -32286,7 +32601,7 @@ fn analyzeSlice(
3228632601 elem_ty = ptr_ptr_child_ty.childType(mod);
3228732602 },
3228832603 },
32289 else => return sema.fail(block, src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(mod)}),
32604 else => return sema.fail(block, src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(pt)}),
3229032605 }
3229132606
3229232607 const ptr = if (slice_ty.isSlice(mod))
......@@ -32297,7 +32612,7 @@ fn analyzeSlice(
3229732612 assert(manyptr_ty_key.flags.size == .One);
3229832613 manyptr_ty_key.child = elem_ty.toIntern();
3229932614 manyptr_ty_key.flags.size = .Many;
32300 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(manyptr_ty_key), ptr_or_slice, ptr_src);
32615 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(manyptr_ty_key), ptr_or_slice, ptr_src);
3230132616 } else ptr_or_slice;
3230232617
3230332618 const start = try sema.coerce(block, Type.usize, uncasted_start, start_src);
......@@ -32311,7 +32626,7 @@ fn analyzeSlice(
3231132626 var end_is_len = uncasted_end_opt == .none;
3231232627 const end = e: {
3231332628 if (array_ty.zigTypeTag(mod) == .Array) {
32314 const len_val = try mod.intValue(Type.usize, array_ty.arrayLen(mod));
32629 const len_val = try pt.intValue(Type.usize, array_ty.arrayLen(mod));
3231532630
3231632631 if (!end_is_len) {
3231732632 const end = if (by_length) end: {
......@@ -32320,7 +32635,7 @@ fn analyzeSlice(
3232032635 break :end try sema.coerce(block, Type.usize, uncasted_end, end_src);
3232132636 } else try sema.coerce(block, Type.usize, uncasted_end_opt, end_src);
3232232637 if (try sema.resolveDefinedValue(block, end_src, end)) |end_val| {
32323 const len_s_val = try mod.intValue(
32638 const len_s_val = try pt.intValue(
3232432639 Type.usize,
3232532640 array_ty.arrayLenIncludingSentinel(mod),
3232632641 );
......@@ -32335,8 +32650,8 @@ fn analyzeSlice(
3233532650 end_src,
3233632651 "end index {} out of bounds for array of length {}{s}",
3233732652 .{
32338 end_val.fmtValue(mod, sema),
32339 len_val.fmtValue(mod, sema),
32653 end_val.fmtValue(pt, sema),
32654 len_val.fmtValue(pt, sema),
3234032655 sentinel_label,
3234132656 },
3234232657 );
......@@ -32366,9 +32681,9 @@ fn analyzeSlice(
3236632681 return sema.fail(block, src, "slice of undefined", .{});
3236732682 }
3236832683 const has_sentinel = slice_ty.sentinel(mod) != null;
32369 const slice_len = try slice_val.sliceLen(mod);
32684 const slice_len = try slice_val.sliceLen(pt);
3237032685 const len_plus_sent = slice_len + @intFromBool(has_sentinel);
32371 const slice_len_val_with_sentinel = try mod.intValue(Type.usize, len_plus_sent);
32686 const slice_len_val_with_sentinel = try pt.intValue(Type.usize, len_plus_sent);
3237232687 if (!(try sema.compareAll(end_val, .lte, slice_len_val_with_sentinel, Type.usize))) {
3237332688 const sentinel_label: []const u8 = if (has_sentinel)
3237432689 " +1 (sentinel)"
......@@ -32380,8 +32695,8 @@ fn analyzeSlice(
3238032695 end_src,
3238132696 "end index {} out of bounds for slice of length {d}{s}",
3238232697 .{
32383 end_val.fmtValue(mod, sema),
32384 try slice_val.sliceLen(mod),
32698 end_val.fmtValue(pt, sema),
32699 try slice_val.sliceLen(pt),
3238532700 sentinel_label,
3238632701 },
3238732702 );
......@@ -32390,7 +32705,7 @@ fn analyzeSlice(
3239032705 // If the slice has a sentinel, we consider end_is_len
3239132706 // is only true if it equals the length WITHOUT the
3239232707 // sentinel, so we don't add a sentinel type.
32393 const slice_len_val = try mod.intValue(Type.usize, slice_len);
32708 const slice_len_val = try pt.intValue(Type.usize, slice_len);
3239432709 if (end_val.eql(slice_len_val, Type.usize, mod)) {
3239532710 end_is_len = true;
3239632711 }
......@@ -32440,21 +32755,21 @@ fn analyzeSlice(
3244032755 start_src,
3244132756 "start index {} is larger than end index {}",
3244232757 .{
32443 start_val.fmtValue(mod, sema),
32444 end_val.fmtValue(mod, sema),
32758 start_val.fmtValue(pt, sema),
32759 end_val.fmtValue(pt, sema),
3244532760 },
3244632761 );
3244732762 }
3244832763 checked_start_lte_end = true;
3244932764 if (try sema.resolveValue(new_ptr)) |ptr_val| sentinel_check: {
3245032765 const expected_sentinel = sentinel orelse break :sentinel_check;
32451 const start_int = start_val.getUnsignedInt(mod).?;
32452 const end_int = end_val.getUnsignedInt(mod).?;
32766 const start_int = start_val.getUnsignedInt(pt).?;
32767 const end_int = end_val.getUnsignedInt(pt).?;
3245332768 const sentinel_index = try sema.usizeCast(block, end_src, end_int - start_int);
3245432769
32455 const many_ptr_ty = try mod.manyConstPtrType(elem_ty);
32456 const many_ptr_val = try mod.getCoerced(ptr_val, many_ptr_ty);
32457 const elem_ptr = try many_ptr_val.ptrElem(sentinel_index, mod);
32770 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);
32771 const many_ptr_val = try pt.getCoerced(ptr_val, many_ptr_ty);
32772 const elem_ptr = try many_ptr_val.ptrElem(sentinel_index, pt);
3245832773 const res = try sema.pointerDerefExtra(block, src, elem_ptr);
3245932774 const actual_sentinel = switch (res) {
3246032775 .runtime_load => break :sentinel_check,
......@@ -32463,13 +32778,13 @@ fn analyzeSlice(
3246332778 block,
3246432779 src,
3246532780 "comptime dereference requires '{}' to have a well-defined layout",
32466 .{ty.fmt(mod)},
32781 .{ty.fmt(pt)},
3246732782 ),
3246832783 .out_of_bounds => |ty| return sema.fail(
3246932784 block,
3247032785 end_src,
3247132786 "slice end index {d} exceeds bounds of containing decl of type '{}'",
32472 .{ end_int, ty.fmt(mod) },
32787 .{ end_int, ty.fmt(pt) },
3247332788 ),
3247432789 };
3247532790
......@@ -32478,8 +32793,8 @@ fn analyzeSlice(
3247832793 const msg = try sema.errMsg(src, "value in memory does not match slice sentinel", .{});
3247932794 errdefer msg.destroy(sema.gpa);
3248032795 try sema.errNote(src, msg, "expected '{}', found '{}'", .{
32481 expected_sentinel.fmtValue(mod, sema),
32482 actual_sentinel.fmtValue(mod, sema),
32796 expected_sentinel.fmtValue(pt, sema),
32797 actual_sentinel.fmtValue(pt, sema),
3248332798 });
3248432799
3248532800 break :msg msg;
......@@ -32501,7 +32816,7 @@ fn analyzeSlice(
3250132816 assert(!block.is_comptime);
3250232817 try sema.requireRuntimeBlock(block, src, runtime_src.?);
3250332818 const ok = try block.addBinOp(.cmp_lte, start, end);
32504 if (!sema.mod.comp.formatted_panics) {
32819 if (!pt.zcu.comp.formatted_panics) {
3250532820 try sema.addSafetyCheck(block, src, ok, .start_index_greater_than_end);
3250632821 } else {
3250732822 try sema.safetyCheckFormatted(block, src, ok, "panicStartGreaterThanEnd", &.{ start, end });
......@@ -32517,10 +32832,10 @@ fn analyzeSlice(
3251732832 const new_allowzero = new_ptr_ty_info.flags.is_allowzero and sema.typeOf(ptr).ptrSize(mod) != .C;
3251832833
3251932834 if (opt_new_len_val) |new_len_val| {
32520 const new_len_int = try new_len_val.toUnsignedIntSema(mod);
32835 const new_len_int = try new_len_val.toUnsignedIntSema(pt);
3252132836
32522 const return_ty = try mod.ptrTypeSema(.{
32523 .child = (try mod.arrayType(.{
32837 const return_ty = try pt.ptrTypeSema(.{
32838 .child = (try pt.arrayType(.{
3252432839 .len = new_len_int,
3252532840 .sentinel = if (sentinel) |s| s.toIntern() else .none,
3252632841 .child = elem_ty.toIntern(),
......@@ -32546,7 +32861,7 @@ fn analyzeSlice(
3254632861
3254732862 bounds_check: {
3254832863 const actual_len = if (array_ty.zigTypeTag(mod) == .Array)
32549 try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
32864 try pt.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
3255032865 else if (slice_ty.isSlice(mod)) l: {
3255132866 const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
3255232867 break :l if (slice_ty.sentinel(mod) == null)
......@@ -32570,18 +32885,18 @@ fn analyzeSlice(
3257032885 };
3257132886
3257232887 if (!new_ptr_val.isUndef(mod)) {
32573 return Air.internedToRef((try mod.getCoerced(new_ptr_val, return_ty)).toIntern());
32888 return Air.internedToRef((try pt.getCoerced(new_ptr_val, return_ty)).toIntern());
3257432889 }
3257532890
3257632891 // Special case: @as([]i32, undefined)[x..x]
3257732892 if (new_len_int == 0) {
32578 return mod.undefRef(return_ty);
32893 return pt.undefRef(return_ty);
3257932894 }
3258032895
3258132896 return sema.fail(block, src, "non-zero length slice of undefined pointer", .{});
3258232897 }
3258332898
32584 const return_ty = try mod.ptrTypeSema(.{
32899 const return_ty = try pt.ptrTypeSema(.{
3258532900 .child = elem_ty.toIntern(),
3258632901 .sentinel = if (sentinel) |s| s.toIntern() else .none,
3258732902 .flags = .{
......@@ -32604,12 +32919,12 @@ fn analyzeSlice(
3260432919
3260532920 // requirement: end <= len
3260632921 const opt_len_inst = if (array_ty.zigTypeTag(mod) == .Array)
32607 try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
32922 try pt.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
3260832923 else if (slice_ty.isSlice(mod)) blk: {
3260932924 if (try sema.resolveDefinedValue(block, src, ptr_or_slice)) |slice_val| {
3261032925 // we don't need to add one for sentinels because the
3261132926 // underlying value data includes the sentinel
32612 break :blk try mod.intRef(Type.usize, try slice_val.sliceLen(mod));
32927 break :blk try pt.intRef(Type.usize, try slice_val.sliceLen(pt));
3261332928 }
3261432929
3261532930 const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
......@@ -32657,7 +32972,8 @@ fn cmpNumeric(
3265732972 lhs_src: LazySrcLoc,
3265832973 rhs_src: LazySrcLoc,
3265932974) CompileError!Air.Inst.Ref {
32660 const mod = sema.mod;
32975 const pt = sema.pt;
32976 const mod = pt.zcu;
3266132977 const lhs_ty = sema.typeOf(uncasted_lhs);
3266232978 const rhs_ty = sema.typeOf(uncasted_rhs);
3266332979
......@@ -32696,12 +33012,12 @@ fn cmpNumeric(
3269633012 }
3269733013
3269833014 if (lhs_val.isUndef(mod) or rhs_val.isUndef(mod)) {
32699 return mod.undefRef(Type.bool);
33015 return pt.undefRef(Type.bool);
3270033016 }
3270133017 if (lhs_val.isNan(mod) or rhs_val.isNan(mod)) {
3270233018 return if (op == std.math.CompareOperator.neq) .bool_true else .bool_false;
3270333019 }
32704 return if (try Value.compareHeteroAdvanced(lhs_val, op, rhs_val, mod, .sema))
33020 return if (try Value.compareHeteroAdvanced(lhs_val, op, rhs_val, pt, .sema))
3270533021 .bool_true
3270633022 else
3270733023 .bool_false;
......@@ -32770,11 +33086,11 @@ fn cmpNumeric(
3277033086 // a signed integer with mantissa bits + 1, and if there was any non-integral part of the float,
3277133087 // add/subtract 1.
3277233088 const lhs_is_signed = if (try sema.resolveDefinedValue(block, lhs_src, lhs)) |lhs_val|
32773 !(try lhs_val.compareAllWithZeroSema(.gte, mod))
33089 !(try lhs_val.compareAllWithZeroSema(.gte, pt))
3277433090 else
3277533091 (lhs_ty.isRuntimeFloat() or lhs_ty.isSignedInt(mod));
3277633092 const rhs_is_signed = if (try sema.resolveDefinedValue(block, rhs_src, rhs)) |rhs_val|
32777 !(try rhs_val.compareAllWithZeroSema(.gte, mod))
33093 !(try rhs_val.compareAllWithZeroSema(.gte, pt))
3277833094 else
3277933095 (rhs_ty.isRuntimeFloat() or rhs_ty.isSignedInt(mod));
3278033096 const dest_int_is_signed = lhs_is_signed or rhs_is_signed;
......@@ -32784,7 +33100,7 @@ fn cmpNumeric(
3278433100 var lhs_bits: usize = undefined;
3278533101 if (try sema.resolveValueResolveLazy(lhs)) |lhs_val| {
3278633102 if (lhs_val.isUndef(mod))
32787 return mod.undefRef(Type.bool);
33103 return pt.undefRef(Type.bool);
3278833104 if (lhs_val.isNan(mod)) switch (op) {
3278933105 .neq => return .bool_true,
3279033106 else => return .bool_false,
......@@ -32796,7 +33112,7 @@ fn cmpNumeric(
3279633112 .lt, .lte => return if (lhs_val.isNegativeInf(mod)) .bool_true else .bool_false,
3279733113 };
3279833114 if (!rhs_is_signed) {
32799 switch (lhs_val.orderAgainstZero(mod)) {
33115 switch (lhs_val.orderAgainstZero(pt)) {
3280033116 .gt => {},
3280133117 .eq => switch (op) { // LHS = 0, RHS is unsigned
3280233118 .lte => return .bool_true,
......@@ -32818,7 +33134,7 @@ fn cmpNumeric(
3281833134 }
3281933135 }
3282033136
32821 var bigint = try float128IntPartToBigInt(sema.gpa, lhs_val.toFloat(f128, mod));
33137 var bigint = try float128IntPartToBigInt(sema.gpa, lhs_val.toFloat(f128, pt));
3282233138 defer bigint.deinit();
3282333139 if (lhs_val.floatHasFraction(mod)) {
3282433140 if (lhs_is_signed) {
......@@ -32829,7 +33145,7 @@ fn cmpNumeric(
3282933145 }
3283033146 lhs_bits = bigint.toConst().bitCountTwosComp();
3283133147 } else {
32832 lhs_bits = lhs_val.intBitCountTwosComp(mod);
33148 lhs_bits = lhs_val.intBitCountTwosComp(pt);
3283333149 }
3283433150 lhs_bits += @intFromBool(!lhs_is_signed and dest_int_is_signed);
3283533151 } else if (lhs_is_float) {
......@@ -32842,7 +33158,7 @@ fn cmpNumeric(
3284233158 var rhs_bits: usize = undefined;
3284333159 if (try sema.resolveValueResolveLazy(rhs)) |rhs_val| {
3284433160 if (rhs_val.isUndef(mod))
32845 return mod.undefRef(Type.bool);
33161 return pt.undefRef(Type.bool);
3284633162 if (rhs_val.isNan(mod)) switch (op) {
3284733163 .neq => return .bool_true,
3284833164 else => return .bool_false,
......@@ -32854,7 +33170,7 @@ fn cmpNumeric(
3285433170 .lt, .lte => return if (rhs_val.isNegativeInf(mod)) .bool_false else .bool_true,
3285533171 };
3285633172 if (!lhs_is_signed) {
32857 switch (rhs_val.orderAgainstZero(mod)) {
33173 switch (rhs_val.orderAgainstZero(pt)) {
3285833174 .gt => {},
3285933175 .eq => switch (op) { // RHS = 0, LHS is unsigned
3286033176 .gte => return .bool_true,
......@@ -32876,7 +33192,7 @@ fn cmpNumeric(
3287633192 }
3287733193 }
3287833194
32879 var bigint = try float128IntPartToBigInt(sema.gpa, rhs_val.toFloat(f128, mod));
33195 var bigint = try float128IntPartToBigInt(sema.gpa, rhs_val.toFloat(f128, pt));
3288033196 defer bigint.deinit();
3288133197 if (rhs_val.floatHasFraction(mod)) {
3288233198 if (rhs_is_signed) {
......@@ -32887,7 +33203,7 @@ fn cmpNumeric(
3288733203 }
3288833204 rhs_bits = bigint.toConst().bitCountTwosComp();
3288933205 } else {
32890 rhs_bits = rhs_val.intBitCountTwosComp(mod);
33206 rhs_bits = rhs_val.intBitCountTwosComp(pt);
3289133207 }
3289233208 rhs_bits += @intFromBool(!rhs_is_signed and dest_int_is_signed);
3289333209 } else if (rhs_is_float) {
......@@ -32901,7 +33217,7 @@ fn cmpNumeric(
3290133217 const max_bits = @max(lhs_bits, rhs_bits);
3290233218 const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits});
3290333219 const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;
32904 break :blk try mod.intType(signedness, casted_bits);
33220 break :blk try pt.intType(signedness, casted_bits);
3290533221 };
3290633222 const casted_lhs = try sema.coerce(block, dest_ty, lhs, lhs_src);
3290733223 const casted_rhs = try sema.coerce(block, dest_ty, rhs, rhs_src);
......@@ -32920,9 +33236,10 @@ fn compareIntsOnlyPossibleResult(
3292033236 op: std.math.CompareOperator,
3292133237 rhs_ty: Type,
3292233238) Allocator.Error!?bool {
32923 const mod = sema.mod;
33239 const pt = sema.pt;
33240 const mod = pt.zcu;
3292433241 const rhs_info = rhs_ty.intInfo(mod);
32925 const vs_zero = lhs_val.orderAgainstZeroAdvanced(mod, .sema) catch unreachable;
33242 const vs_zero = lhs_val.orderAgainstZeroAdvanced(pt, .sema) catch unreachable;
3292633243 const is_zero = vs_zero == .eq;
3292733244 const is_negative = vs_zero == .lt;
3292833245 const is_positive = vs_zero == .gt;
......@@ -32954,7 +33271,7 @@ fn compareIntsOnlyPossibleResult(
3295433271 };
3295533272
3295633273 const sign_adj = @intFromBool(!is_negative and rhs_info.signedness == .signed);
32957 const req_bits = lhs_val.intBitCountTwosComp(mod) + sign_adj;
33274 const req_bits = lhs_val.intBitCountTwosComp(pt) + sign_adj;
3295833275
3295933276 // No sized type can have more than 65535 bits.
3296033277 // The RHS type operand is either a runtime value or sized (but undefined) constant.
......@@ -32981,11 +33298,11 @@ fn compareIntsOnlyPossibleResult(
3298133298
3298233299 if (req_bits != rhs_info.bits) break :edge .{ false, false };
3298333300
32984 const ty = try mod.intType(
33301 const ty = try pt.intType(
3298533302 if (is_negative) .signed else .unsigned,
3298633303 @intCast(req_bits),
3298733304 );
32988 const pop_count = lhs_val.popCount(ty, mod);
33305 const pop_count = lhs_val.popCount(ty, pt);
3298933306
3299033307 if (is_negative) {
3299133308 break :edge .{ pop_count == 1, false };
......@@ -33015,7 +33332,8 @@ fn cmpVector(
3301533332 lhs_src: LazySrcLoc,
3301633333 rhs_src: LazySrcLoc,
3301733334) CompileError!Air.Inst.Ref {
33018 const mod = sema.mod;
33335 const pt = sema.pt;
33336 const mod = pt.zcu;
3301933337 const lhs_ty = sema.typeOf(lhs);
3302033338 const rhs_ty = sema.typeOf(rhs);
3302133339 assert(lhs_ty.zigTypeTag(mod) == .Vector);
......@@ -33026,7 +33344,7 @@ fn cmpVector(
3302633344 const casted_lhs = try sema.coerce(block, resolved_ty, lhs, lhs_src);
3302733345 const casted_rhs = try sema.coerce(block, resolved_ty, rhs, rhs_src);
3302833346
33029 const result_ty = try mod.vectorType(.{
33347 const result_ty = try pt.vectorType(.{
3303033348 .len = lhs_ty.vectorLen(mod),
3303133349 .child = .bool_type,
3303233350 });
......@@ -33035,7 +33353,7 @@ fn cmpVector(
3303533353 if (try sema.resolveValue(casted_lhs)) |lhs_val| {
3303633354 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
3303733355 if (lhs_val.isUndef(mod) or rhs_val.isUndef(mod)) {
33038 return mod.undefRef(result_ty);
33356 return pt.undefRef(result_ty);
3303933357 }
3304033358 const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, resolved_ty);
3304133359 return Air.internedToRef(cmp_val.toIntern());
......@@ -33059,7 +33377,7 @@ fn wrapOptional(
3305933377 inst_src: LazySrcLoc,
3306033378) !Air.Inst.Ref {
3306133379 if (try sema.resolveValue(inst)) |val| {
33062 return Air.internedToRef((try sema.mod.intern(.{ .opt = .{
33380 return Air.internedToRef((try sema.pt.intern(.{ .opt = .{
3306333381 .ty = dest_ty.toIntern(),
3306433382 .val = val.toIntern(),
3306533383 } })));
......@@ -33076,11 +33394,12 @@ fn wrapErrorUnionPayload(
3307633394 inst: Air.Inst.Ref,
3307733395 inst_src: LazySrcLoc,
3307833396) !Air.Inst.Ref {
33079 const mod = sema.mod;
33397 const pt = sema.pt;
33398 const mod = pt.zcu;
3308033399 const dest_payload_ty = dest_ty.errorUnionPayload(mod);
3308133400 const coerced = try sema.coerceExtra(block, dest_payload_ty, inst, inst_src, .{ .report_err = false });
3308233401 if (try sema.resolveValue(coerced)) |val| {
33083 return Air.internedToRef((try mod.intern(.{ .error_union = .{
33402 return Air.internedToRef((try pt.intern(.{ .error_union = .{
3308433403 .ty = dest_ty.toIntern(),
3308533404 .val = .{ .payload = val.toIntern() },
3308633405 } })));
......@@ -33096,7 +33415,8 @@ fn wrapErrorUnionSet(
3309633415 inst: Air.Inst.Ref,
3309733416 inst_src: LazySrcLoc,
3309833417) !Air.Inst.Ref {
33099 const mod = sema.mod;
33418 const pt = sema.pt;
33419 const mod = pt.zcu;
3310033420 const ip = &mod.intern_pool;
3310133421 const inst_ty = sema.typeOf(inst);
3310233422 const dest_err_set_ty = dest_ty.errorUnionSet(mod);
......@@ -33140,7 +33460,7 @@ fn wrapErrorUnionSet(
3314033460 else => unreachable,
3314133461 },
3314233462 }
33143 return Air.internedToRef((try mod.intern(.{ .error_union = .{
33463 return Air.internedToRef((try pt.intern(.{ .error_union = .{
3314433464 .ty = dest_ty.toIntern(),
3314533465 .val = .{ .err_name = expected_name },
3314633466 } })));
......@@ -33158,14 +33478,15 @@ fn unionToTag(
3315833478 un: Air.Inst.Ref,
3315933479 un_src: LazySrcLoc,
3316033480) !Air.Inst.Ref {
33161 const mod = sema.mod;
33481 const pt = sema.pt;
33482 const mod = pt.zcu;
3316233483 if ((try sema.typeHasOnePossibleValue(enum_ty))) |opv| {
3316333484 return Air.internedToRef(opv.toIntern());
3316433485 }
3316533486 if (try sema.resolveValue(un)) |un_val| {
3316633487 const tag_val = un_val.unionTag(mod).?;
3316733488 if (tag_val.isUndef(mod))
33168 return try mod.undefRef(enum_ty);
33489 return try pt.undefRef(enum_ty);
3316933490 return Air.internedToRef(tag_val.toIntern());
3317033491 }
3317133492 try sema.requireRuntimeBlock(block, un_src, null);
......@@ -33399,7 +33720,7 @@ const PeerResolveResult = union(enum) {
3339933720 instructions: []const Air.Inst.Ref,
3340033721 candidate_srcs: PeerTypeCandidateSrc,
3340133722 ) !*Module.ErrorMsg {
33402 const mod = sema.mod;
33723 const pt = sema.pt;
3340333724
3340433725 var opt_msg: ?*Module.ErrorMsg = null;
3340533726 errdefer if (opt_msg) |msg| msg.destroy(sema.gpa);
......@@ -33425,7 +33746,7 @@ const PeerResolveResult = union(enum) {
3342533746 },
3342633747 .field_error => |field_error| {
3342733748 const fmt = "struct field '{}' has conflicting types";
33428 const args = .{field_error.field_name.fmt(&mod.intern_pool)};
33749 const args = .{field_error.field_name.fmt(&pt.zcu.intern_pool)};
3342933750 if (opt_msg) |msg| {
3343033751 try sema.errNote(src, msg, fmt, args);
3343133752 } else {
......@@ -33457,8 +33778,8 @@ const PeerResolveResult = union(enum) {
3345733778
3345833779 const fmt = "incompatible types: '{}' and '{}'";
3345933780 const args = .{
33460 conflict_tys[0].fmt(mod),
33461 conflict_tys[1].fmt(mod),
33781 conflict_tys[0].fmt(pt),
33782 conflict_tys[1].fmt(pt),
3346233783 };
3346333784 const msg = if (opt_msg) |msg| msg: {
3346433785 try sema.errNote(src, msg, fmt, args);
......@@ -33469,8 +33790,8 @@ const PeerResolveResult = union(enum) {
3346933790 break :msg msg;
3347033791 };
3347133792
33472 if (conflict_srcs[0]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[0].fmt(mod)});
33473 if (conflict_srcs[1]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[1].fmt(mod)});
33793 if (conflict_srcs[0]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[0].fmt(pt)});
33794 if (conflict_srcs[1]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[1].fmt(pt)});
3347433795
3347533796 // No child error
3347633797 break;
......@@ -33517,7 +33838,8 @@ fn resolvePeerTypesInner(
3351733838 peer_tys: []?Type,
3351833839 peer_vals: []?Value,
3351933840) !PeerResolveResult {
33520 const mod = sema.mod;
33841 const pt = sema.pt;
33842 const mod = pt.zcu;
3352133843 const ip = &mod.intern_pool;
3352233844
3352333845 var strat_reason: usize = 0;
......@@ -33581,7 +33903,7 @@ fn resolvePeerTypesInner(
3358133903 .payload => |payload_ip| val_ptr.* = Value.fromInterned(payload_ip),
3358233904 .err_name => val_ptr.* = null,
3358333905 },
33584 .undef => val_ptr.* = Value.fromInterned((try sema.mod.intern(.{ .undef = ty_ptr.*.?.toIntern() }))),
33906 .undef => val_ptr.* = Value.fromInterned(try pt.intern(.{ .undef = ty_ptr.*.?.toIntern() })),
3358533907 else => unreachable,
3358633908 };
3358733909 break :blk set_ty;
......@@ -33604,7 +33926,7 @@ fn resolvePeerTypesInner(
3360433926 .success => |ty| ty,
3360533927 else => |result| return result,
3360633928 };
33607 return .{ .success = try mod.errorUnionType(final_set.?, final_payload) };
33929 return .{ .success = try pt.errorUnionType(final_set.?, final_payload) };
3360833930 },
3360933931
3361033932 .nullable => {
......@@ -33642,7 +33964,7 @@ fn resolvePeerTypesInner(
3364233964 .success => |ty| ty,
3364333965 else => |result| return result,
3364433966 };
33645 return .{ .success = try mod.optionalType(child_ty.toIntern()) };
33967 return .{ .success = try pt.optionalType(child_ty.toIntern()) };
3364633968 },
3364733969
3364833970 .array => {
......@@ -33730,7 +34052,7 @@ fn resolvePeerTypesInner(
3373034052 // There should always be at least one array or vector peer
3373134053 assert(opt_first_arr_idx != null);
3373234054
33733 return .{ .success = try mod.arrayType(.{
34055 return .{ .success = try pt.arrayType(.{
3373434056 .len = len,
3373534057 .child = elem_ty.toIntern(),
3373634058 .sentinel = if (sentinel) |sent_val| sent_val.toIntern() else .none,
......@@ -33792,7 +34114,7 @@ fn resolvePeerTypesInner(
3379234114 else => |result| return result,
3379334115 };
3379434116
33795 return .{ .success = try mod.vectorType(.{
34117 return .{ .success = try pt.vectorType(.{
3379634118 .len = @intCast(len.?),
3379734119 .child = child_ty.toIntern(),
3379834120 }) };
......@@ -33844,8 +34166,8 @@ fn resolvePeerTypesInner(
3384434166 }).toIntern();
3384534167
3384634168 if (ptr_info.sentinel != .none and peer_info.sentinel != .none) {
33847 const peer_sent = try ip.getCoerced(sema.gpa, ptr_info.sentinel, ptr_info.child);
33848 const ptr_sent = try ip.getCoerced(sema.gpa, peer_info.sentinel, ptr_info.child);
34169 const peer_sent = try ip.getCoerced(sema.gpa, pt.tid, ptr_info.sentinel, ptr_info.child);
34170 const ptr_sent = try ip.getCoerced(sema.gpa, pt.tid, peer_info.sentinel, ptr_info.child);
3384934171 if (ptr_sent == peer_sent) {
3385034172 ptr_info.sentinel = ptr_sent;
3385134173 } else {
......@@ -33860,12 +34182,12 @@ fn resolvePeerTypesInner(
3386034182 if (ptr_info.flags.alignment != .none)
3386134183 ptr_info.flags.alignment
3386234184 else
33863 Type.fromInterned(ptr_info.child).abiAlignment(mod),
34185 Type.fromInterned(ptr_info.child).abiAlignment(pt),
3386434186
3386534187 if (peer_info.flags.alignment != .none)
3386634188 peer_info.flags.alignment
3386734189 else
33868 Type.fromInterned(peer_info.child).abiAlignment(mod),
34190 Type.fromInterned(peer_info.child).abiAlignment(pt),
3386934191 );
3387034192 if (ptr_info.flags.address_space != peer_info.flags.address_space) {
3387134193 return .{ .conflict = .{
......@@ -33888,7 +34210,7 @@ fn resolvePeerTypesInner(
3388834210
3388934211 opt_ptr_info = ptr_info;
3389034212 }
33891 return .{ .success = try mod.ptrTypeSema(opt_ptr_info.?) };
34213 return .{ .success = try pt.ptrTypeSema(opt_ptr_info.?) };
3389234214 },
3389334215
3389434216 .ptr => {
......@@ -34004,7 +34326,7 @@ fn resolvePeerTypesInner(
3400434326 if (try sema.resolvePairInMemoryCoercible(block, src, cur_arr.elem_ty, peer_arr.elem_ty)) |elem_ty| {
3400534327 // *[n:x]T + *[n:y]T = *[n]T
3400634328 if (cur_arr.len == peer_arr.len) {
34007 ptr_info.child = (try mod.arrayType(.{
34329 ptr_info.child = (try pt.arrayType(.{
3400834330 .len = cur_arr.len,
3400934331 .child = elem_ty.toIntern(),
3401034332 })).toIntern();
......@@ -34148,12 +34470,12 @@ fn resolvePeerTypesInner(
3414834470 no_sentinel: {
3414934471 if (peer_sentinel == .none) break :no_sentinel;
3415034472 if (cur_sentinel == .none) break :no_sentinel;
34151 const peer_sent_coerced = try ip.getCoerced(sema.gpa, peer_sentinel, sentinel_ty);
34152 const cur_sent_coerced = try ip.getCoerced(sema.gpa, cur_sentinel, sentinel_ty);
34473 const peer_sent_coerced = try ip.getCoerced(sema.gpa, pt.tid, peer_sentinel, sentinel_ty);
34474 const cur_sent_coerced = try ip.getCoerced(sema.gpa, pt.tid, cur_sentinel, sentinel_ty);
3415334475 if (peer_sent_coerced != cur_sent_coerced) break :no_sentinel;
3415434476 // Sentinels match
3415534477 if (ptr_info.flags.size == .One) switch (ip.indexToKey(ptr_info.child)) {
34156 .array_type => |array_type| ptr_info.child = (try mod.arrayType(.{
34478 .array_type => |array_type| ptr_info.child = (try pt.arrayType(.{
3415734479 .len = array_type.len,
3415834480 .child = array_type.child,
3415934481 .sentinel = cur_sent_coerced,
......@@ -34167,7 +34489,7 @@ fn resolvePeerTypesInner(
3416734489 // Clear existing sentinel
3416834490 ptr_info.sentinel = .none;
3416934491 switch (ip.indexToKey(ptr_info.child)) {
34170 .array_type => |array_type| ptr_info.child = (try mod.arrayType(.{
34492 .array_type => |array_type| ptr_info.child = (try pt.arrayType(.{
3417134493 .len = array_type.len,
3417234494 .child = array_type.child,
3417334495 .sentinel = .none,
......@@ -34198,7 +34520,7 @@ fn resolvePeerTypesInner(
3419834520 },
3419934521 }
3420034522
34201 return .{ .success = try mod.ptrTypeSema(opt_ptr_info.?) };
34523 return .{ .success = try pt.ptrTypeSema(opt_ptr_info.?) };
3420234524 },
3420334525
3420434526 .func => {
......@@ -34517,7 +34839,7 @@ fn resolvePeerTypesInner(
3451734839 continue;
3451834840 };
3451934841 peer_field_ty.* = ty.structFieldType(field_index, mod);
34520 peer_field_val.* = if (opt_val) |val| try val.fieldValue(mod, field_index) else null;
34842 peer_field_val.* = if (opt_val) |val| try val.fieldValue(pt, field_index) else null;
3452134843 }
3452234844
3452334845 // Resolve field type recursively
......@@ -34555,9 +34877,9 @@ fn resolvePeerTypesInner(
3455534877 var comptime_val: ?Value = null;
3455634878 for (peer_tys) |opt_ty| {
3455734879 const struct_ty = opt_ty orelse continue;
34558 try struct_ty.resolveStructFieldInits(mod);
34880 try struct_ty.resolveStructFieldInits(pt);
3455934881
34560 const uncoerced_field_val = try struct_ty.structFieldValueComptime(mod, field_index) orelse {
34882 const uncoerced_field_val = try struct_ty.structFieldValueComptime(pt, field_index) orelse {
3456134883 comptime_val = null;
3456234884 break;
3456334885 };
......@@ -34584,7 +34906,7 @@ fn resolvePeerTypesInner(
3458434906 field_val.* = if (comptime_val) |v| v.toIntern() else .none;
3458534907 }
3458634908
34587 const final_ty = try ip.getAnonStructType(mod.gpa, .{
34909 const final_ty = try ip.getAnonStructType(mod.gpa, pt.tid, .{
3458834910 .types = field_types,
3458934911 .names = if (is_tuple) &.{} else field_names,
3459034912 .values = field_vals,
......@@ -34628,13 +34950,15 @@ fn maybeMergeErrorSets(sema: *Sema, block: *Block, src: LazySrcLoc, e0: Type, e1
3462834950}
3462934951
3463034952fn resolvePairInMemoryCoercible(sema: *Sema, block: *Block, src: LazySrcLoc, ty_a: Type, ty_b: Type) !?Type {
34953 const target = sema.pt.zcu.getTarget();
34954
3463134955 // ty_b -> ty_a
34632 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, true, sema.mod.getTarget(), src, src)) {
34956 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, true, target, src, src)) {
3463334957 return ty_a;
3463434958 }
3463534959
3463634960 // ty_a -> ty_b
34637 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, true, sema.mod.getTarget(), src, src)) {
34961 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, true, target, src, src)) {
3463834962 return ty_b;
3463934963 }
3464034964
......@@ -34647,7 +34971,8 @@ const ArrayLike = struct {
3464734971 elem_ty: Type,
3464834972};
3464934973fn typeIsArrayLike(sema: *Sema, ty: Type) ?ArrayLike {
34650 const mod = sema.mod;
34974 const pt = sema.pt;
34975 const mod = pt.zcu;
3465134976 return switch (ty.zigTypeTag(mod)) {
3465234977 .Array => .{
3465334978 .len = ty.arrayLen(mod),
......@@ -34676,7 +35001,8 @@ fn typeIsArrayLike(sema: *Sema, ty: Type) ?ArrayLike {
3467635001}
3467735002
3467835003pub fn resolveIes(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError!void {
34679 const mod = sema.mod;
35004 const pt = sema.pt;
35005 const mod = pt.zcu;
3468035006 const ip = &mod.intern_pool;
3468135007
3468235008 if (sema.fn_ret_ty_ies) |ies| {
......@@ -34687,26 +35013,27 @@ pub fn resolveIes(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError!void
3468735013}
3468835014
3468935015pub fn resolveFnTypes(sema: *Sema, fn_ty: Type) CompileError!void {
34690 const mod = sema.mod;
35016 const pt = sema.pt;
35017 const mod = pt.zcu;
3469135018 const ip = &mod.intern_pool;
3469235019 const fn_ty_info = mod.typeToFunc(fn_ty).?;
3469335020
34694 try Type.fromInterned(fn_ty_info.return_type).resolveFully(mod);
35021 try Type.fromInterned(fn_ty_info.return_type).resolveFully(pt);
3469535022
3469635023 if (mod.comp.config.any_error_tracing and
3469735024 Type.fromInterned(fn_ty_info.return_type).isError(mod))
3469835025 {
3469935026 // Ensure the type exists so that backends can assume that.
34700 _ = try mod.getBuiltinType("StackTrace");
35027 _ = try pt.getBuiltinType("StackTrace");
3470135028 }
3470235029
3470335030 for (0..fn_ty_info.param_types.len) |i| {
34704 try Type.fromInterned(fn_ty_info.param_types.get(ip)[i]).resolveFully(mod);
35031 try Type.fromInterned(fn_ty_info.param_types.get(ip)[i]).resolveFully(pt);
3470535032 }
3470635033}
3470735034
3470835035fn resolveLazyValue(sema: *Sema, val: Value) CompileError!Value {
34709 return val.resolveLazy(sema.arena, sema.mod);
35036 return val.resolveLazy(sema.arena, sema.pt);
3471035037}
3471135038
3471235039/// Resolve a struct's alignment only without triggering resolution of its layout.
......@@ -34716,7 +35043,8 @@ pub fn resolveStructAlignment(
3471635043 ty: InternPool.Index,
3471735044 struct_type: InternPool.LoadedStructType,
3471835045) SemaError!void {
34719 const mod = sema.mod;
35046 const pt = sema.pt;
35047 const mod = pt.zcu;
3472035048 const ip = &mod.intern_pool;
3472135049 const target = mod.getTarget();
3472235050
......@@ -34754,7 +35082,7 @@ pub fn resolveStructAlignment(
3475435082 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
3475535083 if (struct_type.fieldIsComptime(ip, i) or try sema.typeRequiresComptime(field_ty))
3475635084 continue;
34757 const field_align = try mod.structFieldAlignmentAdvanced(
35085 const field_align = try pt.structFieldAlignmentAdvanced(
3475835086 struct_type.fieldAlign(ip, i),
3475935087 field_ty,
3476035088 struct_type.layout,
......@@ -34767,7 +35095,8 @@ pub fn resolveStructAlignment(
3476735095}
3476835096
3476935097pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
34770 const zcu = sema.mod;
35098 const pt = sema.pt;
35099 const zcu = pt.zcu;
3477135100 const ip = &zcu.intern_pool;
3477235101 const struct_type = zcu.typeToStruct(ty) orelse return;
3477335102
......@@ -34776,10 +35105,10 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3477635105 if (struct_type.haveLayout(ip))
3477735106 return;
3477835107
34779 try ty.resolveFields(zcu);
35108 try ty.resolveFields(pt);
3478035109
3478135110 if (struct_type.layout == .@"packed") {
34782 semaBackingIntType(zcu, struct_type) catch |err| switch (err) {
35111 semaBackingIntType(pt, struct_type) catch |err| switch (err) {
3478335112 error.OutOfMemory, error.AnalysisFail => |e| return e,
3478435113 error.ComptimeBreak, error.ComptimeReturn, error.GenericPoison => unreachable,
3478535114 };
......@@ -34790,7 +35119,7 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3479035119 const msg = try sema.errMsg(
3479135120 ty.srcLoc(zcu),
3479235121 "struct '{}' depends on itself",
34793 .{ty.fmt(zcu)},
35122 .{ty.fmt(pt)},
3479435123 );
3479535124 return sema.failWithOwnedErrorMsg(null, msg);
3479635125 }
......@@ -34818,7 +35147,7 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3481835147 },
3481935148 else => return err,
3482035149 };
34821 field_align.* = try zcu.structFieldAlignmentAdvanced(
35150 field_align.* = try pt.structFieldAlignmentAdvanced(
3482235151 struct_type.fieldAlign(ip, i),
3482335152 field_ty,
3482435153 struct_type.layout,
......@@ -34911,7 +35240,8 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3491135240 _ = try sema.typeRequiresComptime(ty);
3491235241}
3491335242
34914fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) CompileError!void {
35243fn semaBackingIntType(pt: Zcu.PerThread, struct_type: InternPool.LoadedStructType) CompileError!void {
35244 const zcu = pt.zcu;
3491535245 const gpa = zcu.gpa;
3491635246 const ip = &zcu.intern_pool;
3491735247
......@@ -34927,7 +35257,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3492735257 defer comptime_err_ret_trace.deinit();
3492835258
3492935259 var sema: Sema = .{
34930 .mod = zcu,
35260 .pt = pt,
3493135261 .gpa = gpa,
3493235262 .arena = analysis_arena.allocator(),
3493335263 .code = zir,
......@@ -34958,7 +35288,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3495835288 var accumulator: u64 = 0;
3495935289 for (0..struct_type.field_types.len) |i| {
3496035290 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
34961 accumulator += try field_ty.bitSizeAdvanced(zcu, .sema);
35291 accumulator += try field_ty.bitSizeAdvanced(pt, .sema);
3496235292 }
3496335293 break :blk accumulator;
3496435294 };
......@@ -35004,7 +35334,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3500435334 if (fields_bit_sum > std.math.maxInt(u16)) {
3500535335 return sema.fail(&block, block.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
3500635336 }
35007 const backing_int_ty = try zcu.intType(.unsigned, @intCast(fields_bit_sum));
35337 const backing_int_ty = try pt.intType(.unsigned, @intCast(fields_bit_sum));
3500835338 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
3500935339 }
3501035340
......@@ -35012,26 +35342,27 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3501235342}
3501335343
3501435344fn checkBackingIntType(sema: *Sema, block: *Block, src: LazySrcLoc, backing_int_ty: Type, fields_bit_sum: u64) CompileError!void {
35015 const mod = sema.mod;
35345 const pt = sema.pt;
35346 const mod = pt.zcu;
3501635347
3501735348 if (!backing_int_ty.isInt(mod)) {
35018 return sema.fail(block, src, "expected backing integer type, found '{}'", .{backing_int_ty.fmt(sema.mod)});
35349 return sema.fail(block, src, "expected backing integer type, found '{}'", .{backing_int_ty.fmt(pt)});
3501935350 }
35020 if (backing_int_ty.bitSize(mod) != fields_bit_sum) {
35351 if (backing_int_ty.bitSize(pt) != fields_bit_sum) {
3502135352 return sema.fail(
3502235353 block,
3502335354 src,
3502435355 "backing integer type '{}' has bit size {} but the struct fields have a total bit size of {}",
35025 .{ backing_int_ty.fmt(sema.mod), backing_int_ty.bitSize(mod), fields_bit_sum },
35356 .{ backing_int_ty.fmt(pt), backing_int_ty.bitSize(pt), fields_bit_sum },
3502635357 );
3502735358 }
3502835359}
3502935360
3503035361fn checkIndexable(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
35031 const mod = sema.mod;
35032 if (!ty.isIndexable(mod)) {
35362 const pt = sema.pt;
35363 if (!ty.isIndexable(pt.zcu)) {
3503335364 const msg = msg: {
35034 const msg = try sema.errMsg(src, "type '{}' does not support indexing", .{ty.fmt(sema.mod)});
35365 const msg = try sema.errMsg(src, "type '{}' does not support indexing", .{ty.fmt(pt)});
3503535366 errdefer msg.destroy(sema.gpa);
3503635367 try sema.errNote(src, msg, "operand must be an array, slice, tuple, or vector", .{});
3503735368 break :msg msg;
......@@ -35041,7 +35372,8 @@ fn checkIndexable(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
3504135372}
3504235373
3504335374fn checkMemOperand(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
35044 const mod = sema.mod;
35375 const pt = sema.pt;
35376 const mod = pt.zcu;
3504535377 if (ty.zigTypeTag(mod) == .Pointer) {
3504635378 switch (ty.ptrSize(mod)) {
3504735379 .Slice, .Many, .C => return,
......@@ -35054,7 +35386,7 @@ fn checkMemOperand(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void
3505435386 }
3505535387 }
3505635388 const msg = msg: {
35057 const msg = try sema.errMsg(src, "type '{}' is not an indexable pointer", .{ty.fmt(sema.mod)});
35389 const msg = try sema.errMsg(src, "type '{}' is not an indexable pointer", .{ty.fmt(pt)});
3505835390 errdefer msg.destroy(sema.gpa);
3505935391 try sema.errNote(src, msg, "operand must be a slice, a many pointer or a pointer to an array", .{});
3506035392 break :msg msg;
......@@ -35069,9 +35401,9 @@ pub fn resolveUnionAlignment(
3506935401 ty: Type,
3507035402 union_type: InternPool.LoadedUnionType,
3507135403) SemaError!void {
35072 const mod = sema.mod;
35073 const ip = &mod.intern_pool;
35074 const target = mod.getTarget();
35404 const zcu = sema.pt.zcu;
35405 const ip = &zcu.intern_pool;
35406 const target = zcu.getTarget();
3507535407
3507635408 assert(sema.ownerUnit().unwrap().decl == union_type.decl);
3507735409
......@@ -35108,8 +35440,8 @@ pub fn resolveUnionAlignment(
3510835440
3510935441/// This logic must be kept in sync with `Module.getUnionLayout`.
3511035442pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
35111 const zcu = sema.mod;
35112 const ip = &zcu.intern_pool;
35443 const pt = sema.pt;
35444 const ip = &pt.zcu.intern_pool;
3511335445
3511435446 try sema.resolveTypeFieldsUnion(ty, ip.loadUnionType(ty.ip_index));
3511535447
......@@ -35122,9 +35454,9 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3512235454 .none, .have_field_types => {},
3512335455 .field_types_wip, .layout_wip => {
3512435456 const msg = try sema.errMsg(
35125 ty.srcLoc(zcu),
35457 ty.srcLoc(pt.zcu),
3512635458 "union '{}' depends on itself",
35127 .{ty.fmt(zcu)},
35459 .{ty.fmt(pt)},
3512835460 );
3512935461 return sema.failWithOwnedErrorMsg(null, msg);
3513035462 },
......@@ -35143,7 +35475,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3514335475 for (0..union_type.field_types.len) |field_index| {
3514435476 const field_ty = Type.fromInterned(union_type.field_types.get(ip)[field_index]);
3514535477
35146 if (try sema.typeRequiresComptime(field_ty) or field_ty.zigTypeTag(zcu) == .NoReturn) continue; // TODO: should this affect alignment?
35478 if (try sema.typeRequiresComptime(field_ty) or field_ty.zigTypeTag(pt.zcu) == .NoReturn) continue; // TODO: should this affect alignment?
3514735479
3514835480 max_size = @max(max_size, sema.typeAbiSize(field_ty) catch |err| switch (err) {
3514935481 error.AnalysisFail => {
......@@ -35185,7 +35517,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3518535517 } else {
3518635518 // {Payload, Tag}
3518735519 size += max_size;
35188 size = switch (zcu.getTarget().ofmt) {
35520 size = switch (pt.zcu.getTarget().ofmt) {
3518935521 .c => max_align,
3519035522 else => tag_align,
3519135523 }.forward(size);
......@@ -35205,7 +35537,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3520535537
3520635538 if (union_type.flagsPtr(ip).assumed_runtime_bits and !(try sema.typeHasRuntimeBits(ty))) {
3520735539 const msg = try sema.errMsg(
35208 ty.srcLoc(zcu),
35540 ty.srcLoc(pt.zcu),
3520935541 "union layout depends on it having runtime bits",
3521035542 .{},
3521135543 );
......@@ -35213,10 +35545,10 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3521335545 }
3521435546
3521535547 if (union_type.flagsPtr(ip).assumed_pointer_aligned and
35216 alignment.compareStrict(.neq, Alignment.fromByteUnits(@divExact(zcu.getTarget().ptrBitWidth(), 8))))
35548 alignment.compareStrict(.neq, Alignment.fromByteUnits(@divExact(pt.zcu.getTarget().ptrBitWidth(), 8))))
3521735549 {
3521835550 const msg = try sema.errMsg(
35219 ty.srcLoc(zcu),
35551 ty.srcLoc(pt.zcu),
3522035552 "union layout depends on being pointer aligned",
3522135553 .{},
3522235554 );
......@@ -35229,7 +35561,8 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3522935561pub fn resolveStructFully(sema: *Sema, ty: Type) SemaError!void {
3523035562 try sema.resolveStructLayout(ty);
3523135563
35232 const mod = sema.mod;
35564 const pt = sema.pt;
35565 const mod = pt.zcu;
3523335566 const ip = &mod.intern_pool;
3523435567 const struct_type = mod.typeToStruct(ty).?;
3523535568
......@@ -35244,14 +35577,15 @@ pub fn resolveStructFully(sema: *Sema, ty: Type) SemaError!void {
3524435577
3524535578 for (0..struct_type.field_types.len) |i| {
3524635579 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
35247 try field_ty.resolveFully(mod);
35580 try field_ty.resolveFully(pt);
3524835581 }
3524935582}
3525035583
3525135584pub fn resolveUnionFully(sema: *Sema, ty: Type) SemaError!void {
3525235585 try sema.resolveUnionLayout(ty);
3525335586
35254 const mod = sema.mod;
35587 const pt = sema.pt;
35588 const mod = pt.zcu;
3525535589 const ip = &mod.intern_pool;
3525635590 const union_obj = mod.typeToUnion(ty).?;
3525735591
......@@ -35272,7 +35606,7 @@ pub fn resolveUnionFully(sema: *Sema, ty: Type) SemaError!void {
3527235606 union_obj.flagsPtr(ip).status = .fully_resolved_wip;
3527335607 for (0..union_obj.field_types.len) |field_index| {
3527435608 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
35275 try field_ty.resolveFully(mod);
35609 try field_ty.resolveFully(pt);
3527635610 }
3527735611 union_obj.flagsPtr(ip).status = .fully_resolved;
3527835612 }
......@@ -35286,7 +35620,8 @@ pub fn resolveTypeFieldsStruct(
3528635620 ty: InternPool.Index,
3528735621 struct_type: InternPool.LoadedStructType,
3528835622) SemaError!void {
35289 const zcu = sema.mod;
35623 const pt = sema.pt;
35624 const zcu = pt.zcu;
3529035625 const ip = &zcu.intern_pool;
3529135626 // If there is no owner decl it means the struct has no fields.
3529235627 const owner_decl = struct_type.decl.unwrap() orelse return;
......@@ -35310,13 +35645,13 @@ pub fn resolveTypeFieldsStruct(
3531035645 const msg = try sema.errMsg(
3531135646 Type.fromInterned(ty).srcLoc(zcu),
3531235647 "struct '{}' depends on itself",
35313 .{Type.fromInterned(ty).fmt(zcu)},
35648 .{Type.fromInterned(ty).fmt(pt)},
3531435649 );
3531535650 return sema.failWithOwnedErrorMsg(null, msg);
3531635651 }
3531735652 defer struct_type.clearTypesWip(ip);
3531835653
35319 semaStructFields(zcu, sema.arena, struct_type) catch |err| switch (err) {
35654 semaStructFields(pt, sema.arena, struct_type) catch |err| switch (err) {
3532035655 error.AnalysisFail => {
3532135656 if (zcu.declPtr(owner_decl).analysis == .complete) {
3532235657 zcu.declPtr(owner_decl).analysis = .dependency_failure;
......@@ -35329,7 +35664,8 @@ pub fn resolveTypeFieldsStruct(
3532935664}
3533035665
3533135666pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
35332 const zcu = sema.mod;
35667 const pt = sema.pt;
35668 const zcu = pt.zcu;
3533335669 const ip = &zcu.intern_pool;
3533435670 const struct_type = zcu.typeToStruct(ty) orelse return;
3533535671 const owner_decl = struct_type.decl.unwrap() orelse return;
......@@ -35345,13 +35681,13 @@ pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
3534535681 const msg = try sema.errMsg(
3534635682 ty.srcLoc(zcu),
3534735683 "struct '{}' depends on itself",
35348 .{ty.fmt(zcu)},
35684 .{ty.fmt(pt)},
3534935685 );
3535035686 return sema.failWithOwnedErrorMsg(null, msg);
3535135687 }
3535235688 defer struct_type.clearInitsWip(ip);
3535335689
35354 semaStructFieldInits(zcu, sema.arena, struct_type) catch |err| switch (err) {
35690 semaStructFieldInits(pt, sema.arena, struct_type) catch |err| switch (err) {
3535535691 error.AnalysisFail => {
3535635692 if (zcu.declPtr(owner_decl).analysis == .complete) {
3535735693 zcu.declPtr(owner_decl).analysis = .dependency_failure;
......@@ -35365,7 +35701,8 @@ pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
3536535701}
3536635702
3536735703pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.LoadedUnionType) SemaError!void {
35368 const zcu = sema.mod;
35704 const pt = sema.pt;
35705 const zcu = pt.zcu;
3536935706 const ip = &zcu.intern_pool;
3537035707 const owner_decl = zcu.declPtr(union_type.decl);
3537135708
......@@ -35387,7 +35724,7 @@ pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.Load
3538735724 const msg = try sema.errMsg(
3538835725 ty.srcLoc(zcu),
3538935726 "union '{}' depends on itself",
35390 .{ty.fmt(zcu)},
35727 .{ty.fmt(pt)},
3539135728 );
3539235729 return sema.failWithOwnedErrorMsg(null, msg);
3539335730 },
......@@ -35401,7 +35738,7 @@ pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.Load
3540135738
3540235739 union_type.flagsPtr(ip).status = .field_types_wip;
3540335740 errdefer union_type.flagsPtr(ip).status = .none;
35404 semaUnionFields(zcu, sema.arena, union_type) catch |err| switch (err) {
35741 semaUnionFields(pt, sema.arena, union_type) catch |err| switch (err) {
3540535742 error.AnalysisFail => {
3540635743 if (owner_decl.analysis == .complete) {
3540735744 owner_decl.analysis = .dependency_failure;
......@@ -35422,7 +35759,8 @@ fn resolveInferredErrorSet(
3542235759 src: LazySrcLoc,
3542335760 ies_index: InternPool.Index,
3542435761) CompileError!InternPool.Index {
35425 const mod = sema.mod;
35762 const pt = sema.pt;
35763 const mod = pt.zcu;
3542635764 const ip = &mod.intern_pool;
3542735765 const func_index = ip.iesFuncIndex(ies_index);
3542835766 const func = mod.funcInfo(func_index);
......@@ -35482,8 +35820,8 @@ pub fn resolveInferredErrorSetPtr(
3548235820 src: LazySrcLoc,
3548335821 ies: *InferredErrorSet,
3548435822) CompileError!void {
35485 const mod = sema.mod;
35486 const ip = &mod.intern_pool;
35823 const pt = sema.pt;
35824 const ip = &pt.zcu.intern_pool;
3548735825
3548835826 if (ies.resolved != .none) return;
3548935827
......@@ -35505,7 +35843,7 @@ pub fn resolveInferredErrorSetPtr(
3550535843 }
3550635844 }
3550735845
35508 const resolved_error_set_ty = try mod.errorSetFromUnsortedNames(ies.errors.keys());
35846 const resolved_error_set_ty = try pt.errorSetFromUnsortedNames(ies.errors.keys());
3550935847 ies.resolved = resolved_error_set_ty.toIntern();
3551035848}
3551135849
......@@ -35515,12 +35853,13 @@ fn resolveAdHocInferredErrorSet(
3551535853 src: LazySrcLoc,
3551635854 value: InternPool.Index,
3551735855) CompileError!InternPool.Index {
35518 const mod = sema.mod;
35856 const pt = sema.pt;
35857 const mod = pt.zcu;
3551935858 const gpa = sema.gpa;
3552035859 const ip = &mod.intern_pool;
3552135860 const new_ty = try resolveAdHocInferredErrorSetTy(sema, block, src, ip.typeOf(value));
3552235861 if (new_ty == .none) return value;
35523 return ip.getCoerced(gpa, value, new_ty);
35862 return ip.getCoerced(gpa, pt.tid, value, new_ty);
3552435863}
3552535864
3552635865fn resolveAdHocInferredErrorSetTy(
......@@ -35530,8 +35869,8 @@ fn resolveAdHocInferredErrorSetTy(
3553035869 ty: InternPool.Index,
3553135870) CompileError!InternPool.Index {
3553235871 const ies = sema.fn_ret_ty_ies orelse return .none;
35533 const mod = sema.mod;
35534 const gpa = sema.gpa;
35872 const pt = sema.pt;
35873 const mod = pt.zcu;
3553535874 const ip = &mod.intern_pool;
3553635875 const error_union_info = switch (ip.indexToKey(ty)) {
3553735876 .error_union_type => |x| x,
......@@ -35541,7 +35880,7 @@ fn resolveAdHocInferredErrorSetTy(
3554135880 return .none;
3554235881
3554335882 try sema.resolveInferredErrorSetPtr(block, src, ies);
35544 const new_ty = try ip.get(gpa, .{ .error_union_type = .{
35883 const new_ty = try pt.intern(.{ .error_union_type = .{
3554535884 .error_set_type = ies.resolved,
3554635885 .payload_type = error_union_info.payload_type,
3554735886 } });
......@@ -35554,7 +35893,8 @@ fn resolveInferredErrorSetTy(
3555435893 src: LazySrcLoc,
3555535894 ty: InternPool.Index,
3555635895) CompileError!InternPool.Index {
35557 const mod = sema.mod;
35896 const pt = sema.pt;
35897 const mod = pt.zcu;
3555835898 const ip = &mod.intern_pool;
3555935899 if (ty == .anyerror_type) return ty;
3556035900 switch (ip.indexToKey(ty)) {
......@@ -35614,10 +35954,11 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
3561435954}
3561535955
3561635956fn semaStructFields(
35617 zcu: *Zcu,
35957 pt: Zcu.PerThread,
3561835958 arena: Allocator,
3561935959 struct_type: InternPool.LoadedStructType,
3562035960) CompileError!void {
35961 const zcu = pt.zcu;
3562135962 const gpa = zcu.gpa;
3562235963 const ip = &zcu.intern_pool;
3562335964 const decl_index = struct_type.decl.unwrap() orelse return;
......@@ -35630,7 +35971,7 @@ fn semaStructFields(
3563035971
3563135972 if (fields_len == 0) switch (struct_type.layout) {
3563235973 .@"packed" => {
35633 try semaBackingIntType(zcu, struct_type);
35974 try semaBackingIntType(pt, struct_type);
3563435975 return;
3563535976 },
3563635977 .auto, .@"extern" => {
......@@ -35644,7 +35985,7 @@ fn semaStructFields(
3564435985 defer comptime_err_ret_trace.deinit();
3564535986
3564635987 var sema: Sema = .{
35647 .mod = zcu,
35988 .pt = pt,
3564835989 .gpa = gpa,
3564935990 .arena = arena,
3565035991 .code = zir,
......@@ -35789,7 +36130,7 @@ fn semaStructFields(
3578936130 switch (struct_type.layout) {
3579036131 .@"extern" => if (!try sema.validateExternType(field_ty, .struct_field)) {
3579136132 const msg = msg: {
35792 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36133 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3579336134 errdefer msg.destroy(sema.gpa);
3579436135
3579536136 try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .struct_field);
......@@ -35801,7 +36142,7 @@ fn semaStructFields(
3580136142 },
3580236143 .@"packed" => if (!try sema.validatePackedType(field_ty)) {
3580336144 const msg = msg: {
35804 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36145 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3580536146 errdefer msg.destroy(sema.gpa);
3580636147
3580736148 try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);
......@@ -35837,10 +36178,11 @@ fn semaStructFields(
3583736178
3583836179// This logic must be kept in sync with `semaStructFields`
3583936180fn semaStructFieldInits(
35840 zcu: *Zcu,
36181 pt: Zcu.PerThread,
3584136182 arena: Allocator,
3584236183 struct_type: InternPool.LoadedStructType,
3584336184) CompileError!void {
36185 const zcu = pt.zcu;
3584436186 const gpa = zcu.gpa;
3584536187 const ip = &zcu.intern_pool;
3584636188
......@@ -35857,7 +36199,7 @@ fn semaStructFieldInits(
3585736199 defer comptime_err_ret_trace.deinit();
3585836200
3585936201 var sema: Sema = .{
35860 .mod = zcu,
36202 .pt = pt,
3586136203 .gpa = gpa,
3586236204 .arena = arena,
3586336205 .code = zir,
......@@ -35977,10 +36319,11 @@ fn semaStructFieldInits(
3597736319 try sema.flushExports();
3597836320}
3597936321
35980fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
36322fn semaUnionFields(pt: Zcu.PerThread, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
3598136323 const tracy = trace(@src());
3598236324 defer tracy.end();
3598336325
36326 const zcu = pt.zcu;
3598436327 const gpa = zcu.gpa;
3598536328 const ip = &zcu.intern_pool;
3598636329 const decl_index = union_type.decl;
......@@ -36034,7 +36377,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3603436377 defer comptime_err_ret_trace.deinit();
3603536378
3603636379 var sema: Sema = .{
36037 .mod = zcu,
36380 .pt = pt,
3603836381 .gpa = gpa,
3603936382 .arena = arena,
3604036383 .code = zir,
......@@ -36081,17 +36424,17 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3608136424 // The provided type is an integer type and we must construct the enum tag type here.
3608236425 int_tag_ty = provided_ty;
3608336426 if (int_tag_ty.zigTypeTag(zcu) != .Int and int_tag_ty.zigTypeTag(zcu) != .ComptimeInt) {
36084 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(zcu)});
36427 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(pt)});
3608536428 }
3608636429
3608736430 if (fields_len > 0) {
36088 const field_count_val = try zcu.intValue(Type.comptime_int, fields_len - 1);
36431 const field_count_val = try pt.intValue(Type.comptime_int, fields_len - 1);
3608936432 if (!(try sema.intFitsInType(field_count_val, int_tag_ty, null))) {
3609036433 const msg = msg: {
3609136434 const msg = try sema.errMsg(tag_ty_src, "specified integer tag type cannot represent every field", .{});
3609236435 errdefer msg.destroy(sema.gpa);
3609336436 try sema.errNote(tag_ty_src, msg, "type '{}' cannot fit values in range 0...{d}", .{
36094 int_tag_ty.fmt(zcu),
36437 int_tag_ty.fmt(pt),
3609536438 fields_len - 1,
3609636439 });
3609736440 break :msg msg;
......@@ -36106,7 +36449,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3610636449 union_type.tagTypePtr(ip).* = provided_ty.toIntern();
3610736450 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {
3610836451 .enum_type => ip.loadEnumType(provided_ty.toIntern()),
36109 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(zcu)}),
36452 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(pt)}),
3611036453 };
3611136454 // The fields of the union must match the enum exactly.
3611236455 // A flag per field is used to check for missing and extraneous fields.
......@@ -36202,7 +36545,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3620236545 const val = if (last_tag_val) |val|
3620336546 try sema.intAdd(val, Value.one_comptime_int, int_tag_ty, undefined)
3620436547 else
36205 try zcu.intValue(int_tag_ty, 0);
36548 try pt.intValue(int_tag_ty, 0);
3620636549 last_tag_val = val;
3620736550
3620836551 break :blk val;
......@@ -36214,7 +36557,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3621436557 .offset = .{ .container_field_value = @intCast(gop.index) },
3621536558 };
3621636559 const msg = msg: {
36217 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(zcu, &sema)});
36560 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(pt, &sema)});
3621836561 errdefer msg.destroy(gpa);
3621936562 try sema.errNote(other_value_src, msg, "other occurrence here", .{});
3622036563 break :msg msg;
......@@ -36244,7 +36587,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3624436587 const tag_info = ip.loadEnumType(union_type.tagTypePtr(ip).*);
3624536588 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
3624636589 return sema.fail(&block_scope, name_src, "no field named '{}' in enum '{}'", .{
36247 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(zcu),
36590 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(pt),
3624836591 });
3624936592 };
3625036593
......@@ -36286,7 +36629,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3628636629 !try sema.validateExternType(field_ty, .union_field))
3628736630 {
3628836631 const msg = msg: {
36289 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36632 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3629036633 errdefer msg.destroy(sema.gpa);
3629136634
3629236635 try sema.explainWhyTypeIsNotExtern(msg, type_src, field_ty, .union_field);
......@@ -36297,7 +36640,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3629736640 return sema.failWithOwnedErrorMsg(&block_scope, msg);
3629836641 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
3629936642 const msg = msg: {
36300 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36643 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3630136644 errdefer msg.destroy(sema.gpa);
3630236645
3630336646 try sema.explainWhyTypeIsNotPacked(msg, type_src, field_ty);
......@@ -36366,7 +36709,8 @@ fn generateUnionTagTypeNumbered(
3636636709 enum_field_vals: []const InternPool.Index,
3636736710 union_owner_decl: *Module.Decl,
3636836711) !InternPool.Index {
36369 const mod = sema.mod;
36712 const pt = sema.pt;
36713 const mod = pt.zcu;
3637036714 const gpa = sema.gpa;
3637136715 const ip = &mod.intern_pool;
3637236716
......@@ -36390,11 +36734,11 @@ fn generateUnionTagTypeNumbered(
3639036734 new_decl.owns_tv = true;
3639136735 new_decl.name_fully_qualified = true;
3639236736
36393 const enum_ty = try ip.getGeneratedTagEnumType(gpa, .{
36737 const enum_ty = try ip.getGeneratedTagEnumType(gpa, pt.tid, .{
3639436738 .decl = new_decl_index,
3639536739 .owner_union_ty = union_owner_decl.val.toIntern(),
3639636740 .tag_ty = if (enum_field_vals.len == 0)
36397 (try mod.intType(.unsigned, 0)).toIntern()
36741 (try pt.intType(.unsigned, 0)).toIntern()
3639836742 else
3639936743 ip.typeOf(enum_field_vals[0]),
3640036744 .names = enum_field_names,
......@@ -36404,7 +36748,7 @@ fn generateUnionTagTypeNumbered(
3640436748
3640536749 new_decl.val = Value.fromInterned(enum_ty);
3640636750
36407 try mod.finalizeAnonDecl(new_decl_index);
36751 try pt.finalizeAnonDecl(new_decl_index);
3640836752 return enum_ty;
3640936753}
3641036754
......@@ -36414,7 +36758,8 @@ fn generateUnionTagTypeSimple(
3641436758 enum_field_names: []const InternPool.NullTerminatedString,
3641536759 union_owner_decl: *Module.Decl,
3641636760) !InternPool.Index {
36417 const mod = sema.mod;
36761 const pt = sema.pt;
36762 const mod = pt.zcu;
3641836763 const ip = &mod.intern_pool;
3641936764 const gpa = sema.gpa;
3642036765
......@@ -36438,13 +36783,13 @@ fn generateUnionTagTypeSimple(
3643836783 };
3643936784 errdefer mod.abortAnonDecl(new_decl_index);
3644036785
36441 const enum_ty = try ip.getGeneratedTagEnumType(gpa, .{
36786 const enum_ty = try ip.getGeneratedTagEnumType(gpa, pt.tid, .{
3644236787 .decl = new_decl_index,
3644336788 .owner_union_ty = union_owner_decl.val.toIntern(),
3644436789 .tag_ty = if (enum_field_names.len == 0)
36445 (try mod.intType(.unsigned, 0)).toIntern()
36790 (try pt.intType(.unsigned, 0)).toIntern()
3644636791 else
36447 (try mod.smallestUnsignedInt(enum_field_names.len - 1)).toIntern(),
36792 (try pt.smallestUnsignedInt(enum_field_names.len - 1)).toIntern(),
3644836793 .names = enum_field_names,
3644936794 .values = &.{},
3645036795 .tag_mode = .auto,
......@@ -36454,7 +36799,7 @@ fn generateUnionTagTypeSimple(
3645436799 new_decl.owns_tv = true;
3645536800 new_decl.val = Value.fromInterned(enum_ty);
3645636801
36457 try mod.finalizeAnonDecl(new_decl_index);
36802 try pt.finalizeAnonDecl(new_decl_index);
3645836803 return enum_ty;
3645936804}
3646036805
......@@ -36464,12 +36809,13 @@ fn generateUnionTagTypeSimple(
3646436809/// that the types are already resolved.
3646536810/// TODO assert the return value matches `ty.onePossibleValue`
3646636811pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
36467 const zcu = sema.mod;
36812 const pt = sema.pt;
36813 const zcu = pt.zcu;
3646836814 const ip = &zcu.intern_pool;
3646936815 return switch (ty.toIntern()) {
3647036816 .u0_type,
3647136817 .i0_type,
36472 => try zcu.intValue(ty, 0),
36818 => try pt.intValue(ty, 0),
3647336819 .u1_type,
3647436820 .u8_type,
3647536821 .i8_type,
......@@ -36532,7 +36878,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3653236878 .anyframe_type => unreachable,
3653336879 .null_type => Value.null,
3653436880 .undefined_type => Value.undef,
36535 .optional_noreturn_type => try zcu.nullValue(ty),
36881 .optional_noreturn_type => try pt.nullValue(ty),
3653636882 .generic_poison_type => error.GenericPoison,
3653736883 .empty_struct_type => Value.empty_struct,
3653836884 // values, not types
......@@ -36646,16 +36992,16 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3664636992 => switch (ip.indexToKey(ty.toIntern())) {
3664736993 inline .array_type, .vector_type => |seq_type, seq_tag| {
3664836994 const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
36649 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
36995 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3665036996 .ty = ty.toIntern(),
3665136997 .storage = .{ .elems = &.{} },
36652 } })));
36998 } }));
3665336999
3665437000 if (try sema.typeHasOnePossibleValue(Type.fromInterned(seq_type.child))) |opv| {
36655 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37001 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3665637002 .ty = ty.toIntern(),
3665737003 .storage = .{ .repeated_elem = opv.toIntern() },
36658 } })));
37004 } }));
3665937005 }
3666037006 return null;
3666137007 },
......@@ -36663,17 +37009,17 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3666337009 .struct_type => {
3666437010 // Resolving the layout first helps to avoid loops.
3666537011 // If the type has a coherent layout, we can recurse through fields safely.
36666 try ty.resolveLayout(zcu);
37012 try ty.resolveLayout(pt);
3666737013
3666837014 const struct_type = ip.loadStructType(ty.toIntern());
3666937015
3667037016 if (struct_type.field_types.len == 0) {
3667137017 // In this case the struct has no fields at all and
3667237018 // therefore has one possible value.
36673 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37019 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3667437020 .ty = ty.toIntern(),
3667537021 .storage = .{ .elems = &.{} },
36676 } })));
37022 } }));
3667737023 }
3667837024
3667937025 const field_vals = try sema.arena.alloc(
......@@ -36682,7 +37028,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3668237028 );
3668337029 for (field_vals, 0..) |*field_val, i| {
3668437030 if (struct_type.fieldIsComptime(ip, i)) {
36685 try ty.resolveStructFieldInits(zcu);
37031 try ty.resolveStructFieldInits(pt);
3668637032 field_val.* = struct_type.field_inits.get(ip)[i];
3668737033 continue;
3668837034 }
......@@ -36694,10 +37040,10 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3669437040
3669537041 // In this case the struct has no runtime-known fields and
3669637042 // therefore has one possible value.
36697 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37043 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3669837044 .ty = ty.toIntern(),
3669937045 .storage = .{ .elems = field_vals },
36700 } })));
37046 } }));
3670137047 },
3670237048
3670337049 .anon_struct_type => |tuple| {
......@@ -36707,28 +37053,28 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3670737053 // In this case the struct has all comptime-known fields and
3670837054 // therefore has one possible value.
3670937055 // TODO: write something like getCoercedInts to avoid needing to dupe
36710 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37056 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3671137057 .ty = ty.toIntern(),
3671237058 .storage = .{ .elems = try sema.arena.dupe(InternPool.Index, tuple.values.get(ip)) },
36713 } })));
37059 } }));
3671437060 },
3671537061
3671637062 .union_type => {
3671737063 // Resolving the layout first helps to avoid loops.
3671837064 // If the type has a coherent layout, we can recurse through fields safely.
36719 try ty.resolveLayout(zcu);
37065 try ty.resolveLayout(pt);
3672037066
3672137067 const union_obj = ip.loadUnionType(ty.toIntern());
3672237068 const tag_val = (try sema.typeHasOnePossibleValue(Type.fromInterned(union_obj.tagTypePtr(ip).*))) orelse
3672337069 return null;
3672437070 if (union_obj.field_types.len == 0) {
36725 const only = try zcu.intern(.{ .empty_enum_value = ty.toIntern() });
37071 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
3672637072 return Value.fromInterned(only);
3672737073 }
3672837074 const only_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
3672937075 const val_val = (try sema.typeHasOnePossibleValue(only_field_ty)) orelse
3673037076 return null;
36731 const only = try zcu.intern(.{ .un = .{
37077 const only = try pt.intern(.{ .un = .{
3673237078 .ty = ty.toIntern(),
3673337079 .tag = tag_val.toIntern(),
3673437080 .val = val_val.toIntern(),
......@@ -36743,7 +37089,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3674337089 if (enum_type.tag_ty == .comptime_int_type) return null;
3674437090
3674537091 if (try sema.typeHasOnePossibleValue(Type.fromInterned(enum_type.tag_ty))) |int_opv| {
36746 const only = try zcu.intern(.{ .enum_tag = .{
37092 const only = try pt.intern(.{ .enum_tag = .{
3674737093 .ty = ty.toIntern(),
3674837094 .int = int_opv.toIntern(),
3674937095 } });
......@@ -36753,18 +37099,19 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3675337099 return null;
3675437100 },
3675537101 .auto, .explicit => {
36756 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(zcu)) return null;
37102 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(pt)) return null;
3675737103
3675837104 return Value.fromInterned(switch (enum_type.names.len) {
36759 0 => try zcu.intern(.{ .empty_enum_value = ty.toIntern() }),
36760 1 => try zcu.intern(.{ .enum_tag = .{
37105 0 => try pt.intern(.{ .empty_enum_value = ty.toIntern() }),
37106 1 => try pt.intern(.{ .enum_tag = .{
3676137107 .ty = ty.toIntern(),
3676237108 .int = if (enum_type.values.len == 0)
36763 (try zcu.intValue(Type.fromInterned(enum_type.tag_ty), 0)).toIntern()
37109 (try pt.intValue(Type.fromInterned(enum_type.tag_ty), 0)).toIntern()
3676437110 else
36765 try zcu.intern_pool.getCoercedInts(
37111 try ip.getCoercedInts(
3676637112 zcu.gpa,
36767 zcu.intern_pool.indexToKey(enum_type.values.get(ip)[0]).int,
37113 pt.tid,
37114 ip.indexToKey(enum_type.values.get(ip)[0]).int,
3676837115 enum_type.tag_ty,
3676937116 ),
3677037117 } }),
......@@ -36782,7 +37129,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3678237129
3678337130/// Returns the type of the AIR instruction.
3678437131fn typeOf(sema: *Sema, inst: Air.Inst.Ref) Type {
36785 return sema.getTmpAir().typeOf(inst, &sema.mod.intern_pool);
37132 return sema.getTmpAir().typeOf(inst, &sema.pt.zcu.intern_pool);
3678637133}
3678737134
3678837135pub fn getTmpAir(sema: Sema) Air {
......@@ -36838,12 +37185,13 @@ fn analyzeComptimeAlloc(
3683837185 var_type: Type,
3683937186 alignment: Alignment,
3684037187) CompileError!Air.Inst.Ref {
36841 const mod = sema.mod;
37188 const pt = sema.pt;
37189 const mod = pt.zcu;
3684237190
3684337191 // Needed to make an anon decl with type `var_type` (the `finish()` call below).
3684437192 _ = try sema.typeHasOnePossibleValue(var_type);
3684537193
36846 const ptr_type = try mod.ptrTypeSema(.{
37194 const ptr_type = try pt.ptrTypeSema(.{
3684737195 .child = var_type.toIntern(),
3684837196 .flags = .{
3684937197 .alignment = alignment,
......@@ -36853,7 +37201,7 @@ fn analyzeComptimeAlloc(
3685337201
3685437202 const alloc = try sema.newComptimeAlloc(block, var_type, alignment);
3685537203
36856 return Air.internedToRef((try mod.intern(.{ .ptr = .{
37204 return Air.internedToRef((try pt.intern(.{ .ptr = .{
3685737205 .ty = ptr_type.toIntern(),
3685837206 .base_addr = .{ .comptime_alloc = alloc },
3685937207 .byte_offset = 0,
......@@ -36896,13 +37244,14 @@ pub fn analyzeAsAddressSpace(
3689637244 air_ref: Air.Inst.Ref,
3689737245 ctx: AddressSpaceContext,
3689837246) !std.builtin.AddressSpace {
36899 const mod = sema.mod;
37247 const pt = sema.pt;
37248 const mod = pt.zcu;
3690037249 const coerced = try sema.coerce(block, Type.fromInterned(.address_space_type), air_ref, src);
3690137250 const addrspace_val = try sema.resolveConstDefinedValue(block, src, coerced, .{
3690237251 .needed_comptime_reason = "address space must be comptime-known",
3690337252 });
3690437253 const address_space = mod.toEnum(std.builtin.AddressSpace, addrspace_val);
36905 const target = sema.mod.getTarget();
37254 const target = pt.zcu.getTarget();
3690637255 const arch = target.cpu.arch;
3690737256
3690837257 const is_nv = arch == .nvptx or arch == .nvptx64;
......@@ -36946,7 +37295,8 @@ pub fn analyzeAsAddressSpace(
3694637295/// Returns `null` if the pointer contents cannot be loaded at comptime.
3694737296fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr_ty: Type) CompileError!?Value {
3694837297 // TODO: audit use sites to eliminate this coercion
36949 const coerced_ptr_val = try sema.mod.getCoerced(ptr_val, ptr_ty);
37298 const pt = sema.pt;
37299 const coerced_ptr_val = try pt.getCoerced(ptr_val, ptr_ty);
3695037300 switch (try sema.pointerDerefExtra(block, src, coerced_ptr_val)) {
3695137301 .runtime_load => return null,
3695237302 .val => |v| return v,
......@@ -36954,13 +37304,13 @@ fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr
3695437304 block,
3695537305 src,
3695637306 "comptime dereference requires '{}' to have a well-defined layout",
36957 .{ty.fmt(sema.mod)},
37307 .{ty.fmt(pt)},
3695837308 ),
3695937309 .out_of_bounds => |ty| return sema.fail(
3696037310 block,
3696137311 src,
3696237312 "dereference of '{}' exceeds bounds of containing decl of type '{}'",
36963 .{ ptr_ty.fmt(sema.mod), ty.fmt(sema.mod) },
37313 .{ ptr_ty.fmt(pt), ty.fmt(pt) },
3696437314 ),
3696537315 }
3696637316}
......@@ -36973,10 +37323,10 @@ const DerefResult = union(enum) {
3697337323};
3697437324
3697537325fn pointerDerefExtra(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value) CompileError!DerefResult {
36976 const zcu = sema.mod;
36977 const ip = &zcu.intern_pool;
37326 const pt = sema.pt;
37327 const ip = &pt.zcu.intern_pool;
3697837328 switch (try sema.loadComptimePtr(block, src, ptr_val)) {
36979 .success => |mv| return .{ .val = try mv.intern(zcu, sema.arena) },
37329 .success => |mv| return .{ .val = try mv.intern(pt, sema.arena) },
3698037330 .runtime_load => return .runtime_load,
3698137331 .undef => return sema.failWithUseOfUndef(block, src),
3698237332 .err_payload => |err_name| return sema.fail(block, src, "attempt to unwrap error: {}", .{err_name.fmt(ip)}),
......@@ -37001,7 +37351,8 @@ fn usizeCast(sema: *Sema, block: *Block, src: LazySrcLoc, int: u64) CompileError
3700137351/// a type has zero bits, which can cause a "foo depends on itself" compile error.
3700237352/// This logic must be kept in sync with `Type.isPtrLikeOptional`.
3700337353fn typePtrOrOptionalPtrTy(sema: *Sema, ty: Type) !?Type {
37004 const mod = sema.mod;
37354 const pt = sema.pt;
37355 const mod = pt.zcu;
3700537356 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3700637357 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
3700737358 .One, .Many, .C => ty,
......@@ -37031,27 +37382,28 @@ fn typePtrOrOptionalPtrTy(sema: *Sema, ty: Type) !?Type {
3703137382/// `generic_poison` will return false.
3703237383/// May return false negatives when structs and unions are having their field types resolved.
3703337384pub fn typeRequiresComptime(sema: *Sema, ty: Type) SemaError!bool {
37034 return ty.comptimeOnlyAdvanced(sema.mod, .sema);
37385 return ty.comptimeOnlyAdvanced(sema.pt, .sema);
3703537386}
3703637387
3703737388pub fn typeHasRuntimeBits(sema: *Sema, ty: Type) SemaError!bool {
37038 return ty.hasRuntimeBitsAdvanced(sema.mod, false, .sema) catch |err| switch (err) {
37389 return ty.hasRuntimeBitsAdvanced(sema.pt, false, .sema) catch |err| switch (err) {
3703937390 error.NeedLazy => unreachable,
3704037391 else => |e| return e,
3704137392 };
3704237393}
3704337394
3704437395pub fn typeAbiSize(sema: *Sema, ty: Type) SemaError!u64 {
37045 try ty.resolveLayout(sema.mod);
37046 return ty.abiSize(sema.mod);
37396 const pt = sema.pt;
37397 try ty.resolveLayout(pt);
37398 return ty.abiSize(pt);
3704737399}
3704837400
3704937401pub fn typeAbiAlignment(sema: *Sema, ty: Type) SemaError!Alignment {
37050 return (try ty.abiAlignmentAdvanced(sema.mod, .sema)).scalar;
37402 return (try ty.abiAlignmentAdvanced(sema.pt, .sema)).scalar;
3705137403}
3705237404
3705337405pub fn fnHasRuntimeBits(sema: *Sema, ty: Type) CompileError!bool {
37054 return ty.fnHasRuntimeBitsAdvanced(sema.mod, .sema);
37406 return ty.fnHasRuntimeBitsAdvanced(sema.pt, .sema);
3705537407}
3705637408
3705737409fn unionFieldIndex(
......@@ -37061,9 +37413,10 @@ fn unionFieldIndex(
3706137413 field_name: InternPool.NullTerminatedString,
3706237414 field_src: LazySrcLoc,
3706337415) !u32 {
37064 const mod = sema.mod;
37416 const pt = sema.pt;
37417 const mod = pt.zcu;
3706537418 const ip = &mod.intern_pool;
37066 try union_ty.resolveFields(mod);
37419 try union_ty.resolveFields(pt);
3706737420 const union_obj = mod.typeToUnion(union_ty).?;
3706837421 const field_index = union_obj.loadTagType(ip).nameIndex(ip, field_name) orelse
3706937422 return sema.failWithBadUnionFieldAccess(block, union_ty, union_obj, field_src, field_name);
......@@ -37077,9 +37430,10 @@ fn structFieldIndex(
3707737430 field_name: InternPool.NullTerminatedString,
3707837431 field_src: LazySrcLoc,
3707937432) !u32 {
37080 const mod = sema.mod;
37433 const pt = sema.pt;
37434 const mod = pt.zcu;
3708137435 const ip = &mod.intern_pool;
37082 try struct_ty.resolveFields(mod);
37436 try struct_ty.resolveFields(pt);
3708337437 if (struct_ty.isAnonStruct(mod)) {
3708437438 return sema.anonStructFieldIndex(block, struct_ty, field_name, field_src);
3708537439 } else {
......@@ -37096,7 +37450,8 @@ fn anonStructFieldIndex(
3709637450 field_name: InternPool.NullTerminatedString,
3709737451 field_src: LazySrcLoc,
3709837452) !u32 {
37099 const mod = sema.mod;
37453 const pt = sema.pt;
37454 const mod = pt.zcu;
3710037455 const ip = &mod.intern_pool;
3710137456 switch (ip.indexToKey(struct_ty.toIntern())) {
3710237457 .anon_struct_type => |anon_struct_type| for (anon_struct_type.names.get(ip), 0..) |name, i| {
......@@ -37106,20 +37461,21 @@ fn anonStructFieldIndex(
3710637461 else => unreachable,
3710737462 }
3710837463 return sema.fail(block, field_src, "no field named '{}' in anonymous struct '{}'", .{
37109 field_name.fmt(ip), struct_ty.fmt(sema.mod),
37464 field_name.fmt(ip), struct_ty.fmt(pt),
3711037465 });
3711137466}
3711237467
3711337468/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
3711437469/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
3711537470fn intAdd(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize) !Value {
37471 const pt = sema.pt;
3711637472 var overflow: usize = undefined;
3711737473 return sema.intAddInner(lhs, rhs, ty, &overflow) catch |err| switch (err) {
3711837474 error.Overflow => {
37119 const is_vec = ty.isVector(sema.mod);
37475 const is_vec = ty.isVector(pt.zcu);
3712037476 overflow_idx.* = if (is_vec) overflow else 0;
37121 const safe_ty = if (is_vec) try sema.mod.vectorType(.{
37122 .len = ty.vectorLen(sema.mod),
37477 const safe_ty = if (is_vec) try pt.vectorType(.{
37478 .len = ty.vectorLen(pt.zcu),
3712337479 .child = .comptime_int_type,
3712437480 }) else Type.comptime_int;
3712537481 return sema.intAddInner(lhs, rhs, safe_ty, undefined) catch |err1| switch (err1) {
......@@ -37132,13 +37488,14 @@ fn intAdd(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize)
3713237488}
3713337489
3713437490fn intAddInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize) !Value {
37135 const mod = sema.mod;
37491 const pt = sema.pt;
37492 const mod = pt.zcu;
3713637493 if (ty.zigTypeTag(mod) == .Vector) {
3713737494 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
3713837495 const scalar_ty = ty.scalarType(mod);
3713937496 for (result_data, 0..) |*scalar, i| {
37140 const lhs_elem = try lhs.elemValue(mod, i);
37141 const rhs_elem = try rhs.elemValue(mod, i);
37497 const lhs_elem = try lhs.elemValue(pt, i);
37498 const rhs_elem = try rhs.elemValue(pt, i);
3714237499 const val = sema.intAddScalar(lhs_elem, rhs_elem, scalar_ty) catch |err| switch (err) {
3714337500 error.Overflow => {
3714437501 overflow_idx.* = i;
......@@ -37148,34 +37505,34 @@ fn intAddInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usi
3714837505 };
3714937506 scalar.* = val.toIntern();
3715037507 }
37151 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37508 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3715237509 .ty = ty.toIntern(),
3715337510 .storage = .{ .elems = result_data },
37154 } })));
37511 } }));
3715537512 }
3715637513 return sema.intAddScalar(lhs, rhs, ty);
3715737514}
3715837515
3715937516fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
37160 const mod = sema.mod;
37517 const pt = sema.pt;
3716137518 if (scalar_ty.toIntern() != .comptime_int_type) {
3716237519 const res = try sema.intAddWithOverflowScalar(lhs, rhs, scalar_ty);
37163 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
37520 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
3716437521 return res.wrapped_result;
3716537522 }
3716637523 // TODO is this a performance issue? maybe we should try the operation without
3716737524 // resorting to BigInt first.
3716837525 var lhs_space: Value.BigIntSpace = undefined;
3716937526 var rhs_space: Value.BigIntSpace = undefined;
37170 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37171 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37527 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37528 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3717237529 const limbs = try sema.arena.alloc(
3717337530 std.math.big.Limb,
3717437531 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
3717537532 );
3717637533 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3717737534 result_bigint.add(lhs_bigint, rhs_bigint);
37178 return mod.intValue_big(scalar_ty, result_bigint.toConst());
37535 return pt.intValue_big(scalar_ty, result_bigint.toConst());
3717937536}
3718037537
3718137538/// Supports both floats and ints; handles undefined.
......@@ -37185,15 +37542,16 @@ fn numberAddWrapScalar(
3718537542 rhs: Value,
3718637543 ty: Type,
3718737544) !Value {
37188 const mod = sema.mod;
37189 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return mod.undefValue(ty);
37545 const pt = sema.pt;
37546 const mod = pt.zcu;
37547 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return pt.undefValue(ty);
3719037548
3719137549 if (ty.zigTypeTag(mod) == .ComptimeInt) {
3719237550 return sema.intAdd(lhs, rhs, ty, undefined);
3719337551 }
3719437552
3719537553 if (ty.isAnyFloat()) {
37196 return Value.floatAdd(lhs, rhs, ty, sema.arena, mod);
37554 return Value.floatAdd(lhs, rhs, ty, sema.arena, pt);
3719737555 }
3719837556
3719937557 const overflow_result = try sema.intAddWithOverflow(lhs, rhs, ty);
......@@ -37203,13 +37561,14 @@ fn numberAddWrapScalar(
3720337561/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
3720437562/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
3720537563fn intSub(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize) !Value {
37564 const pt = sema.pt;
3720637565 var overflow: usize = undefined;
3720737566 return sema.intSubInner(lhs, rhs, ty, &overflow) catch |err| switch (err) {
3720837567 error.Overflow => {
37209 const is_vec = ty.isVector(sema.mod);
37568 const is_vec = ty.isVector(pt.zcu);
3721037569 overflow_idx.* = if (is_vec) overflow else 0;
37211 const safe_ty = if (is_vec) try sema.mod.vectorType(.{
37212 .len = ty.vectorLen(sema.mod),
37570 const safe_ty = if (is_vec) try pt.vectorType(.{
37571 .len = ty.vectorLen(pt.zcu),
3721337572 .child = .comptime_int_type,
3721437573 }) else Type.comptime_int;
3721537574 return sema.intSubInner(lhs, rhs, safe_ty, undefined) catch |err1| switch (err1) {
......@@ -37222,13 +37581,13 @@ fn intSub(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize)
3722237581}
3722337582
3722437583fn intSubInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize) !Value {
37225 const mod = sema.mod;
37226 if (ty.zigTypeTag(mod) == .Vector) {
37227 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
37228 const scalar_ty = ty.scalarType(mod);
37584 const pt = sema.pt;
37585 if (ty.zigTypeTag(pt.zcu) == .Vector) {
37586 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
37587 const scalar_ty = ty.scalarType(pt.zcu);
3722937588 for (result_data, 0..) |*scalar, i| {
37230 const lhs_elem = try lhs.elemValue(sema.mod, i);
37231 const rhs_elem = try rhs.elemValue(sema.mod, i);
37589 const lhs_elem = try lhs.elemValue(pt, i);
37590 const rhs_elem = try rhs.elemValue(pt, i);
3723237591 const val = sema.intSubScalar(lhs_elem, rhs_elem, scalar_ty) catch |err| switch (err) {
3723337592 error.Overflow => {
3723437593 overflow_idx.* = i;
......@@ -37238,34 +37597,34 @@ fn intSubInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usi
3723837597 };
3723937598 scalar.* = val.toIntern();
3724037599 }
37241 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37600 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3724237601 .ty = ty.toIntern(),
3724337602 .storage = .{ .elems = result_data },
37244 } })));
37603 } }));
3724537604 }
3724637605 return sema.intSubScalar(lhs, rhs, ty);
3724737606}
3724837607
3724937608fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
37250 const mod = sema.mod;
37609 const pt = sema.pt;
3725137610 if (scalar_ty.toIntern() != .comptime_int_type) {
3725237611 const res = try sema.intSubWithOverflowScalar(lhs, rhs, scalar_ty);
37253 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
37612 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
3725437613 return res.wrapped_result;
3725537614 }
3725637615 // TODO is this a performance issue? maybe we should try the operation without
3725737616 // resorting to BigInt first.
3725837617 var lhs_space: Value.BigIntSpace = undefined;
3725937618 var rhs_space: Value.BigIntSpace = undefined;
37260 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37261 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37619 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37620 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3726237621 const limbs = try sema.arena.alloc(
3726337622 std.math.big.Limb,
3726437623 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
3726537624 );
3726637625 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3726737626 result_bigint.sub(lhs_bigint, rhs_bigint);
37268 return mod.intValue_big(scalar_ty, result_bigint.toConst());
37627 return pt.intValue_big(scalar_ty, result_bigint.toConst());
3726937628}
3727037629
3727137630/// Supports both floats and ints; handles undefined.
......@@ -37275,15 +37634,16 @@ fn numberSubWrapScalar(
3727537634 rhs: Value,
3727637635 ty: Type,
3727737636) !Value {
37278 const mod = sema.mod;
37279 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return mod.undefValue(ty);
37637 const pt = sema.pt;
37638 const mod = pt.zcu;
37639 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return pt.undefValue(ty);
3728037640
3728137641 if (ty.zigTypeTag(mod) == .ComptimeInt) {
3728237642 return sema.intSub(lhs, rhs, ty, undefined);
3728337643 }
3728437644
3728537645 if (ty.isAnyFloat()) {
37286 return Value.floatSub(lhs, rhs, ty, sema.arena, mod);
37646 return Value.floatSub(lhs, rhs, ty, sema.arena, pt);
3728737647 }
3728837648
3728937649 const overflow_result = try sema.intSubWithOverflow(lhs, rhs, ty);
......@@ -37296,28 +37656,29 @@ fn intSubWithOverflow(
3729637656 rhs: Value,
3729737657 ty: Type,
3729837658) !Value.OverflowArithmeticResult {
37299 const mod = sema.mod;
37659 const pt = sema.pt;
37660 const mod = pt.zcu;
3730037661 if (ty.zigTypeTag(mod) == .Vector) {
3730137662 const vec_len = ty.vectorLen(mod);
3730237663 const overflowed_data = try sema.arena.alloc(InternPool.Index, vec_len);
3730337664 const result_data = try sema.arena.alloc(InternPool.Index, vec_len);
3730437665 const scalar_ty = ty.scalarType(mod);
3730537666 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
37306 const lhs_elem = try lhs.elemValue(sema.mod, i);
37307 const rhs_elem = try rhs.elemValue(sema.mod, i);
37667 const lhs_elem = try lhs.elemValue(pt, i);
37668 const rhs_elem = try rhs.elemValue(pt, i);
3730837669 const of_math_result = try sema.intSubWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty);
3730937670 of.* = of_math_result.overflow_bit.toIntern();
3731037671 scalar.* = of_math_result.wrapped_result.toIntern();
3731137672 }
3731237673 return Value.OverflowArithmeticResult{
37313 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37314 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
37674 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
37675 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
3731537676 .storage = .{ .elems = overflowed_data },
37316 } }))),
37317 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37677 } })),
37678 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
3731837679 .ty = ty.toIntern(),
3731937680 .storage = .{ .elems = result_data },
37320 } }))),
37681 } })),
3732137682 };
3732237683 }
3732337684 return sema.intSubWithOverflowScalar(lhs, rhs, ty);
......@@ -37329,29 +37690,30 @@ fn intSubWithOverflowScalar(
3732937690 rhs: Value,
3733037691 ty: Type,
3733137692) !Value.OverflowArithmeticResult {
37332 const mod = sema.mod;
37693 const pt = sema.pt;
37694 const mod = pt.zcu;
3733337695 const info = ty.intInfo(mod);
3733437696
3733537697 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
3733637698 return .{
37337 .overflow_bit = try mod.undefValue(Type.u1),
37338 .wrapped_result = try mod.undefValue(ty),
37699 .overflow_bit = try pt.undefValue(Type.u1),
37700 .wrapped_result = try pt.undefValue(ty),
3733937701 };
3734037702 }
3734137703
3734237704 var lhs_space: Value.BigIntSpace = undefined;
3734337705 var rhs_space: Value.BigIntSpace = undefined;
37344 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37345 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37706 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37707 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3734637708 const limbs = try sema.arena.alloc(
3734737709 std.math.big.Limb,
3734837710 std.math.big.int.calcTwosCompLimbCount(info.bits),
3734937711 );
3735037712 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3735137713 const overflowed = result_bigint.subWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
37352 const wrapped_result = try mod.intValue_big(ty, result_bigint.toConst());
37714 const wrapped_result = try pt.intValue_big(ty, result_bigint.toConst());
3735337715 return Value.OverflowArithmeticResult{
37354 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
37716 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
3735537717 .wrapped_result = wrapped_result,
3735637718 };
3735737719}
......@@ -37367,17 +37729,18 @@ fn intFromFloat(
3736737729 int_ty: Type,
3736837730 mode: IntFromFloatMode,
3736937731) CompileError!Value {
37370 const mod = sema.mod;
37732 const pt = sema.pt;
37733 const mod = pt.zcu;
3737137734 if (float_ty.zigTypeTag(mod) == .Vector) {
3737237735 const result_data = try sema.arena.alloc(InternPool.Index, float_ty.vectorLen(mod));
3737337736 for (result_data, 0..) |*scalar, i| {
37374 const elem_val = try val.elemValue(sema.mod, i);
37737 const elem_val = try val.elemValue(pt, i);
3737537738 scalar.* = (try sema.intFromFloatScalar(block, src, elem_val, int_ty.scalarType(mod), mode)).toIntern();
3737637739 }
37377 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37740 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3737837741 .ty = int_ty.toIntern(),
3737937742 .storage = .{ .elems = result_data },
37380 } })));
37743 } }));
3738137744 }
3738237745 return sema.intFromFloatScalar(block, src, val, int_ty, mode);
3738337746}
......@@ -37415,7 +37778,8 @@ fn intFromFloatScalar(
3741537778 int_ty: Type,
3741637779 mode: IntFromFloatMode,
3741737780) CompileError!Value {
37418 const mod = sema.mod;
37781 const pt = sema.pt;
37782 const mod = pt.zcu;
3741937783
3742037784 if (val.isUndef(mod)) return sema.failWithUseOfUndef(block, src);
3742137785
......@@ -37423,32 +37787,32 @@ fn intFromFloatScalar(
3742337787 block,
3742437788 src,
3742537789 "fractional component prevents float value '{}' from coercion to type '{}'",
37426 .{ val.fmtValue(mod, sema), int_ty.fmt(mod) },
37790 .{ val.fmtValue(pt, sema), int_ty.fmt(pt) },
3742737791 );
3742837792
37429 const float = val.toFloat(f128, mod);
37793 const float = val.toFloat(f128, pt);
3743037794 if (std.math.isNan(float)) {
3743137795 return sema.fail(block, src, "float value NaN cannot be stored in integer type '{}'", .{
37432 int_ty.fmt(sema.mod),
37796 int_ty.fmt(pt),
3743337797 });
3743437798 }
3743537799 if (std.math.isInf(float)) {
3743637800 return sema.fail(block, src, "float value Inf cannot be stored in integer type '{}'", .{
37437 int_ty.fmt(sema.mod),
37801 int_ty.fmt(pt),
3743837802 });
3743937803 }
3744037804
3744137805 var big_int = try float128IntPartToBigInt(sema.arena, float);
3744237806 defer big_int.deinit();
3744337807
37444 const cti_result = try mod.intValue_big(Type.comptime_int, big_int.toConst());
37808 const cti_result = try pt.intValue_big(Type.comptime_int, big_int.toConst());
3744537809
3744637810 if (!(try sema.intFitsInType(cti_result, int_ty, null))) {
3744737811 return sema.fail(block, src, "float value '{}' cannot be stored in integer type '{}'", .{
37448 val.fmtValue(sema.mod, sema), int_ty.fmt(sema.mod),
37812 val.fmtValue(pt, sema), int_ty.fmt(pt),
3744937813 });
3745037814 }
37451 return mod.getCoerced(cti_result, int_ty);
37815 return pt.getCoerced(cti_result, int_ty);
3745237816}
3745337817
3745437818/// Asserts the value is an integer, and the destination type is ComptimeInt or Int.
......@@ -37461,7 +37825,8 @@ fn intFitsInType(
3746137825 ty: Type,
3746237826 vector_index: ?*usize,
3746337827) CompileError!bool {
37464 const mod = sema.mod;
37828 const pt = sema.pt;
37829 const mod = pt.zcu;
3746537830 if (ty.toIntern() == .comptime_int_type) return true;
3746637831 const info = ty.intInfo(mod);
3746737832 switch (val.toIntern()) {
......@@ -37528,22 +37893,23 @@ fn intFitsInType(
3752837893}
3752937894
3753037895fn intInRange(sema: *Sema, tag_ty: Type, int_val: Value, end: usize) !bool {
37531 const mod = sema.mod;
37532 if (!(try int_val.compareAllWithZeroSema(.gte, mod))) return false;
37533 const end_val = try mod.intValue(tag_ty, end);
37896 const pt = sema.pt;
37897 if (!(try int_val.compareAllWithZeroSema(.gte, pt))) return false;
37898 const end_val = try pt.intValue(tag_ty, end);
3753437899 if (!(try sema.compareAll(int_val, .lt, end_val, tag_ty))) return false;
3753537900 return true;
3753637901}
3753737902
3753837903/// Asserts the type is an enum.
3753937904fn enumHasInt(sema: *Sema, ty: Type, int: Value) CompileError!bool {
37540 const mod = sema.mod;
37905 const pt = sema.pt;
37906 const mod = pt.zcu;
3754137907 const enum_type = mod.intern_pool.loadEnumType(ty.toIntern());
3754237908 assert(enum_type.tag_mode != .nonexhaustive);
3754337909 // The `tagValueIndex` function call below relies on the type being the integer tag type.
3754437910 // `getCoerced` assumes the value will fit the new type.
3754537911 if (!(try sema.intFitsInType(int, Type.fromInterned(enum_type.tag_ty), null))) return false;
37546 const int_coerced = try mod.getCoerced(int, Type.fromInterned(enum_type.tag_ty));
37912 const int_coerced = try pt.getCoerced(int, Type.fromInterned(enum_type.tag_ty));
3754737913
3754837914 return enum_type.tagValueIndex(&mod.intern_pool, int_coerced.toIntern()) != null;
3754937915}
......@@ -37554,28 +37920,29 @@ fn intAddWithOverflow(
3755437920 rhs: Value,
3755537921 ty: Type,
3755637922) !Value.OverflowArithmeticResult {
37557 const mod = sema.mod;
37923 const pt = sema.pt;
37924 const mod = pt.zcu;
3755837925 if (ty.zigTypeTag(mod) == .Vector) {
3755937926 const vec_len = ty.vectorLen(mod);
3756037927 const overflowed_data = try sema.arena.alloc(InternPool.Index, vec_len);
3756137928 const result_data = try sema.arena.alloc(InternPool.Index, vec_len);
3756237929 const scalar_ty = ty.scalarType(mod);
3756337930 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
37564 const lhs_elem = try lhs.elemValue(sema.mod, i);
37565 const rhs_elem = try rhs.elemValue(sema.mod, i);
37931 const lhs_elem = try lhs.elemValue(pt, i);
37932 const rhs_elem = try rhs.elemValue(pt, i);
3756637933 const of_math_result = try sema.intAddWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty);
3756737934 of.* = of_math_result.overflow_bit.toIntern();
3756837935 scalar.* = of_math_result.wrapped_result.toIntern();
3756937936 }
3757037937 return Value.OverflowArithmeticResult{
37571 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37572 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
37938 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
37939 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
3757337940 .storage = .{ .elems = overflowed_data },
37574 } }))),
37575 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37941 } })),
37942 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
3757637943 .ty = ty.toIntern(),
3757737944 .storage = .{ .elems = result_data },
37578 } }))),
37945 } })),
3757937946 };
3758037947 }
3758137948 return sema.intAddWithOverflowScalar(lhs, rhs, ty);
......@@ -37587,29 +37954,30 @@ fn intAddWithOverflowScalar(
3758737954 rhs: Value,
3758837955 ty: Type,
3758937956) !Value.OverflowArithmeticResult {
37590 const mod = sema.mod;
37957 const pt = sema.pt;
37958 const mod = pt.zcu;
3759137959 const info = ty.intInfo(mod);
3759237960
3759337961 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
3759437962 return .{
37595 .overflow_bit = try mod.undefValue(Type.u1),
37596 .wrapped_result = try mod.undefValue(ty),
37963 .overflow_bit = try pt.undefValue(Type.u1),
37964 .wrapped_result = try pt.undefValue(ty),
3759737965 };
3759837966 }
3759937967
3760037968 var lhs_space: Value.BigIntSpace = undefined;
3760137969 var rhs_space: Value.BigIntSpace = undefined;
37602 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37603 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37970 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37971 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3760437972 const limbs = try sema.arena.alloc(
3760537973 std.math.big.Limb,
3760637974 std.math.big.int.calcTwosCompLimbCount(info.bits),
3760737975 );
3760837976 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3760937977 const overflowed = result_bigint.addWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
37610 const result = try mod.intValue_big(ty, result_bigint.toConst());
37978 const result = try pt.intValue_big(ty, result_bigint.toConst());
3761137979 return Value.OverflowArithmeticResult{
37612 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
37980 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
3761337981 .wrapped_result = result,
3761437982 };
3761537983}
......@@ -37625,12 +37993,13 @@ fn compareAll(
3762537993 rhs: Value,
3762637994 ty: Type,
3762737995) CompileError!bool {
37628 const mod = sema.mod;
37996 const pt = sema.pt;
37997 const mod = pt.zcu;
3762937998 if (ty.zigTypeTag(mod) == .Vector) {
3763037999 var i: usize = 0;
3763138000 while (i < ty.vectorLen(mod)) : (i += 1) {
37632 const lhs_elem = try lhs.elemValue(sema.mod, i);
37633 const rhs_elem = try rhs.elemValue(sema.mod, i);
38001 const lhs_elem = try lhs.elemValue(pt, i);
38002 const rhs_elem = try rhs.elemValue(pt, i);
3763438003 if (!(try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType(mod)))) {
3763538004 return false;
3763638005 }
......@@ -37648,13 +38017,13 @@ fn compareScalar(
3764838017 rhs: Value,
3764938018 ty: Type,
3765038019) CompileError!bool {
37651 const mod = sema.mod;
37652 const coerced_lhs = try mod.getCoerced(lhs, ty);
37653 const coerced_rhs = try mod.getCoerced(rhs, ty);
38020 const pt = sema.pt;
38021 const coerced_lhs = try pt.getCoerced(lhs, ty);
38022 const coerced_rhs = try pt.getCoerced(rhs, ty);
3765438023 switch (op) {
3765538024 .eq => return sema.valuesEqual(coerced_lhs, coerced_rhs, ty),
3765638025 .neq => return !(try sema.valuesEqual(coerced_lhs, coerced_rhs, ty)),
37657 else => return Value.compareHeteroAdvanced(coerced_lhs, op, coerced_rhs, mod, .sema),
38026 else => return Value.compareHeteroAdvanced(coerced_lhs, op, coerced_rhs, pt, .sema),
3765838027 }
3765938028}
3766038029
......@@ -37664,7 +38033,7 @@ fn valuesEqual(
3766438033 rhs: Value,
3766538034 ty: Type,
3766638035) CompileError!bool {
37667 return lhs.eql(rhs, ty, sema.mod);
38036 return lhs.eql(rhs, ty, sema.pt.zcu);
3766838037}
3766938038
3767038039/// Asserts the values are comparable vectors of type `ty`.
......@@ -37675,29 +38044,30 @@ fn compareVector(
3767538044 rhs: Value,
3767638045 ty: Type,
3767738046) !Value {
37678 const mod = sema.mod;
38047 const pt = sema.pt;
38048 const mod = pt.zcu;
3767938049 assert(ty.zigTypeTag(mod) == .Vector);
3768038050 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
3768138051 for (result_data, 0..) |*scalar, i| {
37682 const lhs_elem = try lhs.elemValue(sema.mod, i);
37683 const rhs_elem = try rhs.elemValue(sema.mod, i);
38052 const lhs_elem = try lhs.elemValue(pt, i);
38053 const rhs_elem = try rhs.elemValue(pt, i);
3768438054 const res_bool = try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType(mod));
3768538055 scalar.* = Value.makeBool(res_bool).toIntern();
3768638056 }
37687 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37688 .ty = (try mod.vectorType(.{ .len = ty.vectorLen(mod), .child = .bool_type })).toIntern(),
38057 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
38058 .ty = (try pt.vectorType(.{ .len = ty.vectorLen(mod), .child = .bool_type })).toIntern(),
3768938059 .storage = .{ .elems = result_data },
37690 } })));
38060 } }));
3769138061}
3769238062
3769338063/// Merge lhs with rhs.
3769438064/// Asserts that lhs and rhs are both error sets and are resolved.
3769538065fn errorSetMerge(sema: *Sema, lhs: Type, rhs: Type) !Type {
37696 const mod = sema.mod;
37697 const ip = &mod.intern_pool;
38066 const pt = sema.pt;
38067 const ip = &pt.zcu.intern_pool;
3769838068 const arena = sema.arena;
37699 const lhs_names = lhs.errorSetNames(mod);
37700 const rhs_names = rhs.errorSetNames(mod);
38069 const lhs_names = lhs.errorSetNames(pt.zcu);
38070 const rhs_names = rhs.errorSetNames(pt.zcu);
3770138071 var names: InferredErrorSet.NameMap = .{};
3770238072 try names.ensureUnusedCapacity(arena, lhs_names.len);
3770338073
......@@ -37708,7 +38078,7 @@ fn errorSetMerge(sema: *Sema, lhs: Type, rhs: Type) !Type {
3770838078 try names.put(arena, rhs_names.get(ip)[rhs_index], {});
3770938079 }
3771038080
37711 return mod.errorSetFromUnsortedNames(names.keys());
38081 return pt.errorSetFromUnsortedNames(names.keys());
3771238082}
3771338083
3771438084/// Avoids crashing the compiler when asking if inferred allocations are noreturn.
......@@ -37718,7 +38088,7 @@ fn isNoReturn(sema: *Sema, ref: Air.Inst.Ref) bool {
3771838088 .inferred_alloc, .inferred_alloc_comptime => return false,
3771938089 else => {},
3772038090 };
37721 return sema.typeOf(ref).isNoReturn(sema.mod);
38091 return sema.typeOf(ref).isNoReturn(sema.pt.zcu);
3772238092}
3772338093
3772438094/// Avoids crashing the compiler when asking if inferred allocations are known to be a certain zig type.
......@@ -37727,11 +38097,12 @@ fn isKnownZigType(sema: *Sema, ref: Air.Inst.Ref, tag: std.builtin.TypeId) bool
3772738097 .inferred_alloc, .inferred_alloc_comptime => return false,
3772838098 else => {},
3772938099 };
37730 return sema.typeOf(ref).zigTypeTag(sema.mod) == tag;
38100 return sema.typeOf(ref).zigTypeTag(sema.pt.zcu) == tag;
3773138101}
3773238102
3773338103pub fn declareDependency(sema: *Sema, dependee: InternPool.Dependee) !void {
37734 if (!sema.mod.comp.debug_incremental) return;
38104 const zcu = sema.pt.zcu;
38105 if (!zcu.comp.debug_incremental) return;
3773538106
3773638107 // Avoid creating dependencies on ourselves. This situation can arise when we analyze the fields
3773738108 // of a type and they use `@This()`. This dependency would be unnecessary, and in fact would
......@@ -37747,11 +38118,11 @@ pub fn declareDependency(sema: *Sema, dependee: InternPool.Dependee) !void {
3774738118 else
3774838119 .{ .decl = sema.owner_decl_index },
3774938120 );
37750 try sema.mod.intern_pool.addDependency(sema.gpa, depender, dependee);
38121 try zcu.intern_pool.addDependency(sema.gpa, depender, dependee);
3775138122}
3775238123
3775338124fn isComptimeMutablePtr(sema: *Sema, val: Value) bool {
37754 return switch (sema.mod.intern_pool.indexToKey(val.toIntern())) {
38125 return switch (sema.pt.zcu.intern_pool.indexToKey(val.toIntern())) {
3775538126 .slice => |slice| sema.isComptimeMutablePtr(Value.fromInterned(slice.ptr)),
3775638127 .ptr => |ptr| switch (ptr.base_addr) {
3775738128 .anon_decl, .decl, .int => false,
......@@ -37766,7 +38137,7 @@ fn isComptimeMutablePtr(sema: *Sema, val: Value) bool {
3776638137
3776738138fn checkRuntimeValue(sema: *Sema, ptr: Air.Inst.Ref) bool {
3776838139 const val = ptr.toInterned() orelse return true;
37769 return !Value.fromInterned(val).canMutateComptimeVarState(sema.mod);
38140 return !Value.fromInterned(val).canMutateComptimeVarState(sema.pt.zcu);
3777038141}
3777138142
3777238143fn validateRuntimeValue(sema: *Sema, block: *Block, val_src: LazySrcLoc, val: Air.Inst.Ref) CompileError!void {
......@@ -37781,7 +38152,8 @@ fn validateRuntimeValue(sema: *Sema, block: *Block, val_src: LazySrcLoc, val: Ai
3778138152
3778238153/// Returns true if any value contained in `val` is undefined.
3778338154fn anyUndef(sema: *Sema, block: *Block, src: LazySrcLoc, val: Value) !bool {
37784 const mod = sema.mod;
38155 const pt = sema.pt;
38156 const mod = pt.zcu;
3778538157 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
3778638158 .undef => true,
3778738159 .simple_value => |v| v == .undefined,
......@@ -37807,13 +38179,14 @@ fn sliceToIpString(
3780738179 slice_val: Value,
3780838180 reason: NeededComptimeReason,
3780938181) CompileError!InternPool.NullTerminatedString {
37810 const zcu = sema.mod;
38182 const pt = sema.pt;
38183 const zcu = pt.zcu;
3781138184 const slice_ty = slice_val.typeOf(zcu);
3781238185 assert(slice_ty.isSlice(zcu));
3781338186 assert(slice_ty.childType(zcu).toIntern() == .u8_type);
3781438187 const array_val = try sema.derefSliceAsArray(block, src, slice_val, reason);
3781538188 const array_ty = array_val.typeOf(zcu);
37816 return array_val.toIpString(array_ty, zcu);
38189 return array_val.toIpString(array_ty, pt);
3781738190}
3781838191
3781938192/// Given a slice value, attempts to dereference it into a comptime-known array.
......@@ -37840,7 +38213,8 @@ fn maybeDerefSliceAsArray(
3784038213 src: LazySrcLoc,
3784138214 slice_val: Value,
3784238215) CompileError!?Value {
37843 const zcu = sema.mod;
38216 const pt = sema.pt;
38217 const zcu = pt.zcu;
3784438218 const ip = &zcu.intern_pool;
3784538219 assert(slice_val.typeOf(zcu).isSlice(zcu));
3784638220 const slice = switch (ip.indexToKey(slice_val.toIntern())) {
......@@ -37849,19 +38223,19 @@ fn maybeDerefSliceAsArray(
3784938223 else => unreachable,
3785038224 };
3785138225 const elem_ty = Type.fromInterned(slice.ty).childType(zcu);
37852 const len = try Value.fromInterned(slice.len).toUnsignedIntSema(zcu);
37853 const array_ty = try zcu.arrayType(.{
38226 const len = try Value.fromInterned(slice.len).toUnsignedIntSema(pt);
38227 const array_ty = try pt.arrayType(.{
3785438228 .child = elem_ty.toIntern(),
3785538229 .len = len,
3785638230 });
37857 const ptr_ty = try zcu.ptrTypeSema(p: {
38231 const ptr_ty = try pt.ptrTypeSema(p: {
3785838232 var p = Type.fromInterned(slice.ty).ptrInfo(zcu);
3785938233 p.flags.size = .One;
3786038234 p.child = array_ty.toIntern();
3786138235 p.sentinel = .none;
3786238236 break :p p;
3786338237 });
37864 const casted_ptr = try zcu.getCoerced(Value.fromInterned(slice.ptr), ptr_ty);
38238 const casted_ptr = try pt.getCoerced(Value.fromInterned(slice.ptr), ptr_ty);
3786538239 return sema.pointerDeref(block, src, casted_ptr, ptr_ty);
3786638240}
3786738241
......@@ -37879,7 +38253,7 @@ fn analyzeUnreachable(sema: *Sema, block: *Block, src: LazySrcLoc, safety_check:
3787938253pub fn flushExports(sema: *Sema) !void {
3788038254 if (sema.exports.items.len == 0) return;
3788138255
37882 const zcu = sema.mod;
38256 const zcu = sema.pt.zcu;
3788338257 const gpa = zcu.gpa;
3788438258
3788538259 const unit = sema.ownerUnit();
src/Sema/bitcast.zig+96-92
......@@ -69,7 +69,8 @@ fn bitCastInner(
6969 host_bits: u64,
7070 bit_offset: u64,
7171) BitCastError!Value {
72 const zcu = sema.mod;
72 const pt = sema.pt;
73 const zcu = pt.zcu;
7374 const endian = zcu.getTarget().cpu.arch.endian();
7475
7576 if (dest_ty.toIntern() == val.typeOf(zcu).toIntern() and bit_offset == 0) {
......@@ -78,29 +79,29 @@ fn bitCastInner(
7879
7980 const val_ty = val.typeOf(zcu);
8081
81 try val_ty.resolveLayout(zcu);
82 try dest_ty.resolveLayout(zcu);
82 try val_ty.resolveLayout(pt);
83 try dest_ty.resolveLayout(pt);
8384
8485 assert(val_ty.hasWellDefinedLayout(zcu));
8586
8687 const abi_pad_bits, const host_pad_bits = if (host_bits > 0)
87 .{ val_ty.abiSize(zcu) * 8 - host_bits, host_bits - val_ty.bitSize(zcu) }
88 .{ val_ty.abiSize(pt) * 8 - host_bits, host_bits - val_ty.bitSize(pt) }
8889 else
89 .{ val_ty.abiSize(zcu) * 8 - val_ty.bitSize(zcu), 0 };
90 .{ val_ty.abiSize(pt) * 8 - val_ty.bitSize(pt), 0 };
9091
9192 const skip_bits = switch (endian) {
9293 .little => bit_offset + byte_offset * 8,
9394 .big => if (host_bits > 0)
94 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - host_bits + bit_offset
95 val_ty.abiSize(pt) * 8 - byte_offset * 8 - host_bits + bit_offset
9596 else
96 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - dest_ty.bitSize(zcu),
97 val_ty.abiSize(pt) * 8 - byte_offset * 8 - dest_ty.bitSize(pt),
9798 };
9899
99100 var unpack: UnpackValueBits = .{
100 .zcu = zcu,
101 .pt = sema.pt,
101102 .arena = sema.arena,
102103 .skip_bits = skip_bits,
103 .remaining_bits = dest_ty.bitSize(zcu),
104 .remaining_bits = dest_ty.bitSize(pt),
104105 .unpacked = std.ArrayList(InternPool.Index).init(sema.arena),
105106 };
106107 switch (endian) {
......@@ -116,7 +117,7 @@ fn bitCastInner(
116117 try unpack.padding(host_pad_bits);
117118
118119 var pack: PackValueBits = .{
119 .zcu = zcu,
120 .pt = sema.pt,
120121 .arena = sema.arena,
121122 .unpacked = unpack.unpacked.items,
122123 };
......@@ -131,33 +132,34 @@ fn bitCastSpliceInner(
131132 host_bits: u64,
132133 bit_offset: u64,
133134) BitCastError!Value {
134 const zcu = sema.mod;
135 const pt = sema.pt;
136 const zcu = pt.zcu;
135137 const endian = zcu.getTarget().cpu.arch.endian();
136138 const val_ty = val.typeOf(zcu);
137139 const splice_val_ty = splice_val.typeOf(zcu);
138140
139 try val_ty.resolveLayout(zcu);
140 try splice_val_ty.resolveLayout(zcu);
141 try val_ty.resolveLayout(pt);
142 try splice_val_ty.resolveLayout(pt);
141143
142 const splice_bits = splice_val_ty.bitSize(zcu);
144 const splice_bits = splice_val_ty.bitSize(pt);
143145
144146 const splice_offset = switch (endian) {
145147 .little => bit_offset + byte_offset * 8,
146148 .big => if (host_bits > 0)
147 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - host_bits + bit_offset
149 val_ty.abiSize(pt) * 8 - byte_offset * 8 - host_bits + bit_offset
148150 else
149 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - splice_bits,
151 val_ty.abiSize(pt) * 8 - byte_offset * 8 - splice_bits,
150152 };
151153
152 assert(splice_offset + splice_bits <= val_ty.abiSize(zcu) * 8);
154 assert(splice_offset + splice_bits <= val_ty.abiSize(pt) * 8);
153155
154156 const abi_pad_bits, const host_pad_bits = if (host_bits > 0)
155 .{ val_ty.abiSize(zcu) * 8 - host_bits, host_bits - val_ty.bitSize(zcu) }
157 .{ val_ty.abiSize(pt) * 8 - host_bits, host_bits - val_ty.bitSize(pt) }
156158 else
157 .{ val_ty.abiSize(zcu) * 8 - val_ty.bitSize(zcu), 0 };
159 .{ val_ty.abiSize(pt) * 8 - val_ty.bitSize(pt), 0 };
158160
159161 var unpack: UnpackValueBits = .{
160 .zcu = zcu,
162 .pt = pt,
161163 .arena = sema.arena,
162164 .skip_bits = 0,
163165 .remaining_bits = splice_offset,
......@@ -179,7 +181,7 @@ fn bitCastSpliceInner(
179181 try unpack.add(splice_val);
180182
181183 unpack.skip_bits = splice_offset + splice_bits;
182 unpack.remaining_bits = val_ty.abiSize(zcu) * 8 - splice_offset - splice_bits;
184 unpack.remaining_bits = val_ty.abiSize(pt) * 8 - splice_offset - splice_bits;
183185 switch (endian) {
184186 .little => {
185187 try unpack.add(val);
......@@ -193,7 +195,7 @@ fn bitCastSpliceInner(
193195 try unpack.padding(host_pad_bits);
194196
195197 var pack: PackValueBits = .{
196 .zcu = zcu,
198 .pt = pt,
197199 .arena = sema.arena,
198200 .unpacked = unpack.unpacked.items,
199201 };
......@@ -209,7 +211,7 @@ fn bitCastSpliceInner(
209211/// of values in *packed* memory - therefore, on big-endian targets, the first element of this
210212/// list contains bits from the *final* byte of the value.
211213const UnpackValueBits = struct {
212 zcu: *Zcu,
214 pt: Zcu.PerThread,
213215 arena: Allocator,
214216 skip_bits: u64,
215217 remaining_bits: u64,
......@@ -217,7 +219,8 @@ const UnpackValueBits = struct {
217219 unpacked: std.ArrayList(InternPool.Index),
218220
219221 fn add(unpack: *UnpackValueBits, val: Value) BitCastError!void {
220 const zcu = unpack.zcu;
222 const pt = unpack.pt;
223 const zcu = pt.zcu;
221224 const endian = zcu.getTarget().cpu.arch.endian();
222225 const ip = &zcu.intern_pool;
223226
......@@ -226,7 +229,7 @@ const UnpackValueBits = struct {
226229 }
227230
228231 const ty = val.typeOf(zcu);
229 const bit_size = ty.bitSize(zcu);
232 const bit_size = ty.bitSize(pt);
230233
231234 if (unpack.skip_bits >= bit_size) {
232235 unpack.skip_bits -= bit_size;
......@@ -279,7 +282,7 @@ const UnpackValueBits = struct {
279282 .little => i,
280283 .big => len - i - 1,
281284 };
282 const elem_val = try val.elemValue(zcu, real_idx);
285 const elem_val = try val.elemValue(pt, real_idx);
283286 try unpack.add(elem_val);
284287 }
285288 },
......@@ -288,7 +291,7 @@ const UnpackValueBits = struct {
288291 // The final element does not have trailing padding.
289292 // Elements are reversed in packed memory on BE targets.
290293 const elem_ty = ty.childType(zcu);
291 const pad_bits = elem_ty.abiSize(zcu) * 8 - elem_ty.bitSize(zcu);
294 const pad_bits = elem_ty.abiSize(pt) * 8 - elem_ty.bitSize(pt);
292295 const len = ty.arrayLen(zcu);
293296 const maybe_sent = ty.sentinel(zcu);
294297
......@@ -303,7 +306,7 @@ const UnpackValueBits = struct {
303306 .little => i,
304307 .big => len - i - 1,
305308 };
306 const elem_val = try val.elemValue(zcu, @intCast(real_idx));
309 const elem_val = try val.elemValue(pt, @intCast(real_idx));
307310 try unpack.add(elem_val);
308311 if (i != len - 1) try unpack.padding(pad_bits);
309312 }
......@@ -320,12 +323,12 @@ const UnpackValueBits = struct {
320323 var cur_bit_off: u64 = 0;
321324 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrder(ip);
322325 while (it.next()) |field_idx| {
323 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8;
326 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8;
324327 const pad_bits = want_bit_off - cur_bit_off;
325 const field_val = try val.fieldValue(zcu, field_idx);
328 const field_val = try val.fieldValue(pt, field_idx);
326329 try unpack.padding(pad_bits);
327330 try unpack.add(field_val);
328 cur_bit_off = want_bit_off + field_val.typeOf(zcu).bitSize(zcu);
331 cur_bit_off = want_bit_off + field_val.typeOf(zcu).bitSize(pt);
329332 }
330333 // Add trailing padding bits.
331334 try unpack.padding(bit_size - cur_bit_off);
......@@ -334,13 +337,13 @@ const UnpackValueBits = struct {
334337 var cur_bit_off: u64 = bit_size;
335338 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrderReverse(ip);
336339 while (it.next()) |field_idx| {
337 const field_val = try val.fieldValue(zcu, field_idx);
340 const field_val = try val.fieldValue(pt, field_idx);
338341 const field_ty = field_val.typeOf(zcu);
339 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8 + field_ty.bitSize(zcu);
342 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8 + field_ty.bitSize(pt);
340343 const pad_bits = cur_bit_off - want_bit_off;
341344 try unpack.padding(pad_bits);
342345 try unpack.add(field_val);
343 cur_bit_off = want_bit_off - field_ty.bitSize(zcu);
346 cur_bit_off = want_bit_off - field_ty.bitSize(pt);
344347 }
345348 assert(cur_bit_off == 0);
346349 },
......@@ -349,7 +352,7 @@ const UnpackValueBits = struct {
349352 // Just add all fields in order. There are no padding bits.
350353 // This is identical between LE and BE targets.
351354 for (0..ty.structFieldCount(zcu)) |i| {
352 const field_val = try val.fieldValue(zcu, i);
355 const field_val = try val.fieldValue(pt, i);
353356 try unpack.add(field_val);
354357 }
355358 },
......@@ -363,7 +366,7 @@ const UnpackValueBits = struct {
363366 // This correctly handles the case where `tag == .none`, since the payload is then
364367 // either an integer or a byte array, both of which we can unpack.
365368 const payload_val = Value.fromInterned(un.val);
366 const pad_bits = bit_size - payload_val.typeOf(zcu).bitSize(zcu);
369 const pad_bits = bit_size - payload_val.typeOf(zcu).bitSize(pt);
367370 if (endian == .little or ty.containerLayout(zcu) == .@"packed") {
368371 try unpack.add(payload_val);
369372 try unpack.padding(pad_bits);
......@@ -377,31 +380,31 @@ const UnpackValueBits = struct {
377380
378381 fn padding(unpack: *UnpackValueBits, pad_bits: u64) BitCastError!void {
379382 if (pad_bits == 0) return;
380 const zcu = unpack.zcu;
383 const pt = unpack.pt;
381384 // Figure out how many full bytes and leftover bits there are.
382385 const bytes = pad_bits / 8;
383386 const bits = pad_bits % 8;
384387 // Add undef u8 values for the bytes...
385 const undef_u8 = try zcu.undefValue(Type.u8);
388 const undef_u8 = try pt.undefValue(Type.u8);
386389 for (0..@intCast(bytes)) |_| {
387390 try unpack.primitive(undef_u8);
388391 }
389392 // ...and an undef int for the leftover bits.
390393 if (bits == 0) return;
391 const bits_ty = try zcu.intType(.unsigned, @intCast(bits));
392 const bits_val = try zcu.undefValue(bits_ty);
394 const bits_ty = try pt.intType(.unsigned, @intCast(bits));
395 const bits_val = try pt.undefValue(bits_ty);
393396 try unpack.primitive(bits_val);
394397 }
395398
396399 fn primitive(unpack: *UnpackValueBits, val: Value) BitCastError!void {
397 const zcu = unpack.zcu;
400 const pt = unpack.pt;
398401
399402 if (unpack.remaining_bits == 0) {
400403 return;
401404 }
402405
403 const ty = val.typeOf(zcu);
404 const bit_size = ty.bitSize(zcu);
406 const ty = val.typeOf(pt.zcu);
407 const bit_size = ty.bitSize(pt);
405408
406409 // Note that this skips all zero-bit types.
407410 if (unpack.skip_bits >= bit_size) {
......@@ -425,21 +428,21 @@ const UnpackValueBits = struct {
425428 }
426429
427430 fn splitPrimitive(unpack: *UnpackValueBits, val: Value, bit_offset: u64, bit_count: u64) BitCastError!void {
428 const zcu = unpack.zcu;
429 const ty = val.typeOf(zcu);
431 const pt = unpack.pt;
432 const ty = val.typeOf(pt.zcu);
430433
431 const val_bits = ty.bitSize(zcu);
434 const val_bits = ty.bitSize(pt);
432435 assert(bit_offset + bit_count <= val_bits);
433436
434 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
437 switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
435438 // In the `ptr` case, this will return `error.ReinterpretDeclRef`
436439 // if we're trying to split a non-integer pointer value.
437440 .int, .float, .enum_tag, .ptr, .opt => {
438441 // This @intCast is okay because no primitive can exceed the size of a u16.
439 const int_ty = try zcu.intType(.unsigned, @intCast(bit_count));
442 const int_ty = try unpack.pt.intType(.unsigned, @intCast(bit_count));
440443 const buf = try unpack.arena.alloc(u8, @intCast((val_bits + 7) / 8));
441 try val.writeToPackedMemory(ty, zcu, buf, 0);
442 const sub_val = try Value.readFromPackedMemory(int_ty, zcu, buf, @intCast(bit_offset), unpack.arena);
444 try val.writeToPackedMemory(ty, unpack.pt, buf, 0);
445 const sub_val = try Value.readFromPackedMemory(int_ty, unpack.pt, buf, @intCast(bit_offset), unpack.arena);
443446 try unpack.primitive(sub_val);
444447 },
445448 .undef => try unpack.padding(bit_count),
......@@ -456,13 +459,14 @@ const UnpackValueBits = struct {
456459/// reconstructs a value of an arbitrary type, with correct handling of `undefined`
457460/// values and of pointers which align in virtual memory.
458461const PackValueBits = struct {
459 zcu: *Zcu,
462 pt: Zcu.PerThread,
460463 arena: Allocator,
461464 bit_offset: u64 = 0,
462465 unpacked: []const InternPool.Index,
463466
464467 fn get(pack: *PackValueBits, ty: Type) BitCastError!Value {
465 const zcu = pack.zcu;
468 const pt = pack.pt;
469 const zcu = pt.zcu;
466470 const endian = zcu.getTarget().cpu.arch.endian();
467471 const ip = &zcu.intern_pool;
468472 const arena = pack.arena;
......@@ -485,7 +489,7 @@ const PackValueBits = struct {
485489 }
486490 },
487491 }
488 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
492 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
489493 .ty = ty.toIntern(),
490494 .storage = .{ .elems = elems },
491495 } }));
......@@ -495,12 +499,12 @@ const PackValueBits = struct {
495499 const len = ty.arrayLen(zcu);
496500 const elem_ty = ty.childType(zcu);
497501 const maybe_sent = ty.sentinel(zcu);
498 const pad_bits = elem_ty.abiSize(zcu) * 8 - elem_ty.bitSize(zcu);
502 const pad_bits = elem_ty.abiSize(pt) * 8 - elem_ty.bitSize(pt);
499503 const elems = try arena.alloc(InternPool.Index, @intCast(len));
500504
501505 if (endian == .big and maybe_sent != null) {
502506 // TODO: validate sentinel was preserved!
503 try pack.padding(elem_ty.bitSize(zcu));
507 try pack.padding(elem_ty.bitSize(pt));
504508 if (len != 0) try pack.padding(pad_bits);
505509 }
506510
......@@ -516,10 +520,10 @@ const PackValueBits = struct {
516520 if (endian == .little and maybe_sent != null) {
517521 // TODO: validate sentinel was preserved!
518522 if (len != 0) try pack.padding(pad_bits);
519 try pack.padding(elem_ty.bitSize(zcu));
523 try pack.padding(elem_ty.bitSize(pt));
520524 }
521525
522 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
526 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
523527 .ty = ty.toIntern(),
524528 .storage = .{ .elems = elems },
525529 } }));
......@@ -534,23 +538,23 @@ const PackValueBits = struct {
534538 var cur_bit_off: u64 = 0;
535539 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrder(ip);
536540 while (it.next()) |field_idx| {
537 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8;
541 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8;
538542 try pack.padding(want_bit_off - cur_bit_off);
539543 const field_ty = ty.structFieldType(field_idx, zcu);
540544 elems[field_idx] = (try pack.get(field_ty)).toIntern();
541 cur_bit_off = want_bit_off + field_ty.bitSize(zcu);
545 cur_bit_off = want_bit_off + field_ty.bitSize(pt);
542546 }
543 try pack.padding(ty.bitSize(zcu) - cur_bit_off);
547 try pack.padding(ty.bitSize(pt) - cur_bit_off);
544548 },
545549 .big => {
546 var cur_bit_off: u64 = ty.bitSize(zcu);
550 var cur_bit_off: u64 = ty.bitSize(pt);
547551 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrderReverse(ip);
548552 while (it.next()) |field_idx| {
549553 const field_ty = ty.structFieldType(field_idx, zcu);
550 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8 + field_ty.bitSize(zcu);
554 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8 + field_ty.bitSize(pt);
551555 try pack.padding(cur_bit_off - want_bit_off);
552556 elems[field_idx] = (try pack.get(field_ty)).toIntern();
553 cur_bit_off = want_bit_off - field_ty.bitSize(zcu);
557 cur_bit_off = want_bit_off - field_ty.bitSize(pt);
554558 }
555559 assert(cur_bit_off == 0);
556560 },
......@@ -559,10 +563,10 @@ const PackValueBits = struct {
559563 // Fill those values now.
560564 for (elems, 0..) |*elem, field_idx| {
561565 if (elem.* != .none) continue;
562 const val = (try ty.structFieldValueComptime(zcu, field_idx)).?;
566 const val = (try ty.structFieldValueComptime(pt, field_idx)).?;
563567 elem.* = val.toIntern();
564568 }
565 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
569 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
566570 .ty = ty.toIntern(),
567571 .storage = .{ .elems = elems },
568572 } }));
......@@ -575,7 +579,7 @@ const PackValueBits = struct {
575579 const field_ty = ty.structFieldType(i, zcu);
576580 elem.* = (try pack.get(field_ty)).toIntern();
577581 }
578 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
582 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
579583 .ty = ty.toIntern(),
580584 .storage = .{ .elems = elems },
581585 } }));
......@@ -591,7 +595,7 @@ const PackValueBits = struct {
591595 const prev_unpacked = pack.unpacked;
592596 const prev_bit_offset = pack.bit_offset;
593597
594 const backing_ty = try ty.unionBackingType(zcu);
598 const backing_ty = try ty.unionBackingType(pt);
595599
596600 backing: {
597601 const backing_val = pack.get(backing_ty) catch |err| switch (err) {
......@@ -607,7 +611,7 @@ const PackValueBits = struct {
607611 pack.bit_offset = prev_bit_offset;
608612 break :backing;
609613 }
610 return Value.fromInterned(try zcu.intern(.{ .un = .{
614 return Value.fromInterned(try pt.intern(.{ .un = .{
611615 .ty = ty.toIntern(),
612616 .tag = .none,
613617 .val = backing_val.toIntern(),
......@@ -618,16 +622,16 @@ const PackValueBits = struct {
618622 for (field_order, 0..) |*f, i| f.* = @intCast(i);
619623 // Sort `field_order` to put the fields with the largest bit sizes first.
620624 const SizeSortCtx = struct {
621 zcu: *Zcu,
625 pt: Zcu.PerThread,
622626 field_types: []const InternPool.Index,
623627 fn lessThan(ctx: @This(), a_idx: u32, b_idx: u32) bool {
624628 const a_ty = Type.fromInterned(ctx.field_types[a_idx]);
625629 const b_ty = Type.fromInterned(ctx.field_types[b_idx]);
626 return a_ty.bitSize(ctx.zcu) > b_ty.bitSize(ctx.zcu);
630 return a_ty.bitSize(ctx.pt) > b_ty.bitSize(ctx.pt);
627631 }
628632 };
629633 std.mem.sortUnstable(u32, field_order, SizeSortCtx{
630 .zcu = zcu,
634 .pt = pt,
631635 .field_types = zcu.typeToUnion(ty).?.field_types.get(ip),
632636 }, SizeSortCtx.lessThan);
633637
......@@ -635,7 +639,7 @@ const PackValueBits = struct {
635639
636640 for (field_order) |field_idx| {
637641 const field_ty = Type.fromInterned(zcu.typeToUnion(ty).?.field_types.get(ip)[field_idx]);
638 const pad_bits = ty.bitSize(zcu) - field_ty.bitSize(zcu);
642 const pad_bits = ty.bitSize(pt) - field_ty.bitSize(pt);
639643 if (!padding_after) try pack.padding(pad_bits);
640644 const field_val = pack.get(field_ty) catch |err| switch (err) {
641645 error.ReinterpretDeclRef => {
......@@ -651,8 +655,8 @@ const PackValueBits = struct {
651655 pack.bit_offset = prev_bit_offset;
652656 continue;
653657 }
654 const tag_val = try zcu.enumValueFieldIndex(ty.unionTagTypeHypothetical(zcu), field_idx);
655 return Value.fromInterned(try zcu.intern(.{ .un = .{
658 const tag_val = try pt.enumValueFieldIndex(ty.unionTagTypeHypothetical(zcu), field_idx);
659 return Value.fromInterned(try pt.intern(.{ .un = .{
656660 .ty = ty.toIntern(),
657661 .tag = tag_val.toIntern(),
658662 .val = field_val.toIntern(),
......@@ -662,7 +666,7 @@ const PackValueBits = struct {
662666 // No field could represent the value. Just do whatever happens when we try to read
663667 // the backing type - either `undefined` or `error.ReinterpretDeclRef`.
664668 const backing_val = try pack.get(backing_ty);
665 return Value.fromInterned(try zcu.intern(.{ .un = .{
669 return Value.fromInterned(try pt.intern(.{ .un = .{
666670 .ty = ty.toIntern(),
667671 .tag = .none,
668672 .val = backing_val.toIntern(),
......@@ -677,14 +681,14 @@ const PackValueBits = struct {
677681 }
678682
679683 fn primitive(pack: *PackValueBits, want_ty: Type) BitCastError!Value {
680 const zcu = pack.zcu;
681 const vals, const bit_offset = pack.prepareBits(want_ty.bitSize(zcu));
684 const pt = pack.pt;
685 const vals, const bit_offset = pack.prepareBits(want_ty.bitSize(pt));
682686
683687 for (vals) |val| {
684 if (!Value.fromInterned(val).isUndef(zcu)) break;
688 if (!Value.fromInterned(val).isUndef(pt.zcu)) break;
685689 } else {
686690 // All bits of the value are `undefined`.
687 return zcu.undefValue(want_ty);
691 return pt.undefValue(want_ty);
688692 }
689693
690694 // TODO: we need to decide how to handle partially-undef values here.
......@@ -702,9 +706,9 @@ const PackValueBits = struct {
702706 ptr_cast: {
703707 if (vals.len != 1) break :ptr_cast;
704708 const val = Value.fromInterned(vals[0]);
705 if (!val.typeOf(zcu).isPtrAtRuntime(zcu)) break :ptr_cast;
706 if (!want_ty.isPtrAtRuntime(zcu)) break :ptr_cast;
707 return zcu.getCoerced(val, want_ty);
709 if (!val.typeOf(pt.zcu).isPtrAtRuntime(pt.zcu)) break :ptr_cast;
710 if (!want_ty.isPtrAtRuntime(pt.zcu)) break :ptr_cast;
711 return pt.getCoerced(val, want_ty);
708712 }
709713
710714 // Reinterpret via an in-memory buffer.
......@@ -712,8 +716,8 @@ const PackValueBits = struct {
712716 var buf_bits: u64 = 0;
713717 for (vals) |ip_val| {
714718 const val = Value.fromInterned(ip_val);
715 const ty = val.typeOf(zcu);
716 buf_bits += ty.bitSize(zcu);
719 const ty = val.typeOf(pt.zcu);
720 buf_bits += ty.bitSize(pt);
717721 }
718722
719723 const buf = try pack.arena.alloc(u8, @intCast((buf_bits + 7) / 8));
......@@ -722,25 +726,25 @@ const PackValueBits = struct {
722726 var cur_bit_off: usize = 0;
723727 for (vals) |ip_val| {
724728 const val = Value.fromInterned(ip_val);
725 const ty = val.typeOf(zcu);
726 if (!val.isUndef(zcu)) {
727 try val.writeToPackedMemory(ty, zcu, buf, cur_bit_off);
729 const ty = val.typeOf(pt.zcu);
730 if (!val.isUndef(pt.zcu)) {
731 try val.writeToPackedMemory(ty, pt, buf, cur_bit_off);
728732 }
729 cur_bit_off += @intCast(ty.bitSize(zcu));
733 cur_bit_off += @intCast(ty.bitSize(pt));
730734 }
731735
732 return Value.readFromPackedMemory(want_ty, zcu, buf, @intCast(bit_offset), pack.arena);
736 return Value.readFromPackedMemory(want_ty, pt, buf, @intCast(bit_offset), pack.arena);
733737 }
734738
735739 fn prepareBits(pack: *PackValueBits, need_bits: u64) struct { []const InternPool.Index, u64 } {
736740 if (need_bits == 0) return .{ &.{}, 0 };
737741
738 const zcu = pack.zcu;
742 const pt = pack.pt;
739743
740744 var bits: u64 = 0;
741745 var len: usize = 0;
742746 while (bits < pack.bit_offset + need_bits) {
743 bits += Value.fromInterned(pack.unpacked[len]).typeOf(zcu).bitSize(zcu);
747 bits += Value.fromInterned(pack.unpacked[len]).typeOf(pt.zcu).bitSize(pt);
744748 len += 1;
745749 }
746750
......@@ -753,7 +757,7 @@ const PackValueBits = struct {
753757 pack.bit_offset = 0;
754758 } else {
755759 pack.unpacked = pack.unpacked[len - 1 ..];
756 pack.bit_offset = Value.fromInterned(pack.unpacked[0]).typeOf(zcu).bitSize(zcu) - extra_bits;
760 pack.bit_offset = Value.fromInterned(pack.unpacked[0]).typeOf(pt.zcu).bitSize(pt) - extra_bits;
757761 }
758762
759763 return .{ result_vals, result_offset };
src/Sema/comptime_ptr_access.zig+57-54
......@@ -12,19 +12,19 @@ pub const ComptimeLoadResult = union(enum) {
1212};
1313
1414pub fn loadComptimePtr(sema: *Sema, block: *Block, src: LazySrcLoc, ptr: Value) !ComptimeLoadResult {
15 const zcu = sema.mod;
16 const ptr_info = ptr.typeOf(zcu).ptrInfo(zcu);
15 const pt = sema.pt;
16 const ptr_info = ptr.typeOf(pt.zcu).ptrInfo(pt.zcu);
1717 // TODO: host size for vectors is terrible
1818 const host_bits = switch (ptr_info.flags.vector_index) {
1919 .none => ptr_info.packed_offset.host_size * 8,
20 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(zcu),
20 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(pt),
2121 };
2222 const bit_offset = if (host_bits != 0) bit_offset: {
23 const child_bits = Type.fromInterned(ptr_info.child).bitSize(zcu);
23 const child_bits = Type.fromInterned(ptr_info.child).bitSize(pt);
2424 const bit_offset = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
2525 .none => 0,
2626 .runtime => return .runtime_load,
27 else => |idx| switch (zcu.getTarget().cpu.arch.endian()) {
27 else => |idx| switch (pt.zcu.getTarget().cpu.arch.endian()) {
2828 .little => child_bits * @intFromEnum(idx),
2929 .big => host_bits - child_bits * (@intFromEnum(idx) + 1), // element order reversed on big endian
3030 },
......@@ -60,28 +60,29 @@ pub fn storeComptimePtr(
6060 ptr: Value,
6161 store_val: Value,
6262) !ComptimeStoreResult {
63 const zcu = sema.mod;
63 const pt = sema.pt;
64 const zcu = pt.zcu;
6465 const ptr_info = ptr.typeOf(zcu).ptrInfo(zcu);
6566 assert(store_val.typeOf(zcu).toIntern() == ptr_info.child);
6667 // TODO: host size for vectors is terrible
6768 const host_bits = switch (ptr_info.flags.vector_index) {
6869 .none => ptr_info.packed_offset.host_size * 8,
69 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(zcu),
70 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(pt),
7071 };
7172 const bit_offset = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
7273 .none => 0,
7374 .runtime => return .runtime_store,
7475 else => |idx| switch (zcu.getTarget().cpu.arch.endian()) {
75 .little => Type.fromInterned(ptr_info.child).bitSize(zcu) * @intFromEnum(idx),
76 .big => host_bits - Type.fromInterned(ptr_info.child).bitSize(zcu) * (@intFromEnum(idx) + 1), // element order reversed on big endian
76 .little => Type.fromInterned(ptr_info.child).bitSize(pt) * @intFromEnum(idx),
77 .big => host_bits - Type.fromInterned(ptr_info.child).bitSize(pt) * (@intFromEnum(idx) + 1), // element order reversed on big endian
7778 },
7879 };
7980 const pseudo_store_ty = if (host_bits > 0) t: {
80 const need_bits = Type.fromInterned(ptr_info.child).bitSize(zcu);
81 const need_bits = Type.fromInterned(ptr_info.child).bitSize(pt);
8182 if (need_bits + bit_offset > host_bits) {
8283 return .exceeds_host_size;
8384 }
84 break :t try zcu.intType(.unsigned, @intCast(host_bits));
85 break :t try sema.pt.intType(.unsigned, @intCast(host_bits));
8586 } else Type.fromInterned(ptr_info.child);
8687
8788 const strat = try prepareComptimePtrStore(sema, block, src, ptr, pseudo_store_ty, 0);
......@@ -103,7 +104,7 @@ pub fn storeComptimePtr(
103104 .needed_well_defined => |ty| return .{ .needed_well_defined = ty },
104105 .out_of_bounds => |ty| return .{ .out_of_bounds = ty },
105106 };
106 const expected = try expected_mv.intern(zcu, sema.arena);
107 const expected = try expected_mv.intern(pt, sema.arena);
107108 if (store_val.toIntern() != expected.toIntern()) {
108109 return .{ .comptime_field_mismatch = expected };
109110 }
......@@ -126,14 +127,14 @@ pub fn storeComptimePtr(
126127 switch (strat) {
127128 .direct => |direct| {
128129 const want_ty = direct.val.typeOf(zcu);
129 const coerced_store_val = try zcu.getCoerced(store_val, want_ty);
130 const coerced_store_val = try pt.getCoerced(store_val, want_ty);
130131 direct.val.* = .{ .interned = coerced_store_val.toIntern() };
131132 return .success;
132133 },
133134 .index => |index| {
134135 const want_ty = index.val.typeOf(zcu).childType(zcu);
135 const coerced_store_val = try zcu.getCoerced(store_val, want_ty);
136 try index.val.setElem(zcu, sema.arena, @intCast(index.elem_index), .{ .interned = coerced_store_val.toIntern() });
136 const coerced_store_val = try pt.getCoerced(store_val, want_ty);
137 try index.val.setElem(pt, sema.arena, @intCast(index.elem_index), .{ .interned = coerced_store_val.toIntern() });
137138 return .success;
138139 },
139140 .flat_index => |flat| {
......@@ -149,7 +150,7 @@ pub fn storeComptimePtr(
149150 // Better would be to gather all the store targets into an array.
150151 var index: u64 = flat.flat_elem_index + idx;
151152 const val_ptr, const final_idx = (try recursiveIndex(sema, flat.val, &index)).?;
152 try val_ptr.setElem(zcu, sema.arena, @intCast(final_idx), .{ .interned = elem });
153 try val_ptr.setElem(pt, sema.arena, @intCast(final_idx), .{ .interned = elem });
153154 }
154155 return .success;
155156 },
......@@ -165,9 +166,9 @@ pub fn storeComptimePtr(
165166 .direct => |direct| .{ direct.val, 0 },
166167 .index => |index| .{
167168 index.val,
168 index.elem_index * index.val.typeOf(zcu).childType(zcu).abiSize(zcu),
169 index.elem_index * index.val.typeOf(zcu).childType(zcu).abiSize(pt),
169170 },
170 .flat_index => |flat| .{ flat.val, flat.flat_elem_index * flat.val.typeOf(zcu).arrayBase(zcu)[0].abiSize(zcu) },
171 .flat_index => |flat| .{ flat.val, flat.flat_elem_index * flat.val.typeOf(zcu).arrayBase(zcu)[0].abiSize(pt) },
171172 .reinterpret => |reinterpret| .{ reinterpret.val, reinterpret.byte_offset },
172173 else => unreachable,
173174 };
......@@ -181,7 +182,7 @@ pub fn storeComptimePtr(
181182 }
182183
183184 const new_val = try sema.bitCastSpliceVal(
184 try val_ptr.intern(zcu, sema.arena),
185 try val_ptr.intern(pt, sema.arena),
185186 store_val,
186187 byte_offset,
187188 host_bits,
......@@ -205,7 +206,8 @@ fn loadComptimePtrInner(
205206 /// before `load_ty`. Otherwise, it is ignored and may be `undefined`.
206207 array_offset: u64,
207208) !ComptimeLoadResult {
208 const zcu = sema.mod;
209 const pt = sema.pt;
210 const zcu = pt.zcu;
209211 const ip = &zcu.intern_pool;
210212
211213 const ptr = switch (ip.indexToKey(ptr_val.toIntern())) {
......@@ -263,7 +265,7 @@ fn loadComptimePtrInner(
263265 const load_one_ty, const load_count = load_ty.arrayBase(zcu);
264266 const count = if (load_one_ty.toIntern() == base_ty.toIntern()) load_count else 1;
265267
266 const want_ty = try zcu.arrayType(.{
268 const want_ty = try sema.pt.arrayType(.{
267269 .len = count,
268270 .child = base_ty.toIntern(),
269271 });
......@@ -285,7 +287,7 @@ fn loadComptimePtrInner(
285287
286288 const agg_ty = agg_val.typeOf(zcu);
287289 switch (agg_ty.zigTypeTag(zcu)) {
288 .Struct, .Pointer => break :val try agg_val.getElem(zcu, @intCast(base_index.index)),
290 .Struct, .Pointer => break :val try agg_val.getElem(sema.pt, @intCast(base_index.index)),
289291 .Union => {
290292 const tag_val: Value, const payload_mv: MutableValue = switch (agg_val) {
291293 .un => |un| .{ Value.fromInterned(un.tag), un.payload.* },
......@@ -427,7 +429,7 @@ fn loadComptimePtrInner(
427429 const next_elem_off = elem_size * (elem_idx + 1);
428430 if (cur_offset + need_bytes <= next_elem_off) {
429431 // We can look at a single array element.
430 cur_val = try cur_val.getElem(zcu, @intCast(elem_idx));
432 cur_val = try cur_val.getElem(sema.pt, @intCast(elem_idx));
431433 cur_offset -= elem_idx * elem_size;
432434 } else {
433435 break;
......@@ -437,10 +439,10 @@ fn loadComptimePtrInner(
437439 .auto => unreachable, // ill-defined layout
438440 .@"packed" => break, // let the bitcast logic handle this
439441 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
440 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
442 const start_off = cur_ty.structFieldOffset(field_idx, pt);
441443 const end_off = start_off + try sema.typeAbiSize(cur_ty.structFieldType(field_idx, zcu));
442444 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
443 cur_val = try cur_val.getElem(zcu, field_idx);
445 cur_val = try cur_val.getElem(sema.pt, field_idx);
444446 cur_offset -= start_off;
445447 break;
446448 }
......@@ -482,7 +484,7 @@ fn loadComptimePtrInner(
482484 }
483485
484486 const result_val = try sema.bitCastVal(
485 try cur_val.intern(zcu, sema.arena),
487 try cur_val.intern(sema.pt, sema.arena),
486488 load_ty,
487489 cur_offset,
488490 host_bits,
......@@ -564,7 +566,8 @@ fn prepareComptimePtrStore(
564566 /// before `store_ty`. Otherwise, it is ignored and may be `undefined`.
565567 array_offset: u64,
566568) !ComptimeStoreStrategy {
567 const zcu = sema.mod;
569 const pt = sema.pt;
570 const zcu = pt.zcu;
568571 const ip = &zcu.intern_pool;
569572
570573 const ptr = switch (ip.indexToKey(ptr_val.toIntern())) {
......@@ -587,14 +590,14 @@ fn prepareComptimePtrStore(
587590 const eu_val_ptr, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
588591 .direct => |direct| .{ direct.val, direct.alloc },
589592 .index => |index| .{
590 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
593 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
591594 index.alloc,
592595 },
593596 .flat_index => unreachable, // base_ty is not an array
594597 .reinterpret => unreachable, // base_ty has ill-defined layout
595598 else => |err| return err,
596599 };
597 try eu_val_ptr.unintern(zcu, sema.arena, false, false);
600 try eu_val_ptr.unintern(pt, sema.arena, false, false);
598601 switch (eu_val_ptr.*) {
599602 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
600603 .undef => return .undef,
......@@ -614,14 +617,14 @@ fn prepareComptimePtrStore(
614617 const opt_val_ptr, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
615618 .direct => |direct| .{ direct.val, direct.alloc },
616619 .index => |index| .{
617 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
620 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
618621 index.alloc,
619622 },
620623 .flat_index => unreachable, // base_ty is not an array
621624 .reinterpret => unreachable, // base_ty has ill-defined layout
622625 else => |err| return err,
623626 };
624 try opt_val_ptr.unintern(zcu, sema.arena, false, false);
627 try opt_val_ptr.unintern(pt, sema.arena, false, false);
625628 switch (opt_val_ptr.*) {
626629 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
627630 .undef => return .undef,
......@@ -648,7 +651,7 @@ fn prepareComptimePtrStore(
648651 const store_one_ty, const store_count = store_ty.arrayBase(zcu);
649652 const count = if (store_one_ty.toIntern() == base_ty.toIntern()) store_count else 1;
650653
651 const want_ty = try zcu.arrayType(.{
654 const want_ty = try pt.arrayType(.{
652655 .len = count,
653656 .child = base_ty.toIntern(),
654657 });
......@@ -668,7 +671,7 @@ fn prepareComptimePtrStore(
668671 const agg_val, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
669672 .direct => |direct| .{ direct.val, direct.alloc },
670673 .index => |index| .{
671 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
674 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
672675 index.alloc,
673676 },
674677 .flat_index => unreachable, // base_ty is not an array
......@@ -679,14 +682,14 @@ fn prepareComptimePtrStore(
679682 const agg_ty = agg_val.typeOf(zcu);
680683 switch (agg_ty.zigTypeTag(zcu)) {
681684 .Struct, .Pointer => break :strat .{ .direct = .{
682 .val = try agg_val.elem(zcu, sema.arena, @intCast(base_index.index)),
685 .val = try agg_val.elem(pt, sema.arena, @intCast(base_index.index)),
683686 .alloc = alloc,
684687 } },
685688 .Union => {
686689 if (agg_val.* == .interned and Value.fromInterned(agg_val.interned).isUndef(zcu)) {
687690 return .undef;
688691 }
689 try agg_val.unintern(zcu, sema.arena, false, false);
692 try agg_val.unintern(pt, sema.arena, false, false);
690693 const un = agg_val.un;
691694 const tag_ty = agg_ty.unionTagTypeHypothetical(zcu);
692695 if (tag_ty.enumTagFieldIndex(Value.fromInterned(un.tag), zcu).? != base_index.index) {
......@@ -847,7 +850,7 @@ fn prepareComptimePtrStore(
847850 const next_elem_off = elem_size * (elem_idx + 1);
848851 if (cur_offset + need_bytes <= next_elem_off) {
849852 // We can look at a single array element.
850 cur_val = try cur_val.elem(zcu, sema.arena, @intCast(elem_idx));
853 cur_val = try cur_val.elem(pt, sema.arena, @intCast(elem_idx));
851854 cur_offset -= elem_idx * elem_size;
852855 } else {
853856 break;
......@@ -857,10 +860,10 @@ fn prepareComptimePtrStore(
857860 .auto => unreachable, // ill-defined layout
858861 .@"packed" => break, // let the bitcast logic handle this
859862 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
860 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
863 const start_off = cur_ty.structFieldOffset(field_idx, pt);
861864 const end_off = start_off + try sema.typeAbiSize(cur_ty.structFieldType(field_idx, zcu));
862865 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
863 cur_val = try cur_val.elem(zcu, sema.arena, field_idx);
866 cur_val = try cur_val.elem(pt, sema.arena, field_idx);
864867 cur_offset -= start_off;
865868 break;
866869 }
......@@ -874,7 +877,7 @@ fn prepareComptimePtrStore(
874877 // Otherwise, we might traverse into a union field which doesn't allow pointers.
875878 // Figure out a solution!
876879 if (true) break;
877 try cur_val.unintern(zcu, sema.arena, false, false);
880 try cur_val.unintern(pt, sema.arena, false, false);
878881 const payload = switch (cur_val.*) {
879882 .un => |un| un.payload,
880883 else => unreachable,
......@@ -918,7 +921,7 @@ fn flattenArray(
918921) Allocator.Error!void {
919922 if (next_idx.* == out.len) return;
920923
921 const zcu = sema.mod;
924 const zcu = sema.pt.zcu;
922925
923926 const ty = val.typeOf(zcu);
924927 const base_elem_count = ty.arrayBase(zcu)[1];
......@@ -928,7 +931,7 @@ fn flattenArray(
928931 }
929932
930933 if (ty.zigTypeTag(zcu) != .Array) {
931 out[@intCast(next_idx.*)] = (try val.intern(zcu, sema.arena)).toIntern();
934 out[@intCast(next_idx.*)] = (try val.intern(sema.pt, sema.arena)).toIntern();
932935 next_idx.* += 1;
933936 return;
934937 }
......@@ -942,7 +945,7 @@ fn flattenArray(
942945 skip.* -= arr_base_elem_count;
943946 continue;
944947 }
945 try flattenArray(sema, try val.getElem(zcu, elem_idx), skip, next_idx, out);
948 try flattenArray(sema, try val.getElem(sema.pt, elem_idx), skip, next_idx, out);
946949 }
947950 if (ty.sentinel(zcu)) |s| {
948951 try flattenArray(sema, .{ .interned = s.toIntern() }, skip, next_idx, out);
......@@ -957,13 +960,13 @@ fn unflattenArray(
957960 elems: []const InternPool.Index,
958961 next_idx: *u64,
959962) Allocator.Error!Value {
960 const zcu = sema.mod;
963 const zcu = sema.pt.zcu;
961964 const arena = sema.arena;
962965
963966 if (ty.zigTypeTag(zcu) != .Array) {
964967 const val = Value.fromInterned(elems[@intCast(next_idx.*)]);
965968 next_idx.* += 1;
966 return zcu.getCoerced(val, ty);
969 return sema.pt.getCoerced(val, ty);
967970 }
968971
969972 const elem_ty = ty.childType(zcu);
......@@ -975,7 +978,7 @@ fn unflattenArray(
975978 // TODO: validate sentinel
976979 _ = try unflattenArray(sema, elem_ty, elems, next_idx);
977980 }
978 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
981 return Value.fromInterned(try sema.pt.intern(.{ .aggregate = .{
979982 .ty = ty.toIntern(),
980983 .storage = .{ .elems = buf },
981984 } }));
......@@ -990,25 +993,25 @@ fn recursiveIndex(
990993 mv: *MutableValue,
991994 index: *u64,
992995) !?struct { *MutableValue, u64 } {
993 const zcu = sema.mod;
996 const pt = sema.pt;
994997
995 const ty = mv.typeOf(zcu);
996 assert(ty.zigTypeTag(zcu) == .Array);
998 const ty = mv.typeOf(pt.zcu);
999 assert(ty.zigTypeTag(pt.zcu) == .Array);
9971000
998 const ty_base_elems = ty.arrayBase(zcu)[1];
1001 const ty_base_elems = ty.arrayBase(pt.zcu)[1];
9991002 if (index.* >= ty_base_elems) {
10001003 index.* -= ty_base_elems;
10011004 return null;
10021005 }
10031006
1004 const elem_ty = ty.childType(zcu);
1005 if (elem_ty.zigTypeTag(zcu) != .Array) {
1006 assert(index.* < ty.arrayLenIncludingSentinel(zcu)); // should be handled by initial check
1007 const elem_ty = ty.childType(pt.zcu);
1008 if (elem_ty.zigTypeTag(pt.zcu) != .Array) {
1009 assert(index.* < ty.arrayLenIncludingSentinel(pt.zcu)); // should be handled by initial check
10071010 return .{ mv, index.* };
10081011 }
10091012
1010 for (0..@intCast(ty.arrayLenIncludingSentinel(zcu))) |elem_index| {
1011 if (try recursiveIndex(sema, try mv.elem(zcu, sema.arena, elem_index), index)) |result| {
1013 for (0..@intCast(ty.arrayLenIncludingSentinel(pt.zcu))) |elem_index| {
1014 if (try recursiveIndex(sema, try mv.elem(pt, sema.arena, elem_index), index)) |result| {
10121015 return result;
10131016 }
10141017 }
src/Type.zig+376-361
......@@ -136,16 +136,16 @@ pub fn format(ty: Type, comptime unused_fmt_string: []const u8, options: std.fmt
136136
137137pub const Formatter = std.fmt.Formatter(format2);
138138
139pub fn fmt(ty: Type, module: *Module) Formatter {
139pub fn fmt(ty: Type, pt: Zcu.PerThread) Formatter {
140140 return .{ .data = .{
141141 .ty = ty,
142 .module = module,
142 .pt = pt,
143143 } };
144144}
145145
146146const FormatContext = struct {
147147 ty: Type,
148 module: *Module,
148 pt: Zcu.PerThread,
149149};
150150
151151fn format2(
......@@ -156,7 +156,7 @@ fn format2(
156156) !void {
157157 comptime assert(unused_format_string.len == 0);
158158 _ = options;
159 return print(ctx.ty, writer, ctx.module);
159 return print(ctx.ty, writer, ctx.pt);
160160}
161161
162162pub fn fmtDebug(ty: Type) std.fmt.Formatter(dump) {
......@@ -178,7 +178,8 @@ pub fn dump(
178178
179179/// Prints a name suitable for `@typeName`.
180180/// TODO: take an `opt_sema` to pass to `fmtValue` when printing sentinels.
181pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void {
181pub fn print(ty: Type, writer: anytype, pt: Zcu.PerThread) @TypeOf(writer).Error!void {
182 const mod = pt.zcu;
182183 const ip = &mod.intern_pool;
183184 switch (ip.indexToKey(ty.toIntern())) {
184185 .int_type => |int_type| {
......@@ -193,8 +194,8 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
193194
194195 if (info.sentinel != .none) switch (info.flags.size) {
195196 .One, .C => unreachable,
196 .Many => try writer.print("[*:{}]", .{Value.fromInterned(info.sentinel).fmtValue(mod, null)}),
197 .Slice => try writer.print("[:{}]", .{Value.fromInterned(info.sentinel).fmtValue(mod, null)}),
197 .Many => try writer.print("[*:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt, null)}),
198 .Slice => try writer.print("[:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt, null)}),
198199 } else switch (info.flags.size) {
199200 .One => try writer.writeAll("*"),
200201 .Many => try writer.writeAll("[*]"),
......@@ -208,7 +209,7 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
208209 const alignment = if (info.flags.alignment != .none)
209210 info.flags.alignment
210211 else
211 Type.fromInterned(info.child).abiAlignment(mod);
212 Type.fromInterned(info.child).abiAlignment(pt);
212213 try writer.print("align({d}", .{alignment.toByteUnits() orelse 0});
213214
214215 if (info.packed_offset.bit_offset != 0 or info.packed_offset.host_size != 0) {
......@@ -230,39 +231,39 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
230231 if (info.flags.is_volatile) try writer.writeAll("volatile ");
231232 if (info.flags.is_allowzero and info.flags.size != .C) try writer.writeAll("allowzero ");
232233
233 try print(Type.fromInterned(info.child), writer, mod);
234 try print(Type.fromInterned(info.child), writer, pt);
234235 return;
235236 },
236237 .array_type => |array_type| {
237238 if (array_type.sentinel == .none) {
238239 try writer.print("[{d}]", .{array_type.len});
239 try print(Type.fromInterned(array_type.child), writer, mod);
240 try print(Type.fromInterned(array_type.child), writer, pt);
240241 } else {
241242 try writer.print("[{d}:{}]", .{
242243 array_type.len,
243 Value.fromInterned(array_type.sentinel).fmtValue(mod, null),
244 Value.fromInterned(array_type.sentinel).fmtValue(pt, null),
244245 });
245 try print(Type.fromInterned(array_type.child), writer, mod);
246 try print(Type.fromInterned(array_type.child), writer, pt);
246247 }
247248 return;
248249 },
249250 .vector_type => |vector_type| {
250251 try writer.print("@Vector({d}, ", .{vector_type.len});
251 try print(Type.fromInterned(vector_type.child), writer, mod);
252 try print(Type.fromInterned(vector_type.child), writer, pt);
252253 try writer.writeAll(")");
253254 return;
254255 },
255256 .opt_type => |child| {
256257 try writer.writeByte('?');
257 return print(Type.fromInterned(child), writer, mod);
258 return print(Type.fromInterned(child), writer, pt);
258259 },
259260 .error_union_type => |error_union_type| {
260 try print(Type.fromInterned(error_union_type.error_set_type), writer, mod);
261 try print(Type.fromInterned(error_union_type.error_set_type), writer, pt);
261262 try writer.writeByte('!');
262263 if (error_union_type.payload_type == .generic_poison_type) {
263264 try writer.writeAll("anytype");
264265 } else {
265 try print(Type.fromInterned(error_union_type.payload_type), writer, mod);
266 try print(Type.fromInterned(error_union_type.payload_type), writer, pt);
266267 }
267268 return;
268269 },
......@@ -355,10 +356,10 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
355356 try writer.print("{}: ", .{anon_struct.names.get(ip)[i].fmt(&mod.intern_pool)});
356357 }
357358
358 try print(Type.fromInterned(field_ty), writer, mod);
359 try print(Type.fromInterned(field_ty), writer, pt);
359360
360361 if (val != .none) {
361 try writer.print(" = {}", .{Value.fromInterned(val).fmtValue(mod, null)});
362 try writer.print(" = {}", .{Value.fromInterned(val).fmtValue(pt, null)});
362363 }
363364 }
364365 try writer.writeAll("}");
......@@ -395,7 +396,7 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
395396 if (param_ty == .generic_poison_type) {
396397 try writer.writeAll("anytype");
397398 } else {
398 try print(Type.fromInterned(param_ty), writer, mod);
399 try print(Type.fromInterned(param_ty), writer, pt);
399400 }
400401 }
401402 if (fn_info.is_var_args) {
......@@ -413,13 +414,13 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
413414 if (fn_info.return_type == .generic_poison_type) {
414415 try writer.writeAll("anytype");
415416 } else {
416 try print(Type.fromInterned(fn_info.return_type), writer, mod);
417 try print(Type.fromInterned(fn_info.return_type), writer, pt);
417418 }
418419 },
419420 .anyframe_type => |child| {
420421 if (child == .none) return writer.writeAll("anyframe");
421422 try writer.writeAll("anyframe->");
422 return print(Type.fromInterned(child), writer, mod);
423 return print(Type.fromInterned(child), writer, pt);
423424 },
424425
425426 // values, not types
......@@ -475,10 +476,11 @@ const RuntimeBitsError = SemaError || error{NeedLazy};
475476/// may return false positives.
476477pub fn hasRuntimeBitsAdvanced(
477478 ty: Type,
478 mod: *Module,
479 pt: Zcu.PerThread,
479480 ignore_comptime_only: bool,
480481 strat: ResolveStratLazy,
481482) RuntimeBitsError!bool {
483 const mod = pt.zcu;
482484 const ip = &mod.intern_pool;
483485 return switch (ty.toIntern()) {
484486 // False because it is a comptime-only type.
......@@ -490,16 +492,16 @@ pub fn hasRuntimeBitsAdvanced(
490492 // to comptime-only types do not, with the exception of function pointers.
491493 if (ignore_comptime_only) return true;
492494 return switch (strat) {
493 .sema => !try ty.comptimeOnlyAdvanced(mod, .sema),
494 .eager => !ty.comptimeOnly(mod),
495 .sema => !try ty.comptimeOnlyAdvanced(pt, .sema),
496 .eager => !ty.comptimeOnly(pt),
495497 .lazy => error.NeedLazy,
496498 };
497499 },
498500 .anyframe_type => true,
499501 .array_type => |array_type| return array_type.lenIncludingSentinel() > 0 and
500 try Type.fromInterned(array_type.child).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
502 try Type.fromInterned(array_type.child).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
501503 .vector_type => |vector_type| return vector_type.len > 0 and
502 try Type.fromInterned(vector_type.child).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
504 try Type.fromInterned(vector_type.child).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
503505 .opt_type => |child| {
504506 const child_ty = Type.fromInterned(child);
505507 if (child_ty.isNoReturn(mod)) {
......@@ -508,8 +510,8 @@ pub fn hasRuntimeBitsAdvanced(
508510 }
509511 if (ignore_comptime_only) return true;
510512 return switch (strat) {
511 .sema => !try child_ty.comptimeOnlyAdvanced(mod, .sema),
512 .eager => !child_ty.comptimeOnly(mod),
513 .sema => !try child_ty.comptimeOnlyAdvanced(pt, .sema),
514 .eager => !child_ty.comptimeOnly(pt),
513515 .lazy => error.NeedLazy,
514516 };
515517 },
......@@ -580,14 +582,14 @@ pub fn hasRuntimeBitsAdvanced(
580582 return true;
581583 }
582584 switch (strat) {
583 .sema => try ty.resolveFields(mod),
585 .sema => try ty.resolveFields(pt),
584586 .eager => assert(struct_type.haveFieldTypes(ip)),
585587 .lazy => if (!struct_type.haveFieldTypes(ip)) return error.NeedLazy,
586588 }
587589 for (0..struct_type.field_types.len) |i| {
588590 if (struct_type.comptime_bits.getBit(ip, i)) continue;
589591 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
590 if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
592 if (try field_ty.hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
591593 return true;
592594 } else {
593595 return false;
......@@ -596,7 +598,7 @@ pub fn hasRuntimeBitsAdvanced(
596598 .anon_struct_type => |tuple| {
597599 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
598600 if (val != .none) continue; // comptime field
599 if (try Type.fromInterned(field_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat)) return true;
601 if (try Type.fromInterned(field_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat)) return true;
600602 }
601603 return false;
602604 },
......@@ -617,21 +619,21 @@ pub fn hasRuntimeBitsAdvanced(
617619 // tag_ty will be `none` if this union's tag type is not resolved yet,
618620 // in which case we want control flow to continue down below.
619621 if (tag_ty != .none and
620 try Type.fromInterned(tag_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
622 try Type.fromInterned(tag_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
621623 {
622624 return true;
623625 }
624626 },
625627 }
626628 switch (strat) {
627 .sema => try ty.resolveFields(mod),
629 .sema => try ty.resolveFields(pt),
628630 .eager => assert(union_type.flagsPtr(ip).status.haveFieldTypes()),
629631 .lazy => if (!union_type.flagsPtr(ip).status.haveFieldTypes())
630632 return error.NeedLazy,
631633 }
632634 for (0..union_type.field_types.len) |field_index| {
633635 const field_ty = Type.fromInterned(union_type.field_types.get(ip)[field_index]);
634 if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
636 if (try field_ty.hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
635637 return true;
636638 } else {
637639 return false;
......@@ -639,7 +641,7 @@ pub fn hasRuntimeBitsAdvanced(
639641 },
640642
641643 .opaque_type => true,
642 .enum_type => Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
644 .enum_type => Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
643645
644646 // values, not types
645647 .undef,
......@@ -777,41 +779,41 @@ pub fn hasWellDefinedLayout(ty: Type, mod: *Module) bool {
777779 };
778780}
779781
780pub fn hasRuntimeBits(ty: Type, mod: *Module) bool {
781 return hasRuntimeBitsAdvanced(ty, mod, false, .eager) catch unreachable;
782pub fn hasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
783 return hasRuntimeBitsAdvanced(ty, pt, false, .eager) catch unreachable;
782784}
783785
784pub fn hasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
785 return hasRuntimeBitsAdvanced(ty, mod, true, .eager) catch unreachable;
786pub fn hasRuntimeBitsIgnoreComptime(ty: Type, pt: Zcu.PerThread) bool {
787 return hasRuntimeBitsAdvanced(ty, pt, true, .eager) catch unreachable;
786788}
787789
788pub fn fnHasRuntimeBits(ty: Type, mod: *Module) bool {
789 return ty.fnHasRuntimeBitsAdvanced(mod, .normal) catch unreachable;
790pub fn fnHasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
791 return ty.fnHasRuntimeBitsAdvanced(pt, .normal) catch unreachable;
790792}
791793
792794/// Determines whether a function type has runtime bits, i.e. whether a
793795/// function with this type can exist at runtime.
794796/// Asserts that `ty` is a function type.
795pub fn fnHasRuntimeBitsAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaError!bool {
796 const fn_info = mod.typeToFunc(ty).?;
797pub fn fnHasRuntimeBitsAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) SemaError!bool {
798 const fn_info = pt.zcu.typeToFunc(ty).?;
797799 if (fn_info.is_generic) return false;
798800 if (fn_info.is_var_args) return true;
799801 if (fn_info.cc == .Inline) return false;
800 return !try Type.fromInterned(fn_info.return_type).comptimeOnlyAdvanced(mod, strat);
802 return !try Type.fromInterned(fn_info.return_type).comptimeOnlyAdvanced(pt, strat);
801803}
802804
803pub fn isFnOrHasRuntimeBits(ty: Type, mod: *Module) bool {
804 switch (ty.zigTypeTag(mod)) {
805 .Fn => return ty.fnHasRuntimeBits(mod),
806 else => return ty.hasRuntimeBits(mod),
805pub fn isFnOrHasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
806 switch (ty.zigTypeTag(pt.zcu)) {
807 .Fn => return ty.fnHasRuntimeBits(pt),
808 else => return ty.hasRuntimeBits(pt),
807809 }
808810}
809811
810812/// Same as `isFnOrHasRuntimeBits` but comptime-only types may return a false positive.
811pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
812 return switch (ty.zigTypeTag(mod)) {
813pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, pt: Zcu.PerThread) bool {
814 return switch (ty.zigTypeTag(pt.zcu)) {
813815 .Fn => true,
814 else => return ty.hasRuntimeBitsIgnoreComptime(mod),
816 else => return ty.hasRuntimeBitsIgnoreComptime(pt),
815817 };
816818}
817819
......@@ -820,24 +822,24 @@ pub fn isNoReturn(ty: Type, mod: *Module) bool {
820822}
821823
822824/// Returns `none` if the pointer is naturally aligned and the element type is 0-bit.
823pub fn ptrAlignment(ty: Type, mod: *Module) Alignment {
824 return ptrAlignmentAdvanced(ty, mod, .normal) catch unreachable;
825pub fn ptrAlignment(ty: Type, pt: Zcu.PerThread) Alignment {
826 return ptrAlignmentAdvanced(ty, pt, .normal) catch unreachable;
825827}
826828
827pub fn ptrAlignmentAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) !Alignment {
828 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
829pub fn ptrAlignmentAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) !Alignment {
830 return switch (pt.zcu.intern_pool.indexToKey(ty.toIntern())) {
829831 .ptr_type => |ptr_type| {
830832 if (ptr_type.flags.alignment != .none)
831833 return ptr_type.flags.alignment;
832834
833835 if (strat == .sema) {
834 const res = try Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(mod, .sema);
836 const res = try Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(pt, .sema);
835837 return res.scalar;
836838 }
837839
838 return (Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
840 return (Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(pt, .eager) catch unreachable).scalar;
839841 },
840 .opt_type => |child| Type.fromInterned(child).ptrAlignmentAdvanced(mod, strat),
842 .opt_type => |child| Type.fromInterned(child).ptrAlignmentAdvanced(pt, strat),
841843 else => unreachable,
842844 };
843845}
......@@ -851,16 +853,16 @@ pub fn ptrAddressSpace(ty: Type, mod: *const Module) std.builtin.AddressSpace {
851853}
852854
853855/// Never returns `none`. Asserts that all necessary type resolution is already done.
854pub fn abiAlignment(ty: Type, mod: *Module) Alignment {
855 return (ty.abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
856pub fn abiAlignment(ty: Type, pt: Zcu.PerThread) Alignment {
857 return (ty.abiAlignmentAdvanced(pt, .eager) catch unreachable).scalar;
856858}
857859
858860/// May capture a reference to `ty`.
859861/// Returned value has type `comptime_int`.
860pub fn lazyAbiAlignment(ty: Type, mod: *Module) !Value {
861 switch (try ty.abiAlignmentAdvanced(mod, .lazy)) {
862pub fn lazyAbiAlignment(ty: Type, pt: Zcu.PerThread) !Value {
863 switch (try ty.abiAlignmentAdvanced(pt, .lazy)) {
862864 .val => |val| return val,
863 .scalar => |x| return mod.intValue(Type.comptime_int, x.toByteUnits() orelse 0),
865 .scalar => |x| return pt.intValue(Type.comptime_int, x.toByteUnits() orelse 0),
864866 }
865867}
866868
......@@ -907,38 +909,39 @@ pub const ResolveStrat = enum {
907909/// necessary, possibly returning a CompileError.
908910pub fn abiAlignmentAdvanced(
909911 ty: Type,
910 mod: *Module,
912 pt: Zcu.PerThread,
911913 strat: ResolveStratLazy,
912914) SemaError!AbiAlignmentAdvanced {
915 const mod = pt.zcu;
913916 const target = mod.getTarget();
914917 const use_llvm = mod.comp.config.use_llvm;
915918 const ip = &mod.intern_pool;
916919
917920 switch (ty.toIntern()) {
918 .empty_struct_type => return AbiAlignmentAdvanced{ .scalar = .@"1" },
921 .empty_struct_type => return .{ .scalar = .@"1" },
919922 else => switch (ip.indexToKey(ty.toIntern())) {
920923 .int_type => |int_type| {
921 if (int_type.bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
924 if (int_type.bits == 0) return .{ .scalar = .@"1" };
922925 return .{ .scalar = intAbiAlignment(int_type.bits, target, use_llvm) };
923926 },
924927 .ptr_type, .anyframe_type => {
925928 return .{ .scalar = ptrAbiAlignment(target) };
926929 },
927930 .array_type => |array_type| {
928 return Type.fromInterned(array_type.child).abiAlignmentAdvanced(mod, strat);
931 return Type.fromInterned(array_type.child).abiAlignmentAdvanced(pt, strat);
929932 },
930933 .vector_type => |vector_type| {
931934 if (vector_type.len == 0) return .{ .scalar = .@"1" };
932935 switch (mod.comp.getZigBackend()) {
933936 else => {
934 const elem_bits: u32 = @intCast(try Type.fromInterned(vector_type.child).bitSizeAdvanced(mod, .sema));
937 const elem_bits: u32 = @intCast(try Type.fromInterned(vector_type.child).bitSizeAdvanced(pt, .sema));
935938 if (elem_bits == 0) return .{ .scalar = .@"1" };
936939 const bytes = ((elem_bits * vector_type.len) + 7) / 8;
937940 const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
938941 return .{ .scalar = Alignment.fromByteUnits(alignment) };
939942 },
940943 .stage2_c => {
941 return Type.fromInterned(vector_type.child).abiAlignmentAdvanced(mod, strat);
944 return Type.fromInterned(vector_type.child).abiAlignmentAdvanced(pt, strat);
942945 },
943946 .stage2_x86_64 => {
944947 if (vector_type.child == .bool_type) {
......@@ -949,7 +952,7 @@ pub fn abiAlignmentAdvanced(
949952 const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
950953 return .{ .scalar = Alignment.fromByteUnits(alignment) };
951954 }
952 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
955 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
953956 if (elem_bytes == 0) return .{ .scalar = .@"1" };
954957 const bytes = elem_bytes * vector_type.len;
955958 if (bytes > 32 and std.Target.x86.featureSetHas(target.cpu.features, .avx512f)) return .{ .scalar = .@"64" };
......@@ -959,12 +962,12 @@ pub fn abiAlignmentAdvanced(
959962 }
960963 },
961964
962 .opt_type => return abiAlignmentAdvancedOptional(ty, mod, strat),
963 .error_union_type => |info| return abiAlignmentAdvancedErrorUnion(ty, mod, strat, Type.fromInterned(info.payload_type)),
965 .opt_type => return ty.abiAlignmentAdvancedOptional(pt, strat),
966 .error_union_type => |info| return ty.abiAlignmentAdvancedErrorUnion(pt, strat, Type.fromInterned(info.payload_type)),
964967
965968 .error_set_type, .inferred_error_set_type => {
966969 const bits = mod.errorSetBits();
967 if (bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
970 if (bits == 0) return .{ .scalar = .@"1" };
968971 return .{ .scalar = intAbiAlignment(bits, target, use_llvm) };
969972 },
970973
......@@ -1012,10 +1015,7 @@ pub fn abiAlignmentAdvanced(
10121015 },
10131016 .f80 => switch (target.c_type_bit_size(.longdouble)) {
10141017 80 => return .{ .scalar = cTypeAlign(target, .longdouble) },
1015 else => {
1016 const u80_ty: Type = .{ .ip_index = .u80_type };
1017 return .{ .scalar = abiAlignment(u80_ty, mod) };
1018 },
1018 else => return .{ .scalar = Type.u80.abiAlignment(pt) },
10191019 },
10201020 .f128 => switch (target.c_type_bit_size(.longdouble)) {
10211021 128 => return .{ .scalar = cTypeAlign(target, .longdouble) },
......@@ -1024,7 +1024,7 @@ pub fn abiAlignmentAdvanced(
10241024
10251025 .anyerror, .adhoc_inferred_error_set => {
10261026 const bits = mod.errorSetBits();
1027 if (bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
1027 if (bits == 0) return .{ .scalar = .@"1" };
10281028 return .{ .scalar = intAbiAlignment(bits, target, use_llvm) };
10291029 },
10301030
......@@ -1044,22 +1044,22 @@ pub fn abiAlignmentAdvanced(
10441044 const struct_type = ip.loadStructType(ty.toIntern());
10451045 if (struct_type.layout == .@"packed") {
10461046 switch (strat) {
1047 .sema => try ty.resolveLayout(mod),
1047 .sema => try ty.resolveLayout(pt),
10481048 .lazy => if (struct_type.backingIntType(ip).* == .none) return .{
1049 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1049 .val = Value.fromInterned(try pt.intern(.{ .int = .{
10501050 .ty = .comptime_int_type,
10511051 .storage = .{ .lazy_align = ty.toIntern() },
1052 } }))),
1052 } })),
10531053 },
10541054 .eager => {},
10551055 }
1056 return .{ .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiAlignment(mod) };
1056 return .{ .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiAlignment(pt) };
10571057 }
10581058
10591059 if (struct_type.flagsPtr(ip).alignment == .none) switch (strat) {
10601060 .eager => unreachable, // struct alignment not resolved
1061 .sema => try ty.resolveStructAlignment(mod),
1062 .lazy => return .{ .val = Value.fromInterned(try mod.intern(.{ .int = .{
1061 .sema => try ty.resolveStructAlignment(pt),
1062 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10631063 .ty = .comptime_int_type,
10641064 .storage = .{ .lazy_align = ty.toIntern() },
10651065 } })) },
......@@ -1071,15 +1071,15 @@ pub fn abiAlignmentAdvanced(
10711071 var big_align: Alignment = .@"1";
10721072 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
10731073 if (val != .none) continue; // comptime field
1074 switch (try Type.fromInterned(field_ty).abiAlignmentAdvanced(mod, strat)) {
1074 switch (try Type.fromInterned(field_ty).abiAlignmentAdvanced(pt, strat)) {
10751075 .scalar => |field_align| big_align = big_align.max(field_align),
10761076 .val => switch (strat) {
10771077 .eager => unreachable, // field type alignment not resolved
10781078 .sema => unreachable, // passed to abiAlignmentAdvanced above
1079 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1079 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10801080 .ty = .comptime_int_type,
10811081 .storage = .{ .lazy_align = ty.toIntern() },
1082 } }))) },
1082 } })) },
10831083 },
10841084 }
10851085 }
......@@ -1090,18 +1090,18 @@ pub fn abiAlignmentAdvanced(
10901090
10911091 if (union_type.flagsPtr(ip).alignment == .none) switch (strat) {
10921092 .eager => unreachable, // union layout not resolved
1093 .sema => try ty.resolveUnionAlignment(mod),
1094 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1093 .sema => try ty.resolveUnionAlignment(pt),
1094 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10951095 .ty = .comptime_int_type,
10961096 .storage = .{ .lazy_align = ty.toIntern() },
1097 } }))) },
1097 } })) },
10981098 };
10991099
11001100 return .{ .scalar = union_type.flagsPtr(ip).alignment };
11011101 },
11021102 .opaque_type => return .{ .scalar = .@"1" },
11031103 .enum_type => return .{
1104 .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiAlignment(mod),
1104 .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiAlignment(pt),
11051105 },
11061106
11071107 // values, not types
......@@ -1131,91 +1131,92 @@ pub fn abiAlignmentAdvanced(
11311131
11321132fn abiAlignmentAdvancedErrorUnion(
11331133 ty: Type,
1134 mod: *Module,
1134 pt: Zcu.PerThread,
11351135 strat: ResolveStratLazy,
11361136 payload_ty: Type,
11371137) SemaError!AbiAlignmentAdvanced {
11381138 // This code needs to be kept in sync with the equivalent switch prong
11391139 // in abiSizeAdvanced.
1140 const code_align = abiAlignment(Type.anyerror, mod);
1140 const code_align = Type.anyerror.abiAlignment(pt);
11411141 switch (strat) {
11421142 .eager, .sema => {
1143 if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1144 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1143 if (!(payload_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1144 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11451145 .ty = .comptime_int_type,
11461146 .storage = .{ .lazy_align = ty.toIntern() },
1147 } }))) },
1147 } })) },
11481148 else => |e| return e,
11491149 })) {
11501150 return .{ .scalar = code_align };
11511151 }
11521152 return .{ .scalar = code_align.max(
1153 (try payload_ty.abiAlignmentAdvanced(mod, strat)).scalar,
1153 (try payload_ty.abiAlignmentAdvanced(pt, strat)).scalar,
11541154 ) };
11551155 },
11561156 .lazy => {
1157 switch (try payload_ty.abiAlignmentAdvanced(mod, strat)) {
1157 switch (try payload_ty.abiAlignmentAdvanced(pt, strat)) {
11581158 .scalar => |payload_align| return .{ .scalar = code_align.max(payload_align) },
11591159 .val => {},
11601160 }
1161 return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1161 return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11621162 .ty = .comptime_int_type,
11631163 .storage = .{ .lazy_align = ty.toIntern() },
1164 } }))) };
1164 } })) };
11651165 },
11661166 }
11671167}
11681168
11691169fn abiAlignmentAdvancedOptional(
11701170 ty: Type,
1171 mod: *Module,
1171 pt: Zcu.PerThread,
11721172 strat: ResolveStratLazy,
11731173) SemaError!AbiAlignmentAdvanced {
1174 const mod = pt.zcu;
11741175 const target = mod.getTarget();
11751176 const child_type = ty.optionalChild(mod);
11761177
11771178 switch (child_type.zigTypeTag(mod)) {
11781179 .Pointer => return .{ .scalar = ptrAbiAlignment(target) },
1179 .ErrorSet => return abiAlignmentAdvanced(Type.anyerror, mod, strat),
1180 .ErrorSet => return Type.anyerror.abiAlignmentAdvanced(pt, strat),
11801181 .NoReturn => return .{ .scalar = .@"1" },
11811182 else => {},
11821183 }
11831184
11841185 switch (strat) {
11851186 .eager, .sema => {
1186 if (!(child_type.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1187 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1187 if (!(child_type.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1188 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11881189 .ty = .comptime_int_type,
11891190 .storage = .{ .lazy_align = ty.toIntern() },
1190 } }))) },
1191 } })) },
11911192 else => |e| return e,
11921193 })) {
11931194 return .{ .scalar = .@"1" };
11941195 }
1195 return child_type.abiAlignmentAdvanced(mod, strat);
1196 return child_type.abiAlignmentAdvanced(pt, strat);
11961197 },
1197 .lazy => switch (try child_type.abiAlignmentAdvanced(mod, strat)) {
1198 .lazy => switch (try child_type.abiAlignmentAdvanced(pt, strat)) {
11981199 .scalar => |x| return .{ .scalar = x.max(.@"1") },
1199 .val => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1200 .val => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12001201 .ty = .comptime_int_type,
12011202 .storage = .{ .lazy_align = ty.toIntern() },
1202 } }))) },
1203 } })) },
12031204 },
12041205 }
12051206}
12061207
12071208/// May capture a reference to `ty`.
1208pub fn lazyAbiSize(ty: Type, mod: *Module) !Value {
1209 switch (try ty.abiSizeAdvanced(mod, .lazy)) {
1209pub fn lazyAbiSize(ty: Type, pt: Zcu.PerThread) !Value {
1210 switch (try ty.abiSizeAdvanced(pt, .lazy)) {
12101211 .val => |val| return val,
1211 .scalar => |x| return mod.intValue(Type.comptime_int, x),
1212 .scalar => |x| return pt.intValue(Type.comptime_int, x),
12121213 }
12131214}
12141215
12151216/// Asserts the type has the ABI size already resolved.
12161217/// Types that return false for hasRuntimeBits() return 0.
1217pub fn abiSize(ty: Type, mod: *Module) u64 {
1218 return (abiSizeAdvanced(ty, mod, .eager) catch unreachable).scalar;
1218pub fn abiSize(ty: Type, pt: Zcu.PerThread) u64 {
1219 return (abiSizeAdvanced(ty, pt, .eager) catch unreachable).scalar;
12191220}
12201221
12211222const AbiSizeAdvanced = union(enum) {
......@@ -1231,38 +1232,39 @@ const AbiSizeAdvanced = union(enum) {
12311232/// necessary, possibly returning a CompileError.
12321233pub fn abiSizeAdvanced(
12331234 ty: Type,
1234 mod: *Module,
1235 pt: Zcu.PerThread,
12351236 strat: ResolveStratLazy,
12361237) SemaError!AbiSizeAdvanced {
1238 const mod = pt.zcu;
12371239 const target = mod.getTarget();
12381240 const use_llvm = mod.comp.config.use_llvm;
12391241 const ip = &mod.intern_pool;
12401242
12411243 switch (ty.toIntern()) {
1242 .empty_struct_type => return AbiSizeAdvanced{ .scalar = 0 },
1244 .empty_struct_type => return .{ .scalar = 0 },
12431245
12441246 else => switch (ip.indexToKey(ty.toIntern())) {
12451247 .int_type => |int_type| {
1246 if (int_type.bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1247 return AbiSizeAdvanced{ .scalar = intAbiSize(int_type.bits, target, use_llvm) };
1248 if (int_type.bits == 0) return .{ .scalar = 0 };
1249 return .{ .scalar = intAbiSize(int_type.bits, target, use_llvm) };
12481250 },
12491251 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
12501252 .Slice => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) * 2 },
12511253 else => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
12521254 },
1253 .anyframe_type => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1255 .anyframe_type => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
12541256
12551257 .array_type => |array_type| {
12561258 const len = array_type.lenIncludingSentinel();
12571259 if (len == 0) return .{ .scalar = 0 };
1258 switch (try Type.fromInterned(array_type.child).abiSizeAdvanced(mod, strat)) {
1260 switch (try Type.fromInterned(array_type.child).abiSizeAdvanced(pt, strat)) {
12591261 .scalar => |elem_size| return .{ .scalar = len * elem_size },
12601262 .val => switch (strat) {
12611263 .sema, .eager => unreachable,
1262 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1264 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12631265 .ty = .comptime_int_type,
12641266 .storage = .{ .lazy_size = ty.toIntern() },
1265 } }))) },
1267 } })) },
12661268 },
12671269 }
12681270 },
......@@ -1270,71 +1272,71 @@ pub fn abiSizeAdvanced(
12701272 const sub_strat: ResolveStrat = switch (strat) {
12711273 .sema => .sema,
12721274 .eager => .normal,
1273 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1275 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12741276 .ty = .comptime_int_type,
12751277 .storage = .{ .lazy_size = ty.toIntern() },
1276 } }))) },
1278 } })) },
12771279 };
1278 const alignment = switch (try ty.abiAlignmentAdvanced(mod, strat)) {
1280 const alignment = switch (try ty.abiAlignmentAdvanced(pt, strat)) {
12791281 .scalar => |x| x,
1280 .val => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1282 .val => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12811283 .ty = .comptime_int_type,
12821284 .storage = .{ .lazy_size = ty.toIntern() },
1283 } }))) },
1285 } })) },
12841286 };
12851287 const total_bytes = switch (mod.comp.getZigBackend()) {
12861288 else => total_bytes: {
1287 const elem_bits = try Type.fromInterned(vector_type.child).bitSizeAdvanced(mod, sub_strat);
1289 const elem_bits = try Type.fromInterned(vector_type.child).bitSizeAdvanced(pt, sub_strat);
12881290 const total_bits = elem_bits * vector_type.len;
12891291 break :total_bytes (total_bits + 7) / 8;
12901292 },
12911293 .stage2_c => total_bytes: {
1292 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
1294 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
12931295 break :total_bytes elem_bytes * vector_type.len;
12941296 },
12951297 .stage2_x86_64 => total_bytes: {
12961298 if (vector_type.child == .bool_type) break :total_bytes std.math.divCeil(u32, vector_type.len, 8) catch unreachable;
1297 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
1299 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
12981300 break :total_bytes elem_bytes * vector_type.len;
12991301 },
13001302 };
1301 return AbiSizeAdvanced{ .scalar = alignment.forward(total_bytes) };
1303 return .{ .scalar = alignment.forward(total_bytes) };
13021304 },
13031305
1304 .opt_type => return ty.abiSizeAdvancedOptional(mod, strat),
1306 .opt_type => return ty.abiSizeAdvancedOptional(pt, strat),
13051307
13061308 .error_set_type, .inferred_error_set_type => {
13071309 const bits = mod.errorSetBits();
1308 if (bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1309 return AbiSizeAdvanced{ .scalar = intAbiSize(bits, target, use_llvm) };
1310 if (bits == 0) return .{ .scalar = 0 };
1311 return .{ .scalar = intAbiSize(bits, target, use_llvm) };
13101312 },
13111313
13121314 .error_union_type => |error_union_type| {
13131315 const payload_ty = Type.fromInterned(error_union_type.payload_type);
13141316 // This code needs to be kept in sync with the equivalent switch prong
13151317 // in abiAlignmentAdvanced.
1316 const code_size = abiSize(Type.anyerror, mod);
1317 if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1318 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1318 const code_size = Type.anyerror.abiSize(pt);
1319 if (!(payload_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1320 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
13191321 .ty = .comptime_int_type,
13201322 .storage = .{ .lazy_size = ty.toIntern() },
1321 } }))) },
1323 } })) },
13221324 else => |e| return e,
13231325 })) {
13241326 // Same as anyerror.
1325 return AbiSizeAdvanced{ .scalar = code_size };
1327 return .{ .scalar = code_size };
13261328 }
1327 const code_align = abiAlignment(Type.anyerror, mod);
1328 const payload_align = abiAlignment(payload_ty, mod);
1329 const payload_size = switch (try payload_ty.abiSizeAdvanced(mod, strat)) {
1329 const code_align = Type.anyerror.abiAlignment(pt);
1330 const payload_align = payload_ty.abiAlignment(pt);
1331 const payload_size = switch (try payload_ty.abiSizeAdvanced(pt, strat)) {
13301332 .scalar => |elem_size| elem_size,
13311333 .val => switch (strat) {
13321334 .sema => unreachable,
13331335 .eager => unreachable,
1334 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1336 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
13351337 .ty = .comptime_int_type,
13361338 .storage = .{ .lazy_size = ty.toIntern() },
1337 } }))) },
1339 } })) },
13381340 },
13391341 };
13401342
......@@ -1350,7 +1352,7 @@ pub fn abiSizeAdvanced(
13501352 size += code_size;
13511353 size = payload_align.forward(size);
13521354 }
1353 return AbiSizeAdvanced{ .scalar = size };
1355 return .{ .scalar = size };
13541356 },
13551357 .func_type => unreachable, // represents machine code; not a pointer
13561358 .simple_type => |t| switch (t) {
......@@ -1362,34 +1364,31 @@ pub fn abiSizeAdvanced(
13621364 .float_mode,
13631365 .reduce_op,
13641366 .call_modifier,
1365 => return AbiSizeAdvanced{ .scalar = 1 },
1367 => return .{ .scalar = 1 },
13661368
1367 .f16 => return AbiSizeAdvanced{ .scalar = 2 },
1368 .f32 => return AbiSizeAdvanced{ .scalar = 4 },
1369 .f64 => return AbiSizeAdvanced{ .scalar = 8 },
1370 .f128 => return AbiSizeAdvanced{ .scalar = 16 },
1369 .f16 => return .{ .scalar = 2 },
1370 .f32 => return .{ .scalar = 4 },
1371 .f64 => return .{ .scalar = 8 },
1372 .f128 => return .{ .scalar = 16 },
13711373 .f80 => switch (target.c_type_bit_size(.longdouble)) {
1372 80 => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },
1373 else => {
1374 const u80_ty: Type = .{ .ip_index = .u80_type };
1375 return AbiSizeAdvanced{ .scalar = abiSize(u80_ty, mod) };
1376 },
1374 80 => return .{ .scalar = target.c_type_byte_size(.longdouble) },
1375 else => return .{ .scalar = Type.u80.abiSize(pt) },
13771376 },
13781377
13791378 .usize,
13801379 .isize,
1381 => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1382
1383 .c_char => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.char) },
1384 .c_short => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.short) },
1385 .c_ushort => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ushort) },
1386 .c_int => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.int) },
1387 .c_uint => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.uint) },
1388 .c_long => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.long) },
1389 .c_ulong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulong) },
1390 .c_longlong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longlong) },
1391 .c_ulonglong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulonglong) },
1392 .c_longdouble => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },
1380 => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1381
1382 .c_char => return .{ .scalar = target.c_type_byte_size(.char) },
1383 .c_short => return .{ .scalar = target.c_type_byte_size(.short) },
1384 .c_ushort => return .{ .scalar = target.c_type_byte_size(.ushort) },
1385 .c_int => return .{ .scalar = target.c_type_byte_size(.int) },
1386 .c_uint => return .{ .scalar = target.c_type_byte_size(.uint) },
1387 .c_long => return .{ .scalar = target.c_type_byte_size(.long) },
1388 .c_ulong => return .{ .scalar = target.c_type_byte_size(.ulong) },
1389 .c_longlong => return .{ .scalar = target.c_type_byte_size(.longlong) },
1390 .c_ulonglong => return .{ .scalar = target.c_type_byte_size(.ulonglong) },
1391 .c_longdouble => return .{ .scalar = target.c_type_byte_size(.longdouble) },
13931392
13941393 .anyopaque,
13951394 .void,
......@@ -1399,12 +1398,12 @@ pub fn abiSizeAdvanced(
13991398 .null,
14001399 .undefined,
14011400 .enum_literal,
1402 => return AbiSizeAdvanced{ .scalar = 0 },
1401 => return .{ .scalar = 0 },
14031402
14041403 .anyerror, .adhoc_inferred_error_set => {
14051404 const bits = mod.errorSetBits();
1406 if (bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1407 return AbiSizeAdvanced{ .scalar = intAbiSize(bits, target, use_llvm) };
1405 if (bits == 0) return .{ .scalar = 0 };
1406 return .{ .scalar = intAbiSize(bits, target, use_llvm) };
14081407 },
14091408
14101409 .prefetch_options => unreachable, // missing call to resolveTypeFields
......@@ -1418,22 +1417,22 @@ pub fn abiSizeAdvanced(
14181417 .struct_type => {
14191418 const struct_type = ip.loadStructType(ty.toIntern());
14201419 switch (strat) {
1421 .sema => try ty.resolveLayout(mod),
1420 .sema => try ty.resolveLayout(pt),
14221421 .lazy => switch (struct_type.layout) {
14231422 .@"packed" => {
14241423 if (struct_type.backingIntType(ip).* == .none) return .{
1425 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1424 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14261425 .ty = .comptime_int_type,
14271426 .storage = .{ .lazy_size = ty.toIntern() },
1428 } }))),
1427 } })),
14291428 };
14301429 },
14311430 .auto, .@"extern" => {
14321431 if (!struct_type.haveLayout(ip)) return .{
1433 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1432 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14341433 .ty = .comptime_int_type,
14351434 .storage = .{ .lazy_size = ty.toIntern() },
1436 } }))),
1435 } })),
14371436 };
14381437 },
14391438 },
......@@ -1441,7 +1440,7 @@ pub fn abiSizeAdvanced(
14411440 }
14421441 switch (struct_type.layout) {
14431442 .@"packed" => return .{
1444 .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiSize(mod),
1443 .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiSize(pt),
14451444 },
14461445 .auto, .@"extern" => {
14471446 assert(struct_type.haveLayout(ip));
......@@ -1451,25 +1450,25 @@ pub fn abiSizeAdvanced(
14511450 },
14521451 .anon_struct_type => |tuple| {
14531452 switch (strat) {
1454 .sema => try ty.resolveLayout(mod),
1453 .sema => try ty.resolveLayout(pt),
14551454 .lazy, .eager => {},
14561455 }
14571456 const field_count = tuple.types.len;
14581457 if (field_count == 0) {
1459 return AbiSizeAdvanced{ .scalar = 0 };
1458 return .{ .scalar = 0 };
14601459 }
1461 return AbiSizeAdvanced{ .scalar = ty.structFieldOffset(field_count, mod) };
1460 return .{ .scalar = ty.structFieldOffset(field_count, pt) };
14621461 },
14631462
14641463 .union_type => {
14651464 const union_type = ip.loadUnionType(ty.toIntern());
14661465 switch (strat) {
1467 .sema => try ty.resolveLayout(mod),
1466 .sema => try ty.resolveLayout(pt),
14681467 .lazy => if (!union_type.flagsPtr(ip).status.haveLayout()) return .{
1469 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1468 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14701469 .ty = .comptime_int_type,
14711470 .storage = .{ .lazy_size = ty.toIntern() },
1472 } }))),
1471 } })),
14731472 },
14741473 .eager => {},
14751474 }
......@@ -1478,7 +1477,7 @@ pub fn abiSizeAdvanced(
14781477 return .{ .scalar = union_type.size(ip).* };
14791478 },
14801479 .opaque_type => unreachable, // no size available
1481 .enum_type => return .{ .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiSize(mod) },
1480 .enum_type => return .{ .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiSize(pt) },
14821481
14831482 // values, not types
14841483 .undef,
......@@ -1507,36 +1506,37 @@ pub fn abiSizeAdvanced(
15071506
15081507fn abiSizeAdvancedOptional(
15091508 ty: Type,
1510 mod: *Module,
1509 pt: Zcu.PerThread,
15111510 strat: ResolveStratLazy,
15121511) SemaError!AbiSizeAdvanced {
1512 const mod = pt.zcu;
15131513 const child_ty = ty.optionalChild(mod);
15141514
15151515 if (child_ty.isNoReturn(mod)) {
1516 return AbiSizeAdvanced{ .scalar = 0 };
1516 return .{ .scalar = 0 };
15171517 }
15181518
1519 if (!(child_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1520 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1519 if (!(child_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1520 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
15211521 .ty = .comptime_int_type,
15221522 .storage = .{ .lazy_size = ty.toIntern() },
1523 } }))) },
1523 } })) },
15241524 else => |e| return e,
1525 })) return AbiSizeAdvanced{ .scalar = 1 };
1525 })) return .{ .scalar = 1 };
15261526
15271527 if (ty.optionalReprIsPayload(mod)) {
1528 return abiSizeAdvanced(child_ty, mod, strat);
1528 return child_ty.abiSizeAdvanced(pt, strat);
15291529 }
15301530
1531 const payload_size = switch (try child_ty.abiSizeAdvanced(mod, strat)) {
1531 const payload_size = switch (try child_ty.abiSizeAdvanced(pt, strat)) {
15321532 .scalar => |elem_size| elem_size,
15331533 .val => switch (strat) {
15341534 .sema => unreachable,
15351535 .eager => unreachable,
1536 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1536 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
15371537 .ty = .comptime_int_type,
15381538 .storage = .{ .lazy_size = ty.toIntern() },
1539 } }))) },
1539 } })) },
15401540 },
15411541 };
15421542
......@@ -1544,8 +1544,8 @@ fn abiSizeAdvancedOptional(
15441544 // field and a boolean as the second. Since the child type's abi alignment is
15451545 // guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
15461546 // to the child type's ABI alignment.
1547 return AbiSizeAdvanced{
1548 .scalar = (child_ty.abiAlignment(mod).toByteUnits() orelse 0) + payload_size,
1547 return .{
1548 .scalar = (child_ty.abiAlignment(pt).toByteUnits() orelse 0) + payload_size,
15491549 };
15501550}
15511551
......@@ -1675,15 +1675,16 @@ pub fn maxIntAlignment(target: std.Target, use_llvm: bool) u16 {
16751675 };
16761676}
16771677
1678pub fn bitSize(ty: Type, mod: *Module) u64 {
1679 return bitSizeAdvanced(ty, mod, .normal) catch unreachable;
1678pub fn bitSize(ty: Type, pt: Zcu.PerThread) u64 {
1679 return bitSizeAdvanced(ty, pt, .normal) catch unreachable;
16801680}
16811681
16821682pub fn bitSizeAdvanced(
16831683 ty: Type,
1684 mod: *Module,
1684 pt: Zcu.PerThread,
16851685 strat: ResolveStrat,
16861686) SemaError!u64 {
1687 const mod = pt.zcu;
16871688 const target = mod.getTarget();
16881689 const ip = &mod.intern_pool;
16891690
......@@ -1702,22 +1703,22 @@ pub fn bitSizeAdvanced(
17021703 if (len == 0) return 0;
17031704 const elem_ty = Type.fromInterned(array_type.child);
17041705 const elem_size = @max(
1705 (try elem_ty.abiAlignmentAdvanced(mod, strat_lazy)).scalar.toByteUnits() orelse 0,
1706 (try elem_ty.abiSizeAdvanced(mod, strat_lazy)).scalar,
1706 (try elem_ty.abiAlignmentAdvanced(pt, strat_lazy)).scalar.toByteUnits() orelse 0,
1707 (try elem_ty.abiSizeAdvanced(pt, strat_lazy)).scalar,
17071708 );
17081709 if (elem_size == 0) return 0;
1709 const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, strat);
1710 const elem_bit_size = try elem_ty.bitSizeAdvanced(pt, strat);
17101711 return (len - 1) * 8 * elem_size + elem_bit_size;
17111712 },
17121713 .vector_type => |vector_type| {
17131714 const child_ty = Type.fromInterned(vector_type.child);
1714 const elem_bit_size = try bitSizeAdvanced(child_ty, mod, strat);
1715 const elem_bit_size = try child_ty.bitSizeAdvanced(pt, strat);
17151716 return elem_bit_size * vector_type.len;
17161717 },
17171718 .opt_type => {
17181719 // Optionals and error unions are not packed so their bitsize
17191720 // includes padding bits.
1720 return (try abiSizeAdvanced(ty, mod, strat_lazy)).scalar * 8;
1721 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17211722 },
17221723
17231724 .error_set_type, .inferred_error_set_type => return mod.errorSetBits(),
......@@ -1725,7 +1726,7 @@ pub fn bitSizeAdvanced(
17251726 .error_union_type => {
17261727 // Optionals and error unions are not packed so their bitsize
17271728 // includes padding bits.
1728 return (try abiSizeAdvanced(ty, mod, strat_lazy)).scalar * 8;
1729 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17291730 },
17301731 .func_type => unreachable, // represents machine code; not a pointer
17311732 .simple_type => |t| switch (t) {
......@@ -1783,42 +1784,42 @@ pub fn bitSizeAdvanced(
17831784 const struct_type = ip.loadStructType(ty.toIntern());
17841785 const is_packed = struct_type.layout == .@"packed";
17851786 if (strat == .sema) {
1786 try ty.resolveFields(mod);
1787 if (is_packed) try ty.resolveLayout(mod);
1787 try ty.resolveFields(pt);
1788 if (is_packed) try ty.resolveLayout(pt);
17881789 }
17891790 if (is_packed) {
1790 return try Type.fromInterned(struct_type.backingIntType(ip).*).bitSizeAdvanced(mod, strat);
1791 return try Type.fromInterned(struct_type.backingIntType(ip).*).bitSizeAdvanced(pt, strat);
17911792 }
1792 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1793 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17931794 },
17941795
17951796 .anon_struct_type => {
1796 if (strat == .sema) try ty.resolveFields(mod);
1797 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1797 if (strat == .sema) try ty.resolveFields(pt);
1798 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17981799 },
17991800
18001801 .union_type => {
18011802 const union_type = ip.loadUnionType(ty.toIntern());
18021803 const is_packed = ty.containerLayout(mod) == .@"packed";
18031804 if (strat == .sema) {
1804 try ty.resolveFields(mod);
1805 if (is_packed) try ty.resolveLayout(mod);
1805 try ty.resolveFields(pt);
1806 if (is_packed) try ty.resolveLayout(pt);
18061807 }
18071808 if (!is_packed) {
1808 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1809 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
18091810 }
18101811 assert(union_type.flagsPtr(ip).status.haveFieldTypes());
18111812
18121813 var size: u64 = 0;
18131814 for (0..union_type.field_types.len) |field_index| {
18141815 const field_ty = union_type.field_types.get(ip)[field_index];
1815 size = @max(size, try bitSizeAdvanced(Type.fromInterned(field_ty), mod, strat));
1816 size = @max(size, try Type.fromInterned(field_ty).bitSizeAdvanced(pt, strat));
18161817 }
18171818
18181819 return size;
18191820 },
18201821 .opaque_type => unreachable,
1821 .enum_type => return bitSizeAdvanced(Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty), mod, strat),
1822 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).bitSizeAdvanced(pt, strat),
18221823
18231824 // values, not types
18241825 .undef,
......@@ -1870,7 +1871,7 @@ pub fn isSinglePointer(ty: Type, mod: *const Module) bool {
18701871
18711872/// Asserts `ty` is a pointer.
18721873pub fn ptrSize(ty: Type, mod: *const Module) std.builtin.Type.Pointer.Size {
1873 return ptrSizeOrNull(ty, mod).?;
1874 return ty.ptrSizeOrNull(mod).?;
18741875}
18751876
18761877/// Returns `null` if `ty` is not a pointer.
......@@ -2105,29 +2106,28 @@ pub fn unionTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?u32 {
21052106 return mod.unionTagFieldIndex(union_obj, enum_tag);
21062107}
21072108
2108pub fn unionHasAllZeroBitFieldTypes(ty: Type, mod: *Module) bool {
2109 const ip = &mod.intern_pool;
2110 const union_obj = mod.typeToUnion(ty).?;
2109pub fn unionHasAllZeroBitFieldTypes(ty: Type, pt: Zcu.PerThread) bool {
2110 const ip = &pt.zcu.intern_pool;
2111 const union_obj = pt.zcu.typeToUnion(ty).?;
21112112 for (union_obj.field_types.get(ip)) |field_ty| {
2112 if (Type.fromInterned(field_ty).hasRuntimeBits(mod)) return false;
2113 if (Type.fromInterned(field_ty).hasRuntimeBits(pt)) return false;
21132114 }
21142115 return true;
21152116}
21162117
21172118/// Returns the type used for backing storage of this union during comptime operations.
21182119/// Asserts the type is either an extern or packed union.
2119pub fn unionBackingType(ty: Type, mod: *Module) !Type {
2120 return switch (ty.containerLayout(mod)) {
2121 .@"extern" => try mod.arrayType(.{ .len = ty.abiSize(mod), .child = .u8_type }),
2122 .@"packed" => try mod.intType(.unsigned, @intCast(ty.bitSize(mod))),
2120pub fn unionBackingType(ty: Type, pt: Zcu.PerThread) !Type {
2121 return switch (ty.containerLayout(pt.zcu)) {
2122 .@"extern" => try pt.arrayType(.{ .len = ty.abiSize(pt), .child = .u8_type }),
2123 .@"packed" => try pt.intType(.unsigned, @intCast(ty.bitSize(pt))),
21232124 .auto => unreachable,
21242125 };
21252126}
21262127
2127pub fn unionGetLayout(ty: Type, mod: *Module) Module.UnionLayout {
2128 const ip = &mod.intern_pool;
2129 const union_obj = ip.loadUnionType(ty.toIntern());
2130 return mod.getUnionLayout(union_obj);
2128pub fn unionGetLayout(ty: Type, pt: Zcu.PerThread) Module.UnionLayout {
2129 const union_obj = pt.zcu.intern_pool.loadUnionType(ty.toIntern());
2130 return pt.getUnionLayout(union_obj);
21312131}
21322132
21332133pub fn containerLayout(ty: Type, mod: *Module) std.builtin.Type.ContainerLayout {
......@@ -2509,7 +2509,8 @@ pub fn isNumeric(ty: Type, mod: *const Module) bool {
25092509
25102510/// During semantic analysis, instead call `Sema.typeHasOnePossibleValue` which
25112511/// resolves field types rather than asserting they are already resolved.
2512pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
2512pub fn onePossibleValue(starting_type: Type, pt: Zcu.PerThread) !?Value {
2513 const mod = pt.zcu;
25132514 var ty = starting_type;
25142515 const ip = &mod.intern_pool;
25152516 while (true) switch (ty.toIntern()) {
......@@ -2518,7 +2519,7 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
25182519 else => switch (ip.indexToKey(ty.toIntern())) {
25192520 .int_type => |int_type| {
25202521 if (int_type.bits == 0) {
2521 return try mod.intValue(ty, 0);
2522 return try pt.intValue(ty, 0);
25222523 } else {
25232524 return null;
25242525 }
......@@ -2534,21 +2535,21 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
25342535
25352536 inline .array_type, .vector_type => |seq_type, seq_tag| {
25362537 const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
2537 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2538 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25382539 .ty = ty.toIntern(),
25392540 .storage = .{ .elems = &.{} },
2540 } })));
2541 if (try Type.fromInterned(seq_type.child).onePossibleValue(mod)) |opv| {
2542 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2541 } }));
2542 if (try Type.fromInterned(seq_type.child).onePossibleValue(pt)) |opv| {
2543 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25432544 .ty = ty.toIntern(),
25442545 .storage = .{ .repeated_elem = opv.toIntern() },
2545 } })));
2546 } }));
25462547 }
25472548 return null;
25482549 },
25492550 .opt_type => |child| {
25502551 if (child == .noreturn_type) {
2551 return try mod.nullValue(ty);
2552 return try pt.nullValue(ty);
25522553 } else {
25532554 return null;
25542555 }
......@@ -2615,17 +2616,17 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26152616 continue;
26162617 }
26172618 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
2618 if (try field_ty.onePossibleValue(mod)) |field_opv| {
2619 if (try field_ty.onePossibleValue(pt)) |field_opv| {
26192620 field_val.* = field_opv.toIntern();
26202621 } else return null;
26212622 }
26222623
26232624 // In this case the struct has no runtime-known fields and
26242625 // therefore has one possible value.
2625 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2626 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26262627 .ty = ty.toIntern(),
26272628 .storage = .{ .elems = field_vals },
2628 } })));
2629 } }));
26292630 },
26302631
26312632 .anon_struct_type => |tuple| {
......@@ -2637,24 +2638,24 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26372638 // TODO: write something like getCoercedInts to avoid needing to dupe
26382639 const duped_values = try mod.gpa.dupe(InternPool.Index, tuple.values.get(ip));
26392640 defer mod.gpa.free(duped_values);
2640 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2641 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26412642 .ty = ty.toIntern(),
26422643 .storage = .{ .elems = duped_values },
2643 } })));
2644 } }));
26442645 },
26452646
26462647 .union_type => {
26472648 const union_obj = ip.loadUnionType(ty.toIntern());
2648 const tag_val = (try Type.fromInterned(union_obj.enum_tag_ty).onePossibleValue(mod)) orelse
2649 const tag_val = (try Type.fromInterned(union_obj.enum_tag_ty).onePossibleValue(pt)) orelse
26492650 return null;
26502651 if (union_obj.field_types.len == 0) {
2651 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
2652 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
26522653 return Value.fromInterned(only);
26532654 }
26542655 const only_field_ty = union_obj.field_types.get(ip)[0];
2655 const val_val = (try Type.fromInterned(only_field_ty).onePossibleValue(mod)) orelse
2656 const val_val = (try Type.fromInterned(only_field_ty).onePossibleValue(pt)) orelse
26562657 return null;
2657 const only = try mod.intern(.{ .un = .{
2658 const only = try pt.intern(.{ .un = .{
26582659 .ty = ty.toIntern(),
26592660 .tag = tag_val.toIntern(),
26602661 .val = val_val.toIntern(),
......@@ -2668,8 +2669,8 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26682669 .nonexhaustive => {
26692670 if (enum_type.tag_ty == .comptime_int_type) return null;
26702671
2671 if (try Type.fromInterned(enum_type.tag_ty).onePossibleValue(mod)) |int_opv| {
2672 const only = try mod.intern(.{ .enum_tag = .{
2672 if (try Type.fromInterned(enum_type.tag_ty).onePossibleValue(pt)) |int_opv| {
2673 const only = try pt.intern(.{ .enum_tag = .{
26732674 .ty = ty.toIntern(),
26742675 .int = int_opv.toIntern(),
26752676 } });
......@@ -2679,18 +2680,18 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26792680 return null;
26802681 },
26812682 .auto, .explicit => {
2682 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(mod)) return null;
2683 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(pt)) return null;
26832684
26842685 switch (enum_type.names.len) {
26852686 0 => {
2686 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
2687 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
26872688 return Value.fromInterned(only);
26882689 },
26892690 1 => {
26902691 if (enum_type.values.len == 0) {
2691 const only = try mod.intern(.{ .enum_tag = .{
2692 const only = try pt.intern(.{ .enum_tag = .{
26922693 .ty = ty.toIntern(),
2693 .int = try mod.intern(.{ .int = .{
2694 .int = try pt.intern(.{ .int = .{
26942695 .ty = enum_type.tag_ty,
26952696 .storage = .{ .u64 = 0 },
26962697 } }),
......@@ -2733,13 +2734,14 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
27332734
27342735/// During semantic analysis, instead call `Sema.typeRequiresComptime` which
27352736/// resolves field types rather than asserting they are already resolved.
2736pub fn comptimeOnly(ty: Type, mod: *Module) bool {
2737 return ty.comptimeOnlyAdvanced(mod, .normal) catch unreachable;
2737pub fn comptimeOnly(ty: Type, pt: Zcu.PerThread) bool {
2738 return ty.comptimeOnlyAdvanced(pt, .normal) catch unreachable;
27382739}
27392740
27402741/// `generic_poison` will return false.
27412742/// May return false negatives when structs and unions are having their field types resolved.
2742pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaError!bool {
2743pub fn comptimeOnlyAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) SemaError!bool {
2744 const mod = pt.zcu;
27432745 const ip = &mod.intern_pool;
27442746 return switch (ty.toIntern()) {
27452747 .empty_struct_type => false,
......@@ -2749,19 +2751,19 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
27492751 .ptr_type => |ptr_type| {
27502752 const child_ty = Type.fromInterned(ptr_type.child);
27512753 switch (child_ty.zigTypeTag(mod)) {
2752 .Fn => return !try child_ty.fnHasRuntimeBitsAdvanced(mod, strat),
2754 .Fn => return !try child_ty.fnHasRuntimeBitsAdvanced(pt, strat),
27532755 .Opaque => return false,
2754 else => return child_ty.comptimeOnlyAdvanced(mod, strat),
2756 else => return child_ty.comptimeOnlyAdvanced(pt, strat),
27552757 }
27562758 },
27572759 .anyframe_type => |child| {
27582760 if (child == .none) return false;
2759 return Type.fromInterned(child).comptimeOnlyAdvanced(mod, strat);
2761 return Type.fromInterned(child).comptimeOnlyAdvanced(pt, strat);
27602762 },
2761 .array_type => |array_type| return Type.fromInterned(array_type.child).comptimeOnlyAdvanced(mod, strat),
2762 .vector_type => |vector_type| return Type.fromInterned(vector_type.child).comptimeOnlyAdvanced(mod, strat),
2763 .opt_type => |child| return Type.fromInterned(child).comptimeOnlyAdvanced(mod, strat),
2764 .error_union_type => |error_union_type| return Type.fromInterned(error_union_type.payload_type).comptimeOnlyAdvanced(mod, strat),
2763 .array_type => |array_type| return Type.fromInterned(array_type.child).comptimeOnlyAdvanced(pt, strat),
2764 .vector_type => |vector_type| return Type.fromInterned(vector_type.child).comptimeOnlyAdvanced(pt, strat),
2765 .opt_type => |child| return Type.fromInterned(child).comptimeOnlyAdvanced(pt, strat),
2766 .error_union_type => |error_union_type| return Type.fromInterned(error_union_type.payload_type).comptimeOnlyAdvanced(pt, strat),
27652767
27662768 .error_set_type,
27672769 .inferred_error_set_type,
......@@ -2836,13 +2838,13 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28362838 struct_type.flagsPtr(ip).requires_comptime = .wip;
28372839 errdefer struct_type.flagsPtr(ip).requires_comptime = .unknown;
28382840
2839 try ty.resolveFields(mod);
2841 try ty.resolveFields(pt);
28402842
28412843 for (0..struct_type.field_types.len) |i_usize| {
28422844 const i: u32 = @intCast(i_usize);
28432845 if (struct_type.fieldIsComptime(ip, i)) continue;
28442846 const field_ty = struct_type.field_types.get(ip)[i];
2845 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) {
2847 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) {
28462848 // Note that this does not cause the layout to
28472849 // be considered resolved. Comptime-only types
28482850 // still maintain a layout of their
......@@ -2861,7 +2863,7 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28612863 .anon_struct_type => |tuple| {
28622864 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
28632865 const have_comptime_val = val != .none;
2864 if (!have_comptime_val and try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) return true;
2866 if (!have_comptime_val and try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) return true;
28652867 }
28662868 return false;
28672869 },
......@@ -2880,11 +2882,11 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28802882 union_type.flagsPtr(ip).requires_comptime = .wip;
28812883 errdefer union_type.flagsPtr(ip).requires_comptime = .unknown;
28822884
2883 try ty.resolveFields(mod);
2885 try ty.resolveFields(pt);
28842886
28852887 for (0..union_type.field_types.len) |field_idx| {
28862888 const field_ty = union_type.field_types.get(ip)[field_idx];
2887 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) {
2889 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) {
28882890 union_type.flagsPtr(ip).requires_comptime = .yes;
28892891 return true;
28902892 }
......@@ -2898,7 +2900,7 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28982900
28992901 .opaque_type => false,
29002902
2901 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).comptimeOnlyAdvanced(mod, strat),
2903 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).comptimeOnlyAdvanced(pt, strat),
29022904
29032905 // values, not types
29042906 .undef,
......@@ -2930,10 +2932,10 @@ pub fn isVector(ty: Type, mod: *const Module) bool {
29302932}
29312933
29322934/// Returns 0 if not a vector, otherwise returns @bitSizeOf(Element) * vector_len.
2933pub fn totalVectorBits(ty: Type, zcu: *Zcu) u64 {
2934 if (!ty.isVector(zcu)) return 0;
2935 const v = zcu.intern_pool.indexToKey(ty.toIntern()).vector_type;
2936 return v.len * Type.fromInterned(v.child).bitSize(zcu);
2935pub fn totalVectorBits(ty: Type, pt: Zcu.PerThread) u64 {
2936 if (!ty.isVector(pt.zcu)) return 0;
2937 const v = pt.zcu.intern_pool.indexToKey(ty.toIntern()).vector_type;
2938 return v.len * Type.fromInterned(v.child).bitSize(pt);
29372939}
29382940
29392941pub fn isArrayOrVector(ty: Type, mod: *const Module) bool {
......@@ -3013,23 +3015,25 @@ pub fn getNamespace(ty: Type, zcu: *Zcu) ?InternPool.OptionalNamespaceIndex {
30133015}
30143016
30153017// Works for vectors and vectors of integers.
3016pub fn minInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
3017 const scalar = try minIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
3018 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
3018pub fn minInt(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3019 const mod = pt.zcu;
3020 const scalar = try minIntScalar(ty.scalarType(mod), pt, dest_ty.scalarType(mod));
3021 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
30193022 .ty = dest_ty.toIntern(),
30203023 .storage = .{ .repeated_elem = scalar.toIntern() },
3021 } }))) else scalar;
3024 } })) else scalar;
30223025}
30233026
30243027/// Asserts that the type is an integer.
3025pub fn minIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
3028pub fn minIntScalar(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3029 const mod = pt.zcu;
30263030 const info = ty.intInfo(mod);
3027 if (info.signedness == .unsigned) return mod.intValue(dest_ty, 0);
3028 if (info.bits == 0) return mod.intValue(dest_ty, -1);
3031 if (info.signedness == .unsigned) return pt.intValue(dest_ty, 0);
3032 if (info.bits == 0) return pt.intValue(dest_ty, -1);
30293033
30303034 if (std.math.cast(u6, info.bits - 1)) |shift| {
30313035 const n = @as(i64, std.math.minInt(i64)) >> (63 - shift);
3032 return mod.intValue(dest_ty, n);
3036 return pt.intValue(dest_ty, n);
30333037 }
30343038
30353039 var res = try std.math.big.int.Managed.init(mod.gpa);
......@@ -3037,31 +3041,32 @@ pub fn minIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
30373041
30383042 try res.setTwosCompIntLimit(.min, info.signedness, info.bits);
30393043
3040 return mod.intValue_big(dest_ty, res.toConst());
3044 return pt.intValue_big(dest_ty, res.toConst());
30413045}
30423046
30433047// Works for vectors and vectors of integers.
30443048/// The returned Value will have type dest_ty.
3045pub fn maxInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
3046 const scalar = try maxIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
3047 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
3049pub fn maxInt(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3050 const mod = pt.zcu;
3051 const scalar = try maxIntScalar(ty.scalarType(mod), pt, dest_ty.scalarType(mod));
3052 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
30483053 .ty = dest_ty.toIntern(),
30493054 .storage = .{ .repeated_elem = scalar.toIntern() },
3050 } }))) else scalar;
3055 } })) else scalar;
30513056}
30523057
30533058/// The returned Value will have type dest_ty.
3054pub fn maxIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
3055 const info = ty.intInfo(mod);
3059pub fn maxIntScalar(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3060 const info = ty.intInfo(pt.zcu);
30563061
30573062 switch (info.bits) {
30583063 0 => return switch (info.signedness) {
3059 .signed => try mod.intValue(dest_ty, -1),
3060 .unsigned => try mod.intValue(dest_ty, 0),
3064 .signed => try pt.intValue(dest_ty, -1),
3065 .unsigned => try pt.intValue(dest_ty, 0),
30613066 },
30623067 1 => return switch (info.signedness) {
3063 .signed => try mod.intValue(dest_ty, 0),
3064 .unsigned => try mod.intValue(dest_ty, 1),
3068 .signed => try pt.intValue(dest_ty, 0),
3069 .unsigned => try pt.intValue(dest_ty, 1),
30653070 },
30663071 else => {},
30673072 }
......@@ -3069,20 +3074,20 @@ pub fn maxIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
30693074 if (std.math.cast(u6, info.bits - 1)) |shift| switch (info.signedness) {
30703075 .signed => {
30713076 const n = @as(i64, std.math.maxInt(i64)) >> (63 - shift);
3072 return mod.intValue(dest_ty, n);
3077 return pt.intValue(dest_ty, n);
30733078 },
30743079 .unsigned => {
30753080 const n = @as(u64, std.math.maxInt(u64)) >> (63 - shift);
3076 return mod.intValue(dest_ty, n);
3081 return pt.intValue(dest_ty, n);
30773082 },
30783083 };
30793084
3080 var res = try std.math.big.int.Managed.init(mod.gpa);
3085 var res = try std.math.big.int.Managed.init(pt.zcu.gpa);
30813086 defer res.deinit();
30823087
30833088 try res.setTwosCompIntLimit(.max, info.signedness, info.bits);
30843089
3085 return mod.intValue_big(dest_ty, res.toConst());
3090 return pt.intValue_big(dest_ty, res.toConst());
30863091}
30873092
30883093/// Asserts the type is an enum or a union.
......@@ -3188,26 +3193,26 @@ pub fn structFieldType(ty: Type, index: usize, mod: *Module) Type {
31883193 };
31893194}
31903195
3191pub fn structFieldAlign(ty: Type, index: usize, zcu: *Zcu) Alignment {
3192 return ty.structFieldAlignAdvanced(index, zcu, .normal) catch unreachable;
3196pub fn structFieldAlign(ty: Type, index: usize, pt: Zcu.PerThread) Alignment {
3197 return ty.structFieldAlignAdvanced(index, pt, .normal) catch unreachable;
31933198}
31943199
3195pub fn structFieldAlignAdvanced(ty: Type, index: usize, zcu: *Zcu, strat: ResolveStrat) !Alignment {
3196 const ip = &zcu.intern_pool;
3200pub fn structFieldAlignAdvanced(ty: Type, index: usize, pt: Zcu.PerThread, strat: ResolveStrat) !Alignment {
3201 const ip = &pt.zcu.intern_pool;
31973202 switch (ip.indexToKey(ty.toIntern())) {
31983203 .struct_type => {
31993204 const struct_type = ip.loadStructType(ty.toIntern());
32003205 assert(struct_type.layout != .@"packed");
32013206 const explicit_align = struct_type.fieldAlign(ip, index);
32023207 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[index]);
3203 return zcu.structFieldAlignmentAdvanced(explicit_align, field_ty, struct_type.layout, strat);
3208 return pt.structFieldAlignmentAdvanced(explicit_align, field_ty, struct_type.layout, strat);
32043209 },
32053210 .anon_struct_type => |anon_struct| {
3206 return (try Type.fromInterned(anon_struct.types.get(ip)[index]).abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
3211 return (try Type.fromInterned(anon_struct.types.get(ip)[index]).abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
32073212 },
32083213 .union_type => {
32093214 const union_obj = ip.loadUnionType(ty.toIntern());
3210 return zcu.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(index), strat);
3215 return pt.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(index), strat);
32113216 },
32123217 else => unreachable,
32133218 }
......@@ -3233,7 +3238,8 @@ pub fn structFieldDefaultValue(ty: Type, index: usize, mod: *Module) Value {
32333238 }
32343239}
32353240
3236pub fn structFieldValueComptime(ty: Type, mod: *Module, index: usize) !?Value {
3241pub fn structFieldValueComptime(ty: Type, pt: Zcu.PerThread, index: usize) !?Value {
3242 const mod = pt.zcu;
32373243 const ip = &mod.intern_pool;
32383244 switch (ip.indexToKey(ty.toIntern())) {
32393245 .struct_type => {
......@@ -3242,13 +3248,13 @@ pub fn structFieldValueComptime(ty: Type, mod: *Module, index: usize) !?Value {
32423248 assert(struct_type.haveFieldInits(ip));
32433249 return Value.fromInterned(struct_type.field_inits.get(ip)[index]);
32443250 } else {
3245 return Type.fromInterned(struct_type.field_types.get(ip)[index]).onePossibleValue(mod);
3251 return Type.fromInterned(struct_type.field_types.get(ip)[index]).onePossibleValue(pt);
32463252 }
32473253 },
32483254 .anon_struct_type => |tuple| {
32493255 const val = tuple.values.get(ip)[index];
32503256 if (val == .none) {
3251 return Type.fromInterned(tuple.types.get(ip)[index]).onePossibleValue(mod);
3257 return Type.fromInterned(tuple.types.get(ip)[index]).onePossibleValue(pt);
32523258 } else {
32533259 return Value.fromInterned(val);
32543260 }
......@@ -3272,7 +3278,8 @@ pub const FieldOffset = struct {
32723278};
32733279
32743280/// Supports structs and unions.
3275pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
3281pub fn structFieldOffset(ty: Type, index: usize, pt: Zcu.PerThread) u64 {
3282 const mod = pt.zcu;
32763283 const ip = &mod.intern_pool;
32773284 switch (ip.indexToKey(ty.toIntern())) {
32783285 .struct_type => {
......@@ -3287,17 +3294,17 @@ pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
32873294 var big_align: Alignment = .none;
32883295
32893296 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
3290 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) {
3297 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) {
32913298 // comptime field
32923299 if (i == index) return offset;
32933300 continue;
32943301 }
32953302
3296 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
3303 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
32973304 big_align = big_align.max(field_align);
32983305 offset = field_align.forward(offset);
32993306 if (i == index) return offset;
3300 offset += Type.fromInterned(field_ty).abiSize(mod);
3307 offset += Type.fromInterned(field_ty).abiSize(pt);
33013308 }
33023309 offset = big_align.max(.@"1").forward(offset);
33033310 return offset;
......@@ -3307,7 +3314,7 @@ pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
33073314 const union_type = ip.loadUnionType(ty.toIntern());
33083315 if (!union_type.hasTag(ip))
33093316 return 0;
3310 const layout = mod.getUnionLayout(union_type);
3317 const layout = pt.getUnionLayout(union_type);
33113318 if (layout.tag_align.compare(.gte, layout.payload_align)) {
33123319 // {Tag, Payload}
33133320 return layout.payload_align.forward(layout.tag_size);
......@@ -3421,12 +3428,13 @@ pub fn optEuBaseType(ty: Type, mod: *Module) Type {
34213428 };
34223429}
34233430
3424pub fn toUnsigned(ty: Type, mod: *Module) !Type {
3431pub fn toUnsigned(ty: Type, pt: Zcu.PerThread) !Type {
3432 const mod = pt.zcu;
34253433 return switch (ty.zigTypeTag(mod)) {
3426 .Int => mod.intType(.unsigned, ty.intInfo(mod).bits),
3427 .Vector => try mod.vectorType(.{
3434 .Int => pt.intType(.unsigned, ty.intInfo(mod).bits),
3435 .Vector => try pt.vectorType(.{
34283436 .len = ty.vectorLen(mod),
3429 .child = (try ty.childType(mod).toUnsigned(mod)).toIntern(),
3437 .child = (try ty.childType(mod).toUnsigned(pt)).toIntern(),
34303438 }),
34313439 else => unreachable,
34323440 };
......@@ -3492,7 +3500,7 @@ pub fn arrayBase(ty: Type, zcu: *const Zcu) struct { Type, u64 } {
34923500 return .{ cur_ty, cur_len };
34933501}
34943502
3495pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx: u32, zcu: *Zcu) union(enum) {
3503pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx: u32, pt: Zcu.PerThread) union(enum) {
34963504 /// The result is a bit-pointer with the same value and a new packed offset.
34973505 bit_ptr: InternPool.Key.PtrType.PackedOffset,
34983506 /// The result is a standard pointer.
......@@ -3505,6 +3513,7 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35053513} {
35063514 comptime assert(Type.packed_struct_layout_version == 2);
35073515
3516 const zcu = pt.zcu;
35083517 const parent_ptr_info = parent_ptr_ty.ptrInfo(zcu);
35093518 const field_ty = struct_ty.structFieldType(field_idx, zcu);
35103519
......@@ -3515,7 +3524,7 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35153524 if (i == field_idx) {
35163525 bit_offset = running_bits;
35173526 }
3518 running_bits += @intCast(f_ty.bitSize(zcu));
3527 running_bits += @intCast(f_ty.bitSize(pt));
35193528 }
35203529
35213530 const res_host_size: u16, const res_bit_offset: u16 = if (parent_ptr_info.packed_offset.host_size != 0)
......@@ -3532,9 +3541,9 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35323541 // targets before adding the necessary complications to this code. This will not
35333542 // cause miscompilations; it only means the field pointer uses bit masking when it
35343543 // might not be strictly necessary.
3535 if (res_bit_offset % 8 == 0 and field_ty.bitSize(zcu) == field_ty.abiSize(zcu) * 8 and zcu.getTarget().cpu.arch.endian() == .little) {
3544 if (res_bit_offset % 8 == 0 and field_ty.bitSize(pt) == field_ty.abiSize(pt) * 8 and zcu.getTarget().cpu.arch.endian() == .little) {
35363545 const byte_offset = res_bit_offset / 8;
3537 const new_align = Alignment.fromLog2Units(@ctz(byte_offset | parent_ptr_ty.ptrAlignment(zcu).toByteUnits().?));
3546 const new_align = Alignment.fromLog2Units(@ctz(byte_offset | parent_ptr_ty.ptrAlignment(pt).toByteUnits().?));
35383547 return .{ .byte_ptr = .{
35393548 .offset = byte_offset,
35403549 .alignment = new_align,
......@@ -3547,34 +3556,35 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35473556 } };
35483557}
35493558
3550pub fn resolveLayout(ty: Type, zcu: *Zcu) SemaError!void {
3559pub fn resolveLayout(ty: Type, pt: Zcu.PerThread) SemaError!void {
3560 const zcu = pt.zcu;
35513561 const ip = &zcu.intern_pool;
35523562 switch (ip.indexToKey(ty.toIntern())) {
3553 .simple_type => |simple_type| return resolveSimpleType(simple_type, zcu),
3563 .simple_type => |simple_type| return resolveSimpleType(simple_type, pt),
35543564 else => {},
35553565 }
35563566 switch (ty.zigTypeTag(zcu)) {
35573567 .Struct => switch (ip.indexToKey(ty.toIntern())) {
35583568 .anon_struct_type => |anon_struct_type| for (0..anon_struct_type.types.len) |i| {
35593569 const field_ty = Type.fromInterned(anon_struct_type.types.get(ip)[i]);
3560 try field_ty.resolveLayout(zcu);
3570 try field_ty.resolveLayout(pt);
35613571 },
3562 .struct_type => return ty.resolveStructInner(zcu, .layout),
3572 .struct_type => return ty.resolveStructInner(pt, .layout),
35633573 else => unreachable,
35643574 },
3565 .Union => return ty.resolveUnionInner(zcu, .layout),
3575 .Union => return ty.resolveUnionInner(pt, .layout),
35663576 .Array => {
35673577 if (ty.arrayLenIncludingSentinel(zcu) == 0) return;
35683578 const elem_ty = ty.childType(zcu);
3569 return elem_ty.resolveLayout(zcu);
3579 return elem_ty.resolveLayout(pt);
35703580 },
35713581 .Optional => {
35723582 const payload_ty = ty.optionalChild(zcu);
3573 return payload_ty.resolveLayout(zcu);
3583 return payload_ty.resolveLayout(pt);
35743584 },
35753585 .ErrorUnion => {
35763586 const payload_ty = ty.errorUnionPayload(zcu);
3577 return payload_ty.resolveLayout(zcu);
3587 return payload_ty.resolveLayout(pt);
35783588 },
35793589 .Fn => {
35803590 const info = zcu.typeToFunc(ty).?;
......@@ -3585,16 +3595,16 @@ pub fn resolveLayout(ty: Type, zcu: *Zcu) SemaError!void {
35853595 }
35863596 for (0..info.param_types.len) |i| {
35873597 const param_ty = info.param_types.get(ip)[i];
3588 try Type.fromInterned(param_ty).resolveLayout(zcu);
3598 try Type.fromInterned(param_ty).resolveLayout(pt);
35893599 }
3590 try Type.fromInterned(info.return_type).resolveLayout(zcu);
3600 try Type.fromInterned(info.return_type).resolveLayout(pt);
35913601 },
35923602 else => {},
35933603 }
35943604}
35953605
3596pub fn resolveFields(ty: Type, zcu: *Zcu) SemaError!void {
3597 const ip = &zcu.intern_pool;
3606pub fn resolveFields(ty: Type, pt: Zcu.PerThread) SemaError!void {
3607 const ip = &pt.zcu.intern_pool;
35983608 const ty_ip = ty.toIntern();
35993609
36003610 switch (ty_ip) {
......@@ -3680,22 +3690,23 @@ pub fn resolveFields(ty: Type, zcu: *Zcu) SemaError!void {
36803690 .type_struct,
36813691 .type_struct_packed,
36823692 .type_struct_packed_inits,
3683 => return ty.resolveStructInner(zcu, .fields),
3693 => return ty.resolveStructInner(pt, .fields),
36843694
3685 .type_union => return ty.resolveUnionInner(zcu, .fields),
3695 .type_union => return ty.resolveUnionInner(pt, .fields),
36863696
3687 .simple_type => return resolveSimpleType(ip.indexToKey(ty_ip).simple_type, zcu),
3697 .simple_type => return resolveSimpleType(ip.indexToKey(ty_ip).simple_type, pt),
36883698
36893699 else => {},
36903700 },
36913701 }
36923702}
36933703
3694pub fn resolveFully(ty: Type, zcu: *Zcu) SemaError!void {
3704pub fn resolveFully(ty: Type, pt: Zcu.PerThread) SemaError!void {
3705 const zcu = pt.zcu;
36953706 const ip = &zcu.intern_pool;
36963707
36973708 switch (ip.indexToKey(ty.toIntern())) {
3698 .simple_type => |simple_type| return resolveSimpleType(simple_type, zcu),
3709 .simple_type => |simple_type| return resolveSimpleType(simple_type, pt),
36993710 else => {},
37003711 }
37013712
......@@ -3719,52 +3730,53 @@ pub fn resolveFully(ty: Type, zcu: *Zcu) SemaError!void {
37193730 .EnumLiteral,
37203731 => {},
37213732
3722 .Pointer => return ty.childType(zcu).resolveFully(zcu),
3723 .Array => return ty.childType(zcu).resolveFully(zcu),
3724 .Optional => return ty.optionalChild(zcu).resolveFully(zcu),
3725 .ErrorUnion => return ty.errorUnionPayload(zcu).resolveFully(zcu),
3733 .Pointer => return ty.childType(zcu).resolveFully(pt),
3734 .Array => return ty.childType(zcu).resolveFully(pt),
3735 .Optional => return ty.optionalChild(zcu).resolveFully(pt),
3736 .ErrorUnion => return ty.errorUnionPayload(zcu).resolveFully(pt),
37263737 .Fn => {
37273738 const info = zcu.typeToFunc(ty).?;
37283739 if (info.is_generic) return;
37293740 for (0..info.param_types.len) |i| {
37303741 const param_ty = info.param_types.get(ip)[i];
3731 try Type.fromInterned(param_ty).resolveFully(zcu);
3742 try Type.fromInterned(param_ty).resolveFully(pt);
37323743 }
3733 try Type.fromInterned(info.return_type).resolveFully(zcu);
3744 try Type.fromInterned(info.return_type).resolveFully(pt);
37343745 },
37353746
37363747 .Struct => switch (ip.indexToKey(ty.toIntern())) {
37373748 .anon_struct_type => |anon_struct_type| for (0..anon_struct_type.types.len) |i| {
37383749 const field_ty = Type.fromInterned(anon_struct_type.types.get(ip)[i]);
3739 try field_ty.resolveFully(zcu);
3750 try field_ty.resolveFully(pt);
37403751 },
3741 .struct_type => return ty.resolveStructInner(zcu, .full),
3752 .struct_type => return ty.resolveStructInner(pt, .full),
37423753 else => unreachable,
37433754 },
3744 .Union => return ty.resolveUnionInner(zcu, .full),
3755 .Union => return ty.resolveUnionInner(pt, .full),
37453756 }
37463757}
37473758
3748pub fn resolveStructFieldInits(ty: Type, zcu: *Zcu) SemaError!void {
3759pub fn resolveStructFieldInits(ty: Type, pt: Zcu.PerThread) SemaError!void {
37493760 // TODO: stop calling this for tuples!
3750 _ = zcu.typeToStruct(ty) orelse return;
3751 return ty.resolveStructInner(zcu, .inits);
3761 _ = pt.zcu.typeToStruct(ty) orelse return;
3762 return ty.resolveStructInner(pt, .inits);
37523763}
37533764
3754pub fn resolveStructAlignment(ty: Type, zcu: *Zcu) SemaError!void {
3755 return ty.resolveStructInner(zcu, .alignment);
3765pub fn resolveStructAlignment(ty: Type, pt: Zcu.PerThread) SemaError!void {
3766 return ty.resolveStructInner(pt, .alignment);
37563767}
37573768
3758pub fn resolveUnionAlignment(ty: Type, zcu: *Zcu) SemaError!void {
3759 return ty.resolveUnionInner(zcu, .alignment);
3769pub fn resolveUnionAlignment(ty: Type, pt: Zcu.PerThread) SemaError!void {
3770 return ty.resolveUnionInner(pt, .alignment);
37603771}
37613772
37623773/// `ty` must be a struct.
37633774fn resolveStructInner(
37643775 ty: Type,
3765 zcu: *Zcu,
3776 pt: Zcu.PerThread,
37663777 resolution: enum { fields, inits, alignment, layout, full },
37673778) SemaError!void {
3779 const zcu = pt.zcu;
37683780 const gpa = zcu.gpa;
37693781
37703782 const struct_obj = zcu.typeToStruct(ty).?;
......@@ -3777,7 +3789,7 @@ fn resolveStructInner(
37773789 defer comptime_err_ret_trace.deinit();
37783790
37793791 var sema: Sema = .{
3780 .mod = zcu,
3792 .pt = pt,
37813793 .gpa = gpa,
37823794 .arena = analysis_arena.allocator(),
37833795 .code = undefined, // This ZIR will not be used.
......@@ -3804,9 +3816,10 @@ fn resolveStructInner(
38043816/// `ty` must be a union.
38053817fn resolveUnionInner(
38063818 ty: Type,
3807 zcu: *Zcu,
3819 pt: Zcu.PerThread,
38083820 resolution: enum { fields, alignment, layout, full },
38093821) SemaError!void {
3822 const zcu = pt.zcu;
38103823 const gpa = zcu.gpa;
38113824
38123825 const union_obj = zcu.typeToUnion(ty).?;
......@@ -3819,7 +3832,7 @@ fn resolveUnionInner(
38193832 defer comptime_err_ret_trace.deinit();
38203833
38213834 var sema: Sema = .{
3822 .mod = zcu,
3835 .pt = pt,
38233836 .gpa = gpa,
38243837 .arena = analysis_arena.allocator(),
38253838 .code = undefined, // This ZIR will not be used.
......@@ -3845,7 +3858,7 @@ fn resolveUnionInner(
38453858/// Fully resolves a simple type. This is usually a nop, but for builtin types with
38463859/// special InternPool indices (such as std.builtin.Type) it will analyze and fully
38473860/// resolve the type.
3848fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Error!void {
3861fn resolveSimpleType(simple_type: InternPool.SimpleType, pt: Zcu.PerThread) Allocator.Error!void {
38493862 const builtin_type_name: []const u8 = switch (simple_type) {
38503863 .atomic_order => "AtomicOrder",
38513864 .atomic_rmw_op => "AtomicRmwOp",
......@@ -3861,7 +3874,7 @@ fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Er
38613874 else => return,
38623875 };
38633876 // This will fully resolve the type.
3864 _ = try zcu.getBuiltinType(builtin_type_name);
3877 _ = try pt.getBuiltinType(builtin_type_name);
38653878}
38663879
38673880/// Returns the type of a pointer to an element.
......@@ -3874,7 +3887,8 @@ fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Er
38743887/// Handles const-ness and address spaces in particular.
38753888/// This code is duplicated in `Sema.analyzePtrArithmetic`.
38763889/// May perform type resolution and return a transitive `error.AnalysisFail`.
3877pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
3890pub fn elemPtrType(ptr_ty: Type, offset: ?usize, pt: Zcu.PerThread) !Type {
3891 const zcu = pt.zcu;
38783892 const ptr_info = ptr_ty.ptrInfo(zcu);
38793893 const elem_ty = ptr_ty.elemType2(zcu);
38803894 const is_allowzero = ptr_info.flags.is_allowzero and (offset orelse 0) == 0;
......@@ -3887,14 +3901,14 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
38873901 alignment: Alignment = .none,
38883902 vector_index: VI = .none,
38893903 } = if (parent_ty.isVector(zcu) and ptr_info.flags.size == .One) blk: {
3890 const elem_bits = elem_ty.bitSize(zcu);
3904 const elem_bits = elem_ty.bitSize(pt);
38913905 if (elem_bits == 0) break :blk .{};
38923906 const is_packed = elem_bits < 8 or !std.math.isPowerOfTwo(elem_bits);
38933907 if (!is_packed) break :blk .{};
38943908
38953909 break :blk .{
38963910 .host_size = @intCast(parent_ty.arrayLen(zcu)),
3897 .alignment = parent_ty.abiAlignment(zcu),
3911 .alignment = parent_ty.abiAlignment(pt),
38983912 .vector_index = if (offset) |some| @enumFromInt(some) else .runtime,
38993913 };
39003914 } else .{};
......@@ -3908,7 +3922,7 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
39083922 }
39093923 // If the addend is not a comptime-known value we can still count on
39103924 // it being a multiple of the type size.
3911 const elem_size = (try elem_ty.abiSizeAdvanced(zcu, .sema)).scalar;
3925 const elem_size = (try elem_ty.abiSizeAdvanced(pt, .sema)).scalar;
39123926 const addend = if (offset) |off| elem_size * off else elem_size;
39133927
39143928 // The resulting pointer is aligned to the lcd between the offset (an
......@@ -3921,7 +3935,7 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
39213935 assert(new_align != .none);
39223936 break :a new_align;
39233937 };
3924 return zcu.ptrTypeSema(.{
3938 return pt.ptrTypeSema(.{
39253939 .child = elem_ty.toIntern(),
39263940 .flags = .{
39273941 .alignment = alignment,
......@@ -3944,6 +3958,7 @@ pub const @"u16": Type = .{ .ip_index = .u16_type };
39443958pub const @"u29": Type = .{ .ip_index = .u29_type };
39453959pub const @"u32": Type = .{ .ip_index = .u32_type };
39463960pub const @"u64": Type = .{ .ip_index = .u64_type };
3961pub const @"u80": Type = .{ .ip_index = .u80_type };
39473962pub const @"u128": Type = .{ .ip_index = .u128_type };
39483963
39493964pub const @"i8": Type = .{ .ip_index = .i8_type };
src/Value.zig+1163-1084
......@@ -40,10 +40,10 @@ pub fn fmtDebug(val: Value) std.fmt.Formatter(dump) {
4040 return .{ .data = val };
4141}
4242
43pub fn fmtValue(val: Value, mod: *Module, opt_sema: ?*Sema) std.fmt.Formatter(print_value.format) {
43pub fn fmtValue(val: Value, pt: Zcu.PerThread, opt_sema: ?*Sema) std.fmt.Formatter(print_value.format) {
4444 return .{ .data = .{
4545 .val = val,
46 .mod = mod,
46 .pt = pt,
4747 .opt_sema = opt_sema,
4848 .depth = 3,
4949 } };
......@@ -55,15 +55,16 @@ pub fn fmtValueFull(ctx: print_value.FormatContext) std.fmt.Formatter(print_valu
5555
5656/// Converts `val` to a null-terminated string stored in the InternPool.
5757/// Asserts `val` is an array of `u8`
58pub fn toIpString(val: Value, ty: Type, mod: *Module) !InternPool.NullTerminatedString {
58pub fn toIpString(val: Value, ty: Type, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
59 const mod = pt.zcu;
5960 assert(ty.zigTypeTag(mod) == .Array);
6061 assert(ty.childType(mod).toIntern() == .u8_type);
6162 const ip = &mod.intern_pool;
6263 switch (mod.intern_pool.indexToKey(val.toIntern()).aggregate.storage) {
6364 .bytes => |bytes| return bytes.toNullTerminatedString(ty.arrayLen(mod), ip),
64 .elems => return arrayToIpString(val, ty.arrayLen(mod), mod),
65 .elems => return arrayToIpString(val, ty.arrayLen(mod), pt),
6566 .repeated_elem => |elem| {
66 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(mod));
67 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(pt));
6768 const len: usize = @intCast(ty.arrayLen(mod));
6869 try ip.string_bytes.appendNTimes(mod.gpa, byte, len);
6970 return ip.getOrPutTrailingString(mod.gpa, len, .no_embedded_nulls);
......@@ -73,16 +74,17 @@ pub fn toIpString(val: Value, ty: Type, mod: *Module) !InternPool.NullTerminated
7374
7475/// Asserts that the value is representable as an array of bytes.
7576/// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
76pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, mod: *Module) ![]u8 {
77pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) ![]u8 {
78 const mod = pt.zcu;
7779 const ip = &mod.intern_pool;
7880 return switch (ip.indexToKey(val.toIntern())) {
7981 .enum_literal => |enum_literal| allocator.dupe(u8, enum_literal.toSlice(ip)),
80 .slice => |slice| try arrayToAllocatedBytes(val, Value.fromInterned(slice.len).toUnsignedInt(mod), allocator, mod),
82 .slice => |slice| try arrayToAllocatedBytes(val, Value.fromInterned(slice.len).toUnsignedInt(pt), allocator, pt),
8183 .aggregate => |aggregate| switch (aggregate.storage) {
8284 .bytes => |bytes| try allocator.dupe(u8, bytes.toSlice(ty.arrayLenIncludingSentinel(mod), ip)),
83 .elems => try arrayToAllocatedBytes(val, ty.arrayLen(mod), allocator, mod),
85 .elems => try arrayToAllocatedBytes(val, ty.arrayLen(mod), allocator, pt),
8486 .repeated_elem => |elem| {
85 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(mod));
87 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(pt));
8688 const result = try allocator.alloc(u8, @intCast(ty.arrayLen(mod)));
8789 @memset(result, byte);
8890 return result;
......@@ -92,16 +94,17 @@ pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, mod: *Module
9294 };
9395}
9496
95fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, mod: *Module) ![]u8 {
97fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, pt: Zcu.PerThread) ![]u8 {
9698 const result = try allocator.alloc(u8, @intCast(len));
9799 for (result, 0..) |*elem, i| {
98 const elem_val = try val.elemValue(mod, i);
99 elem.* = @intCast(elem_val.toUnsignedInt(mod));
100 const elem_val = try val.elemValue(pt, i);
101 elem.* = @intCast(elem_val.toUnsignedInt(pt));
100102 }
101103 return result;
102104}
103105
104fn arrayToIpString(val: Value, len_u64: u64, mod: *Module) !InternPool.NullTerminatedString {
106fn arrayToIpString(val: Value, len_u64: u64, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
107 const mod = pt.zcu;
105108 const gpa = mod.gpa;
106109 const ip = &mod.intern_pool;
107110 const len: usize = @intCast(len_u64);
......@@ -110,9 +113,9 @@ fn arrayToIpString(val: Value, len_u64: u64, mod: *Module) !InternPool.NullTermi
110113 // I don't think elemValue has the possibility to affect ip.string_bytes. Let's
111114 // assert just to be sure.
112115 const prev = ip.string_bytes.items.len;
113 const elem_val = try val.elemValue(mod, i);
116 const elem_val = try val.elemValue(pt, i);
114117 assert(ip.string_bytes.items.len == prev);
115 const byte: u8 = @intCast(elem_val.toUnsignedInt(mod));
118 const byte: u8 = @intCast(elem_val.toUnsignedInt(pt));
116119 ip.string_bytes.appendAssumeCapacity(byte);
117120 }
118121 return ip.getOrPutTrailingString(gpa, len, .no_embedded_nulls);
......@@ -133,14 +136,14 @@ pub fn toType(self: Value) Type {
133136 return Type.fromInterned(self.toIntern());
134137}
135138
136pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
137 const ip = &mod.intern_pool;
139pub fn intFromEnum(val: Value, ty: Type, pt: Zcu.PerThread) Allocator.Error!Value {
140 const ip = &pt.zcu.intern_pool;
138141 const enum_ty = ip.typeOf(val.toIntern());
139142 return switch (ip.indexToKey(enum_ty)) {
140143 // Assume it is already an integer and return it directly.
141144 .simple_type, .int_type => val,
142145 .enum_literal => |enum_literal| {
143 const field_index = ty.enumFieldIndex(enum_literal, mod).?;
146 const field_index = ty.enumFieldIndex(enum_literal, pt.zcu).?;
144147 switch (ip.indexToKey(ty.toIntern())) {
145148 // Assume it is already an integer and return it directly.
146149 .simple_type, .int_type => return val,
......@@ -150,13 +153,13 @@ pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
150153 return Value.fromInterned(enum_type.values.get(ip)[field_index]);
151154 } else {
152155 // Field index and integer values are the same.
153 return mod.intValue(Type.fromInterned(enum_type.tag_ty), field_index);
156 return pt.intValue(Type.fromInterned(enum_type.tag_ty), field_index);
154157 }
155158 },
156159 else => unreachable,
157160 }
158161 },
159 .enum_type => try mod.getCoerced(val, Type.fromInterned(ip.loadEnumType(enum_ty).tag_ty)),
162 .enum_type => try pt.getCoerced(val, Type.fromInterned(ip.loadEnumType(enum_ty).tag_ty)),
160163 else => unreachable,
161164 };
162165}
......@@ -164,38 +167,38 @@ pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
164167pub const ResolveStrat = Type.ResolveStrat;
165168
166169/// Asserts the value is an integer.
167pub fn toBigInt(val: Value, space: *BigIntSpace, mod: *Module) BigIntConst {
168 return val.toBigIntAdvanced(space, mod, .normal) catch unreachable;
170pub fn toBigInt(val: Value, space: *BigIntSpace, pt: Zcu.PerThread) BigIntConst {
171 return val.toBigIntAdvanced(space, pt, .normal) catch unreachable;
169172}
170173
171174/// Asserts the value is an integer.
172175pub fn toBigIntAdvanced(
173176 val: Value,
174177 space: *BigIntSpace,
175 mod: *Module,
178 pt: Zcu.PerThread,
176179 strat: ResolveStrat,
177180) Module.CompileError!BigIntConst {
178181 return switch (val.toIntern()) {
179182 .bool_false => BigIntMutable.init(&space.limbs, 0).toConst(),
180183 .bool_true => BigIntMutable.init(&space.limbs, 1).toConst(),
181184 .null_value => BigIntMutable.init(&space.limbs, 0).toConst(),
182 else => switch (mod.intern_pool.indexToKey(val.toIntern())) {
185 else => switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
183186 .int => |int| switch (int.storage) {
184187 .u64, .i64, .big_int => int.storage.toBigInt(space),
185188 .lazy_align, .lazy_size => |ty| {
186 if (strat == .sema) try Type.fromInterned(ty).resolveLayout(mod);
189 if (strat == .sema) try Type.fromInterned(ty).resolveLayout(pt);
187190 const x = switch (int.storage) {
188191 else => unreachable,
189 .lazy_align => Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0,
190 .lazy_size => Type.fromInterned(ty).abiSize(mod),
192 .lazy_align => Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0,
193 .lazy_size => Type.fromInterned(ty).abiSize(pt),
191194 };
192195 return BigIntMutable.init(&space.limbs, x).toConst();
193196 },
194197 },
195 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).toBigIntAdvanced(space, mod, strat),
198 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).toBigIntAdvanced(space, pt, strat),
196199 .opt, .ptr => BigIntMutable.init(
197200 &space.limbs,
198 (try val.getUnsignedIntAdvanced(mod, strat)).?,
201 (try val.getUnsignedIntAdvanced(pt, strat)).?,
199202 ).toConst(),
200203 else => unreachable,
201204 },
......@@ -229,13 +232,14 @@ pub fn getVariable(val: Value, mod: *Module) ?InternPool.Key.Variable {
229232
230233/// If the value fits in a u64, return it, otherwise null.
231234/// Asserts not undefined.
232pub fn getUnsignedInt(val: Value, mod: *Module) ?u64 {
233 return getUnsignedIntAdvanced(val, mod, .normal) catch unreachable;
235pub fn getUnsignedInt(val: Value, pt: Zcu.PerThread) ?u64 {
236 return getUnsignedIntAdvanced(val, pt, .normal) catch unreachable;
234237}
235238
236239/// If the value fits in a u64, return it, otherwise null.
237240/// Asserts not undefined.
238pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u64 {
241pub fn getUnsignedIntAdvanced(val: Value, pt: Zcu.PerThread, strat: ResolveStrat) !?u64 {
242 const mod = pt.zcu;
239243 return switch (val.toIntern()) {
240244 .undef => unreachable,
241245 .bool_false => 0,
......@@ -246,22 +250,22 @@ pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u
246250 .big_int => |big_int| big_int.to(u64) catch null,
247251 .u64 => |x| x,
248252 .i64 => |x| std.math.cast(u64, x),
249 .lazy_align => |ty| (try Type.fromInterned(ty).abiAlignmentAdvanced(mod, strat.toLazy())).scalar.toByteUnits() orelse 0,
250 .lazy_size => |ty| (try Type.fromInterned(ty).abiSizeAdvanced(mod, strat.toLazy())).scalar,
253 .lazy_align => |ty| (try Type.fromInterned(ty).abiAlignmentAdvanced(pt, strat.toLazy())).scalar.toByteUnits() orelse 0,
254 .lazy_size => |ty| (try Type.fromInterned(ty).abiSizeAdvanced(pt, strat.toLazy())).scalar,
251255 },
252256 .ptr => |ptr| switch (ptr.base_addr) {
253257 .int => ptr.byte_offset,
254258 .field => |field| {
255 const base_addr = (try Value.fromInterned(field.base).getUnsignedIntAdvanced(mod, strat)) orelse return null;
259 const base_addr = (try Value.fromInterned(field.base).getUnsignedIntAdvanced(pt, strat)) orelse return null;
256260 const struct_ty = Value.fromInterned(field.base).typeOf(mod).childType(mod);
257 if (strat == .sema) try struct_ty.resolveLayout(mod);
258 return base_addr + struct_ty.structFieldOffset(@intCast(field.index), mod) + ptr.byte_offset;
261 if (strat == .sema) try struct_ty.resolveLayout(pt);
262 return base_addr + struct_ty.structFieldOffset(@intCast(field.index), pt) + ptr.byte_offset;
259263 },
260264 else => null,
261265 },
262266 .opt => |opt| switch (opt.val) {
263267 .none => 0,
264 else => |payload| Value.fromInterned(payload).getUnsignedIntAdvanced(mod, strat),
268 else => |payload| Value.fromInterned(payload).getUnsignedIntAdvanced(pt, strat),
265269 },
266270 else => null,
267271 },
......@@ -269,27 +273,27 @@ pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u
269273}
270274
271275/// Asserts the value is an integer and it fits in a u64
272pub fn toUnsignedInt(val: Value, zcu: *Zcu) u64 {
273 return getUnsignedInt(val, zcu).?;
276pub fn toUnsignedInt(val: Value, pt: Zcu.PerThread) u64 {
277 return getUnsignedInt(val, pt).?;
274278}
275279
276280/// Asserts the value is an integer and it fits in a u64
277pub fn toUnsignedIntSema(val: Value, zcu: *Zcu) !u64 {
278 return (try getUnsignedIntAdvanced(val, zcu, .sema)).?;
281pub fn toUnsignedIntSema(val: Value, pt: Zcu.PerThread) !u64 {
282 return (try getUnsignedIntAdvanced(val, pt, .sema)).?;
279283}
280284
281285/// Asserts the value is an integer and it fits in a i64
282pub fn toSignedInt(val: Value, mod: *Module) i64 {
286pub fn toSignedInt(val: Value, pt: Zcu.PerThread) i64 {
283287 return switch (val.toIntern()) {
284288 .bool_false => 0,
285289 .bool_true => 1,
286 else => switch (mod.intern_pool.indexToKey(val.toIntern())) {
290 else => switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
287291 .int => |int| switch (int.storage) {
288292 .big_int => |big_int| big_int.to(i64) catch unreachable,
289293 .i64 => |x| x,
290294 .u64 => |x| @intCast(x),
291 .lazy_align => |ty| @intCast(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0),
292 .lazy_size => |ty| @intCast(Type.fromInterned(ty).abiSize(mod)),
295 .lazy_align => |ty| @intCast(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0),
296 .lazy_size => |ty| @intCast(Type.fromInterned(ty).abiSize(pt)),
293297 },
294298 else => unreachable,
295299 },
......@@ -321,16 +325,17 @@ fn ptrHasIntAddr(val: Value, mod: *Module) bool {
321325///
322326/// Asserts that buffer.len >= ty.abiSize(). The buffer is allowed to extend past
323327/// the end of the value in memory.
324pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
328pub fn writeToMemory(val: Value, ty: Type, pt: Zcu.PerThread, buffer: []u8) error{
325329 ReinterpretDeclRef,
326330 IllDefinedMemoryLayout,
327331 Unimplemented,
328332 OutOfMemory,
329333}!void {
334 const mod = pt.zcu;
330335 const target = mod.getTarget();
331336 const endian = target.cpu.arch.endian();
332337 if (val.isUndef(mod)) {
333 const size: usize = @intCast(ty.abiSize(mod));
338 const size: usize = @intCast(ty.abiSize(pt));
334339 @memset(buffer[0..size], 0xaa);
335340 return;
336341 }
......@@ -346,41 +351,41 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
346351 const byte_count: u16 = @intCast((@as(u17, bits) + 7) / 8);
347352
348353 var bigint_buffer: BigIntSpace = undefined;
349 const bigint = val.toBigInt(&bigint_buffer, mod);
354 const bigint = val.toBigInt(&bigint_buffer, pt);
350355 bigint.writeTwosComplement(buffer[0..byte_count], endian);
351356 },
352357 .Float => switch (ty.floatBits(target)) {
353 16 => std.mem.writeInt(u16, buffer[0..2], @bitCast(val.toFloat(f16, mod)), endian),
354 32 => std.mem.writeInt(u32, buffer[0..4], @bitCast(val.toFloat(f32, mod)), endian),
355 64 => std.mem.writeInt(u64, buffer[0..8], @bitCast(val.toFloat(f64, mod)), endian),
356 80 => std.mem.writeInt(u80, buffer[0..10], @bitCast(val.toFloat(f80, mod)), endian),
357 128 => std.mem.writeInt(u128, buffer[0..16], @bitCast(val.toFloat(f128, mod)), endian),
358 16 => std.mem.writeInt(u16, buffer[0..2], @bitCast(val.toFloat(f16, pt)), endian),
359 32 => std.mem.writeInt(u32, buffer[0..4], @bitCast(val.toFloat(f32, pt)), endian),
360 64 => std.mem.writeInt(u64, buffer[0..8], @bitCast(val.toFloat(f64, pt)), endian),
361 80 => std.mem.writeInt(u80, buffer[0..10], @bitCast(val.toFloat(f80, pt)), endian),
362 128 => std.mem.writeInt(u128, buffer[0..16], @bitCast(val.toFloat(f128, pt)), endian),
358363 else => unreachable,
359364 },
360365 .Array => {
361366 const len = ty.arrayLen(mod);
362367 const elem_ty = ty.childType(mod);
363 const elem_size: usize = @intCast(elem_ty.abiSize(mod));
368 const elem_size: usize = @intCast(elem_ty.abiSize(pt));
364369 var elem_i: usize = 0;
365370 var buf_off: usize = 0;
366371 while (elem_i < len) : (elem_i += 1) {
367 const elem_val = try val.elemValue(mod, elem_i);
368 try elem_val.writeToMemory(elem_ty, mod, buffer[buf_off..]);
372 const elem_val = try val.elemValue(pt, elem_i);
373 try elem_val.writeToMemory(elem_ty, pt, buffer[buf_off..]);
369374 buf_off += elem_size;
370375 }
371376 },
372377 .Vector => {
373378 // We use byte_count instead of abi_size here, so that any padding bytes
374379 // follow the data bytes, on both big- and little-endian systems.
375 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
376 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
380 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
381 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
377382 },
378383 .Struct => {
379384 const struct_type = mod.typeToStruct(ty) orelse return error.IllDefinedMemoryLayout;
380385 switch (struct_type.layout) {
381386 .auto => return error.IllDefinedMemoryLayout,
382387 .@"extern" => for (0..struct_type.field_types.len) |field_index| {
383 const off: usize = @intCast(ty.structFieldOffset(field_index, mod));
388 const off: usize = @intCast(ty.structFieldOffset(field_index, pt));
384389 const field_val = Value.fromInterned(switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
385390 .bytes => |bytes| {
386391 buffer[off] = bytes.at(field_index, ip);
......@@ -390,11 +395,11 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
390395 .repeated_elem => |elem| elem,
391396 });
392397 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
393 try writeToMemory(field_val, field_ty, mod, buffer[off..]);
398 try writeToMemory(field_val, field_ty, pt, buffer[off..]);
394399 },
395400 .@"packed" => {
396 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
397 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
401 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
402 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
398403 },
399404 }
400405 },
......@@ -421,34 +426,34 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
421426 const union_obj = mod.typeToUnion(ty).?;
422427 const field_index = mod.unionTagFieldIndex(union_obj, union_tag).?;
423428 const field_type = Type.fromInterned(union_obj.field_types.get(&mod.intern_pool)[field_index]);
424 const field_val = try val.fieldValue(mod, field_index);
425 const byte_count: usize = @intCast(field_type.abiSize(mod));
426 return writeToMemory(field_val, field_type, mod, buffer[0..byte_count]);
429 const field_val = try val.fieldValue(pt, field_index);
430 const byte_count: usize = @intCast(field_type.abiSize(pt));
431 return writeToMemory(field_val, field_type, pt, buffer[0..byte_count]);
427432 } else {
428 const backing_ty = try ty.unionBackingType(mod);
429 const byte_count: usize = @intCast(backing_ty.abiSize(mod));
430 return writeToMemory(val.unionValue(mod), backing_ty, mod, buffer[0..byte_count]);
433 const backing_ty = try ty.unionBackingType(pt);
434 const byte_count: usize = @intCast(backing_ty.abiSize(pt));
435 return writeToMemory(val.unionValue(mod), backing_ty, pt, buffer[0..byte_count]);
431436 }
432437 },
433438 .@"packed" => {
434 const backing_ty = try ty.unionBackingType(mod);
435 const byte_count: usize = @intCast(backing_ty.abiSize(mod));
436 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
439 const backing_ty = try ty.unionBackingType(pt);
440 const byte_count: usize = @intCast(backing_ty.abiSize(pt));
441 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
437442 },
438443 },
439444 .Pointer => {
440445 if (ty.isSlice(mod)) return error.IllDefinedMemoryLayout;
441446 if (!val.ptrHasIntAddr(mod)) return error.ReinterpretDeclRef;
442 return val.writeToMemory(Type.usize, mod, buffer);
447 return val.writeToMemory(Type.usize, pt, buffer);
443448 },
444449 .Optional => {
445450 if (!ty.isPtrLikeOptional(mod)) return error.IllDefinedMemoryLayout;
446451 const child = ty.optionalChild(mod);
447452 const opt_val = val.optionalValue(mod);
448453 if (opt_val) |some| {
449 return some.writeToMemory(child, mod, buffer);
454 return some.writeToMemory(child, pt, buffer);
450455 } else {
451 return writeToMemory(try mod.intValue(Type.usize, 0), Type.usize, mod, buffer);
456 return writeToMemory(try pt.intValue(Type.usize, 0), Type.usize, pt, buffer);
452457 }
453458 },
454459 else => return error.Unimplemented,
......@@ -462,15 +467,16 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
462467pub fn writeToPackedMemory(
463468 val: Value,
464469 ty: Type,
465 mod: *Module,
470 pt: Zcu.PerThread,
466471 buffer: []u8,
467472 bit_offset: usize,
468473) error{ ReinterpretDeclRef, OutOfMemory }!void {
474 const mod = pt.zcu;
469475 const ip = &mod.intern_pool;
470476 const target = mod.getTarget();
471477 const endian = target.cpu.arch.endian();
472478 if (val.isUndef(mod)) {
473 const bit_size: usize = @intCast(ty.bitSize(mod));
479 const bit_size: usize = @intCast(ty.bitSize(pt));
474480 if (bit_size != 0) {
475481 std.mem.writeVarPackedInt(buffer, bit_offset, bit_size, @as(u1, 0), endian);
476482 }
......@@ -494,30 +500,30 @@ pub fn writeToPackedMemory(
494500 const bits = ty.intInfo(mod).bits;
495501 if (bits == 0) return;
496502
497 switch (ip.indexToKey((try val.intFromEnum(ty, mod)).toIntern()).int.storage) {
503 switch (ip.indexToKey((try val.intFromEnum(ty, pt)).toIntern()).int.storage) {
498504 inline .u64, .i64 => |int| std.mem.writeVarPackedInt(buffer, bit_offset, bits, int, endian),
499505 .big_int => |bigint| bigint.writePackedTwosComplement(buffer, bit_offset, bits, endian),
500506 .lazy_align => |lazy_align| {
501 const num = Type.fromInterned(lazy_align).abiAlignment(mod).toByteUnits() orelse 0;
507 const num = Type.fromInterned(lazy_align).abiAlignment(pt).toByteUnits() orelse 0;
502508 std.mem.writeVarPackedInt(buffer, bit_offset, bits, num, endian);
503509 },
504510 .lazy_size => |lazy_size| {
505 const num = Type.fromInterned(lazy_size).abiSize(mod);
511 const num = Type.fromInterned(lazy_size).abiSize(pt);
506512 std.mem.writeVarPackedInt(buffer, bit_offset, bits, num, endian);
507513 },
508514 }
509515 },
510516 .Float => switch (ty.floatBits(target)) {
511 16 => std.mem.writePackedInt(u16, buffer, bit_offset, @bitCast(val.toFloat(f16, mod)), endian),
512 32 => std.mem.writePackedInt(u32, buffer, bit_offset, @bitCast(val.toFloat(f32, mod)), endian),
513 64 => std.mem.writePackedInt(u64, buffer, bit_offset, @bitCast(val.toFloat(f64, mod)), endian),
514 80 => std.mem.writePackedInt(u80, buffer, bit_offset, @bitCast(val.toFloat(f80, mod)), endian),
515 128 => std.mem.writePackedInt(u128, buffer, bit_offset, @bitCast(val.toFloat(f128, mod)), endian),
517 16 => std.mem.writePackedInt(u16, buffer, bit_offset, @bitCast(val.toFloat(f16, pt)), endian),
518 32 => std.mem.writePackedInt(u32, buffer, bit_offset, @bitCast(val.toFloat(f32, pt)), endian),
519 64 => std.mem.writePackedInt(u64, buffer, bit_offset, @bitCast(val.toFloat(f64, pt)), endian),
520 80 => std.mem.writePackedInt(u80, buffer, bit_offset, @bitCast(val.toFloat(f80, pt)), endian),
521 128 => std.mem.writePackedInt(u128, buffer, bit_offset, @bitCast(val.toFloat(f128, pt)), endian),
516522 else => unreachable,
517523 },
518524 .Vector => {
519525 const elem_ty = ty.childType(mod);
520 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(mod));
526 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(pt));
521527 const len: usize = @intCast(ty.arrayLen(mod));
522528
523529 var bits: u16 = 0;
......@@ -525,8 +531,8 @@ pub fn writeToPackedMemory(
525531 while (elem_i < len) : (elem_i += 1) {
526532 // On big-endian systems, LLVM reverses the element order of vectors by default
527533 const tgt_elem_i = if (endian == .big) len - elem_i - 1 else elem_i;
528 const elem_val = try val.elemValue(mod, tgt_elem_i);
529 try elem_val.writeToPackedMemory(elem_ty, mod, buffer, bit_offset + bits);
534 const elem_val = try val.elemValue(pt, tgt_elem_i);
535 try elem_val.writeToPackedMemory(elem_ty, pt, buffer, bit_offset + bits);
530536 bits += elem_bit_size;
531537 }
532538 },
......@@ -543,8 +549,8 @@ pub fn writeToPackedMemory(
543549 .repeated_elem => |elem| elem,
544550 });
545551 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
546 const field_bits: u16 = @intCast(field_ty.bitSize(mod));
547 try field_val.writeToPackedMemory(field_ty, mod, buffer, bit_offset + bits);
552 const field_bits: u16 = @intCast(field_ty.bitSize(pt));
553 try field_val.writeToPackedMemory(field_ty, pt, buffer, bit_offset + bits);
548554 bits += field_bits;
549555 }
550556 },
......@@ -556,11 +562,11 @@ pub fn writeToPackedMemory(
556562 if (val.unionTag(mod)) |union_tag| {
557563 const field_index = mod.unionTagFieldIndex(union_obj, union_tag).?;
558564 const field_type = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
559 const field_val = try val.fieldValue(mod, field_index);
560 return field_val.writeToPackedMemory(field_type, mod, buffer, bit_offset);
565 const field_val = try val.fieldValue(pt, field_index);
566 return field_val.writeToPackedMemory(field_type, pt, buffer, bit_offset);
561567 } else {
562 const backing_ty = try ty.unionBackingType(mod);
563 return val.unionValue(mod).writeToPackedMemory(backing_ty, mod, buffer, bit_offset);
568 const backing_ty = try ty.unionBackingType(pt);
569 return val.unionValue(mod).writeToPackedMemory(backing_ty, pt, buffer, bit_offset);
564570 }
565571 },
566572 }
......@@ -568,16 +574,16 @@ pub fn writeToPackedMemory(
568574 .Pointer => {
569575 assert(!ty.isSlice(mod)); // No well defined layout.
570576 if (!val.ptrHasIntAddr(mod)) return error.ReinterpretDeclRef;
571 return val.writeToPackedMemory(Type.usize, mod, buffer, bit_offset);
577 return val.writeToPackedMemory(Type.usize, pt, buffer, bit_offset);
572578 },
573579 .Optional => {
574580 assert(ty.isPtrLikeOptional(mod));
575581 const child = ty.optionalChild(mod);
576582 const opt_val = val.optionalValue(mod);
577583 if (opt_val) |some| {
578 return some.writeToPackedMemory(child, mod, buffer, bit_offset);
584 return some.writeToPackedMemory(child, pt, buffer, bit_offset);
579585 } else {
580 return writeToPackedMemory(try mod.intValue(Type.usize, 0), Type.usize, mod, buffer, bit_offset);
586 return writeToPackedMemory(try pt.intValue(Type.usize, 0), Type.usize, pt, buffer, bit_offset);
581587 }
582588 },
583589 else => @panic("TODO implement writeToPackedMemory for more types"),
......@@ -590,7 +596,7 @@ pub fn writeToPackedMemory(
590596/// the end of the value in memory.
591597pub fn readFromMemory(
592598 ty: Type,
593 mod: *Module,
599 pt: Zcu.PerThread,
594600 buffer: []const u8,
595601 arena: Allocator,
596602) error{
......@@ -598,6 +604,7 @@ pub fn readFromMemory(
598604 Unimplemented,
599605 OutOfMemory,
600606}!Value {
607 const mod = pt.zcu;
601608 const ip = &mod.intern_pool;
602609 const target = mod.getTarget();
603610 const endian = target.cpu.arch.endian();
......@@ -642,7 +649,7 @@ pub fn readFromMemory(
642649 return mod.getCoerced(try mod.intValue_big(int_ty, bigint.toConst()), ty);
643650 }
644651 },
645 .Float => return Value.fromInterned((try mod.intern(.{ .float = .{
652 .Float => return Value.fromInterned(try pt.intern(.{ .float = .{
646653 .ty = ty.toIntern(),
647654 .storage = switch (ty.floatBits(target)) {
648655 16 => .{ .f16 = @bitCast(std.mem.readInt(u16, buffer[0..2], endian)) },
......@@ -652,25 +659,25 @@ pub fn readFromMemory(
652659 128 => .{ .f128 = @bitCast(std.mem.readInt(u128, buffer[0..16], endian)) },
653660 else => unreachable,
654661 },
655 } }))),
662 } })),
656663 .Array => {
657664 const elem_ty = ty.childType(mod);
658 const elem_size = elem_ty.abiSize(mod);
665 const elem_size = elem_ty.abiSize(pt);
659666 const elems = try arena.alloc(InternPool.Index, @intCast(ty.arrayLen(mod)));
660667 var offset: usize = 0;
661668 for (elems) |*elem| {
662669 elem.* = (try readFromMemory(elem_ty, mod, buffer[offset..], arena)).toIntern();
663670 offset += @intCast(elem_size);
664671 }
665 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
672 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
666673 .ty = ty.toIntern(),
667674 .storage = .{ .elems = elems },
668 } })));
675 } }));
669676 },
670677 .Vector => {
671678 // We use byte_count instead of abi_size here, so that any padding bytes
672679 // follow the data bytes, on both big- and little-endian systems.
673 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
680 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
674681 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
675682 },
676683 .Struct => {
......@@ -683,16 +690,16 @@ pub fn readFromMemory(
683690 for (field_vals, 0..) |*field_val, i| {
684691 const field_ty = Type.fromInterned(field_types.get(ip)[i]);
685692 const off: usize = @intCast(ty.structFieldOffset(i, mod));
686 const sz: usize = @intCast(field_ty.abiSize(mod));
693 const sz: usize = @intCast(field_ty.abiSize(pt));
687694 field_val.* = (try readFromMemory(field_ty, mod, buffer[off..(off + sz)], arena)).toIntern();
688695 }
689 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
696 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
690697 .ty = ty.toIntern(),
691698 .storage = .{ .elems = field_vals },
692 } })));
699 } }));
693700 },
694701 .@"packed" => {
695 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
702 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
696703 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
697704 },
698705 }
......@@ -704,49 +711,49 @@ pub fn readFromMemory(
704711 const index = (int << @as(u6, @intCast(64 - bits))) >> @as(u6, @intCast(64 - bits));
705712 const name = mod.global_error_set.keys()[@intCast(index)];
706713
707 return Value.fromInterned((try mod.intern(.{ .err = .{
714 return Value.fromInterned(try pt.intern(.{ .err = .{
708715 .ty = ty.toIntern(),
709716 .name = name,
710 } })));
717 } }));
711718 },
712719 .Union => switch (ty.containerLayout(mod)) {
713720 .auto => return error.IllDefinedMemoryLayout,
714721 .@"extern" => {
715 const union_size = ty.abiSize(mod);
722 const union_size = ty.abiSize(pt);
716723 const array_ty = try mod.arrayType(.{ .len = union_size, .child = .u8_type });
717724 const val = (try readFromMemory(array_ty, mod, buffer, arena)).toIntern();
718 return Value.fromInterned((try mod.intern(.{ .un = .{
725 return Value.fromInterned(try pt.intern(.{ .un = .{
719726 .ty = ty.toIntern(),
720727 .tag = .none,
721728 .val = val,
722 } })));
729 } }));
723730 },
724731 .@"packed" => {
725 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
732 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
726733 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
727734 },
728735 },
729736 .Pointer => {
730737 assert(!ty.isSlice(mod)); // No well defined layout.
731738 const int_val = try readFromMemory(Type.usize, mod, buffer, arena);
732 return Value.fromInterned((try mod.intern(.{ .ptr = .{
739 return Value.fromInterned(try pt.intern(.{ .ptr = .{
733740 .ty = ty.toIntern(),
734741 .base_addr = .int,
735 .byte_offset = int_val.toUnsignedInt(mod),
736 } })));
742 .byte_offset = int_val.toUnsignedInt(pt),
743 } }));
737744 },
738745 .Optional => {
739746 assert(ty.isPtrLikeOptional(mod));
740747 const child_ty = ty.optionalChild(mod);
741748 const child_val = try readFromMemory(child_ty, mod, buffer, arena);
742 return Value.fromInterned((try mod.intern(.{ .opt = .{
749 return Value.fromInterned(try pt.intern(.{ .opt = .{
743750 .ty = ty.toIntern(),
744 .val = switch (child_val.orderAgainstZero(mod)) {
751 .val = switch (child_val.orderAgainstZero(pt)) {
745752 .lt => unreachable,
746753 .eq => .none,
747754 .gt => child_val.toIntern(),
748755 },
749 } })));
756 } }));
750757 },
751758 else => return error.Unimplemented,
752759 }
......@@ -758,7 +765,7 @@ pub fn readFromMemory(
758765/// big-endian packed memory layouts start at the end of the buffer.
759766pub fn readFromPackedMemory(
760767 ty: Type,
761 mod: *Module,
768 pt: Zcu.PerThread,
762769 buffer: []const u8,
763770 bit_offset: usize,
764771 arena: Allocator,
......@@ -766,6 +773,7 @@ pub fn readFromPackedMemory(
766773 IllDefinedMemoryLayout,
767774 OutOfMemory,
768775}!Value {
776 const mod = pt.zcu;
769777 const ip = &mod.intern_pool;
770778 const target = mod.getTarget();
771779 const endian = target.cpu.arch.endian();
......@@ -783,35 +791,35 @@ pub fn readFromPackedMemory(
783791 }
784792 },
785793 .Int => {
786 if (buffer.len == 0) return mod.intValue(ty, 0);
794 if (buffer.len == 0) return pt.intValue(ty, 0);
787795 const int_info = ty.intInfo(mod);
788796 const bits = int_info.bits;
789 if (bits == 0) return mod.intValue(ty, 0);
797 if (bits == 0) return pt.intValue(ty, 0);
790798
791799 // Fast path for integers <= u64
792800 if (bits <= 64) switch (int_info.signedness) {
793801 // Use different backing types for unsigned vs signed to avoid the need to go via
794802 // a larger type like `i128`.
795 .unsigned => return mod.intValue(ty, std.mem.readVarPackedInt(u64, buffer, bit_offset, bits, endian, .unsigned)),
796 .signed => return mod.intValue(ty, std.mem.readVarPackedInt(i64, buffer, bit_offset, bits, endian, .signed)),
803 .unsigned => return pt.intValue(ty, std.mem.readVarPackedInt(u64, buffer, bit_offset, bits, endian, .unsigned)),
804 .signed => return pt.intValue(ty, std.mem.readVarPackedInt(i64, buffer, bit_offset, bits, endian, .signed)),
797805 };
798806
799807 // Slow path, we have to construct a big-int
800 const abi_size: usize = @intCast(ty.abiSize(mod));
808 const abi_size: usize = @intCast(ty.abiSize(pt));
801809 const Limb = std.math.big.Limb;
802810 const limb_count = (abi_size + @sizeOf(Limb) - 1) / @sizeOf(Limb);
803811 const limbs_buffer = try arena.alloc(Limb, limb_count);
804812
805813 var bigint = BigIntMutable.init(limbs_buffer, 0);
806814 bigint.readPackedTwosComplement(buffer, bit_offset, bits, endian, int_info.signedness);
807 return mod.intValue_big(ty, bigint.toConst());
815 return pt.intValue_big(ty, bigint.toConst());
808816 },
809817 .Enum => {
810818 const int_ty = ty.intTagType(mod);
811 const int_val = try Value.readFromPackedMemory(int_ty, mod, buffer, bit_offset, arena);
812 return mod.getCoerced(int_val, ty);
819 const int_val = try Value.readFromPackedMemory(int_ty, pt, buffer, bit_offset, arena);
820 return pt.getCoerced(int_val, ty);
813821 },
814 .Float => return Value.fromInterned((try mod.intern(.{ .float = .{
822 .Float => return Value.fromInterned(try pt.intern(.{ .float = .{
815823 .ty = ty.toIntern(),
816824 .storage = switch (ty.floatBits(target)) {
817825 16 => .{ .f16 = @bitCast(std.mem.readPackedInt(u16, buffer, bit_offset, endian)) },
......@@ -821,23 +829,23 @@ pub fn readFromPackedMemory(
821829 128 => .{ .f128 = @bitCast(std.mem.readPackedInt(u128, buffer, bit_offset, endian)) },
822830 else => unreachable,
823831 },
824 } }))),
832 } })),
825833 .Vector => {
826834 const elem_ty = ty.childType(mod);
827835 const elems = try arena.alloc(InternPool.Index, @intCast(ty.arrayLen(mod)));
828836
829837 var bits: u16 = 0;
830 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(mod));
838 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(pt));
831839 for (elems, 0..) |_, i| {
832840 // On big-endian systems, LLVM reverses the element order of vectors by default
833841 const tgt_elem_i = if (endian == .big) elems.len - i - 1 else i;
834 elems[tgt_elem_i] = (try readFromPackedMemory(elem_ty, mod, buffer, bit_offset + bits, arena)).toIntern();
842 elems[tgt_elem_i] = (try readFromPackedMemory(elem_ty, pt, buffer, bit_offset + bits, arena)).toIntern();
835843 bits += elem_bit_size;
836844 }
837 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
845 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
838846 .ty = ty.toIntern(),
839847 .storage = .{ .elems = elems },
840 } })));
848 } }));
841849 },
842850 .Struct => {
843851 // Sema is supposed to have emitted a compile error already for Auto layout structs,
......@@ -847,43 +855,43 @@ pub fn readFromPackedMemory(
847855 const field_vals = try arena.alloc(InternPool.Index, struct_type.field_types.len);
848856 for (field_vals, 0..) |*field_val, i| {
849857 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
850 const field_bits: u16 = @intCast(field_ty.bitSize(mod));
851 field_val.* = (try readFromPackedMemory(field_ty, mod, buffer, bit_offset + bits, arena)).toIntern();
858 const field_bits: u16 = @intCast(field_ty.bitSize(pt));
859 field_val.* = (try readFromPackedMemory(field_ty, pt, buffer, bit_offset + bits, arena)).toIntern();
852860 bits += field_bits;
853861 }
854 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
862 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
855863 .ty = ty.toIntern(),
856864 .storage = .{ .elems = field_vals },
857 } })));
865 } }));
858866 },
859867 .Union => switch (ty.containerLayout(mod)) {
860868 .auto, .@"extern" => unreachable, // Handled by non-packed readFromMemory
861869 .@"packed" => {
862 const backing_ty = try ty.unionBackingType(mod);
863 const val = (try readFromPackedMemory(backing_ty, mod, buffer, bit_offset, arena)).toIntern();
864 return Value.fromInterned((try mod.intern(.{ .un = .{
870 const backing_ty = try ty.unionBackingType(pt);
871 const val = (try readFromPackedMemory(backing_ty, pt, buffer, bit_offset, arena)).toIntern();
872 return Value.fromInterned(try pt.intern(.{ .un = .{
865873 .ty = ty.toIntern(),
866874 .tag = .none,
867875 .val = val,
868 } })));
876 } }));
869877 },
870878 },
871879 .Pointer => {
872880 assert(!ty.isSlice(mod)); // No well defined layout.
873 const int_val = try readFromPackedMemory(Type.usize, mod, buffer, bit_offset, arena);
874 return Value.fromInterned(try mod.intern(.{ .ptr = .{
881 const int_val = try readFromPackedMemory(Type.usize, pt, buffer, bit_offset, arena);
882 return Value.fromInterned(try pt.intern(.{ .ptr = .{
875883 .ty = ty.toIntern(),
876884 .base_addr = .int,
877 .byte_offset = int_val.toUnsignedInt(mod),
885 .byte_offset = int_val.toUnsignedInt(pt),
878886 } }));
879887 },
880888 .Optional => {
881889 assert(ty.isPtrLikeOptional(mod));
882890 const child_ty = ty.optionalChild(mod);
883 const child_val = try readFromPackedMemory(child_ty, mod, buffer, bit_offset, arena);
884 return Value.fromInterned(try mod.intern(.{ .opt = .{
891 const child_val = try readFromPackedMemory(child_ty, pt, buffer, bit_offset, arena);
892 return Value.fromInterned(try pt.intern(.{ .opt = .{
885893 .ty = ty.toIntern(),
886 .val = switch (child_val.orderAgainstZero(mod)) {
894 .val = switch (child_val.orderAgainstZero(pt)) {
887895 .lt => unreachable,
888896 .eq => .none,
889897 .gt => child_val.toIntern(),
......@@ -895,8 +903,8 @@ pub fn readFromPackedMemory(
895903}
896904
897905/// Asserts that the value is a float or an integer.
898pub fn toFloat(val: Value, comptime T: type, mod: *Module) T {
899 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
906pub fn toFloat(val: Value, comptime T: type, pt: Zcu.PerThread) T {
907 return switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
900908 .int => |int| switch (int.storage) {
901909 .big_int => |big_int| @floatCast(bigIntToFloat(big_int.limbs, big_int.positive)),
902910 inline .u64, .i64 => |x| {
......@@ -905,8 +913,8 @@ pub fn toFloat(val: Value, comptime T: type, mod: *Module) T {
905913 }
906914 return @floatFromInt(x);
907915 },
908 .lazy_align => |ty| @floatFromInt(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0),
909 .lazy_size => |ty| @floatFromInt(Type.fromInterned(ty).abiSize(mod)),
916 .lazy_align => |ty| @floatFromInt(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0),
917 .lazy_size => |ty| @floatFromInt(Type.fromInterned(ty).abiSize(pt)),
910918 },
911919 .float => |float| switch (float.storage) {
912920 inline else => |x| @floatCast(x),
......@@ -934,29 +942,30 @@ fn bigIntToFloat(limbs: []const std.math.big.Limb, positive: bool) f128 {
934942 }
935943}
936944
937pub fn clz(val: Value, ty: Type, mod: *Module) u64 {
945pub fn clz(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
938946 var bigint_buf: BigIntSpace = undefined;
939 const bigint = val.toBigInt(&bigint_buf, mod);
940 return bigint.clz(ty.intInfo(mod).bits);
947 const bigint = val.toBigInt(&bigint_buf, pt);
948 return bigint.clz(ty.intInfo(pt.zcu).bits);
941949}
942950
943pub fn ctz(val: Value, ty: Type, mod: *Module) u64 {
951pub fn ctz(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
944952 var bigint_buf: BigIntSpace = undefined;
945 const bigint = val.toBigInt(&bigint_buf, mod);
946 return bigint.ctz(ty.intInfo(mod).bits);
953 const bigint = val.toBigInt(&bigint_buf, pt);
954 return bigint.ctz(ty.intInfo(pt.zcu).bits);
947955}
948956
949pub fn popCount(val: Value, ty: Type, mod: *Module) u64 {
957pub fn popCount(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
950958 var bigint_buf: BigIntSpace = undefined;
951 const bigint = val.toBigInt(&bigint_buf, mod);
952 return @intCast(bigint.popCount(ty.intInfo(mod).bits));
959 const bigint = val.toBigInt(&bigint_buf, pt);
960 return @intCast(bigint.popCount(ty.intInfo(pt.zcu).bits));
953961}
954962
955pub fn bitReverse(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
963pub fn bitReverse(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) !Value {
964 const mod = pt.zcu;
956965 const info = ty.intInfo(mod);
957966
958967 var buffer: Value.BigIntSpace = undefined;
959 const operand_bigint = val.toBigInt(&buffer, mod);
968 const operand_bigint = val.toBigInt(&buffer, pt);
960969
961970 const limbs = try arena.alloc(
962971 std.math.big.Limb,
......@@ -965,17 +974,18 @@ pub fn bitReverse(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
965974 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
966975 result_bigint.bitReverse(operand_bigint, info.signedness, info.bits);
967976
968 return mod.intValue_big(ty, result_bigint.toConst());
977 return pt.intValue_big(ty, result_bigint.toConst());
969978}
970979
971pub fn byteSwap(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
980pub fn byteSwap(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) !Value {
981 const mod = pt.zcu;
972982 const info = ty.intInfo(mod);
973983
974984 // Bit count must be evenly divisible by 8
975985 assert(info.bits % 8 == 0);
976986
977987 var buffer: Value.BigIntSpace = undefined;
978 const operand_bigint = val.toBigInt(&buffer, mod);
988 const operand_bigint = val.toBigInt(&buffer, pt);
979989
980990 const limbs = try arena.alloc(
981991 std.math.big.Limb,
......@@ -984,33 +994,33 @@ pub fn byteSwap(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
984994 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
985995 result_bigint.byteSwap(operand_bigint, info.signedness, info.bits / 8);
986996
987 return mod.intValue_big(ty, result_bigint.toConst());
997 return pt.intValue_big(ty, result_bigint.toConst());
988998}
989999
9901000/// Asserts the value is an integer and not undefined.
9911001/// Returns the number of bits the value requires to represent stored in twos complement form.
992pub fn intBitCountTwosComp(self: Value, mod: *Module) usize {
1002pub fn intBitCountTwosComp(self: Value, pt: Zcu.PerThread) usize {
9931003 var buffer: BigIntSpace = undefined;
994 const big_int = self.toBigInt(&buffer, mod);
1004 const big_int = self.toBigInt(&buffer, pt);
9951005 return big_int.bitCountTwosComp();
9961006}
9971007
9981008/// Converts an integer or a float to a float. May result in a loss of information.
9991009/// Caller can find out by equality checking the result against the operand.
1000pub fn floatCast(val: Value, dest_ty: Type, zcu: *Zcu) !Value {
1001 const target = zcu.getTarget();
1002 if (val.isUndef(zcu)) return zcu.undefValue(dest_ty);
1003 return Value.fromInterned((try zcu.intern(.{ .float = .{
1010pub fn floatCast(val: Value, dest_ty: Type, pt: Zcu.PerThread) !Value {
1011 const target = pt.zcu.getTarget();
1012 if (val.isUndef(pt.zcu)) return pt.undefValue(dest_ty);
1013 return Value.fromInterned(try pt.intern(.{ .float = .{
10041014 .ty = dest_ty.toIntern(),
10051015 .storage = switch (dest_ty.floatBits(target)) {
1006 16 => .{ .f16 = val.toFloat(f16, zcu) },
1007 32 => .{ .f32 = val.toFloat(f32, zcu) },
1008 64 => .{ .f64 = val.toFloat(f64, zcu) },
1009 80 => .{ .f80 = val.toFloat(f80, zcu) },
1010 128 => .{ .f128 = val.toFloat(f128, zcu) },
1016 16 => .{ .f16 = val.toFloat(f16, pt) },
1017 32 => .{ .f32 = val.toFloat(f32, pt) },
1018 64 => .{ .f64 = val.toFloat(f64, pt) },
1019 80 => .{ .f80 = val.toFloat(f80, pt) },
1020 128 => .{ .f128 = val.toFloat(f128, pt) },
10111021 else => unreachable,
10121022 },
1013 } })));
1023 } }));
10141024}
10151025
10161026/// Asserts the value is a float
......@@ -1023,19 +1033,19 @@ pub fn floatHasFraction(self: Value, mod: *const Module) bool {
10231033 };
10241034}
10251035
1026pub fn orderAgainstZero(lhs: Value, mod: *Module) std.math.Order {
1027 return orderAgainstZeroAdvanced(lhs, mod, .normal) catch unreachable;
1036pub fn orderAgainstZero(lhs: Value, pt: Zcu.PerThread) std.math.Order {
1037 return orderAgainstZeroAdvanced(lhs, pt, .normal) catch unreachable;
10281038}
10291039
10301040pub fn orderAgainstZeroAdvanced(
10311041 lhs: Value,
1032 mod: *Module,
1042 pt: Zcu.PerThread,
10331043 strat: ResolveStrat,
10341044) Module.CompileError!std.math.Order {
10351045 return switch (lhs.toIntern()) {
10361046 .bool_false => .eq,
10371047 .bool_true => .gt,
1038 else => switch (mod.intern_pool.indexToKey(lhs.toIntern())) {
1048 else => switch (pt.zcu.intern_pool.indexToKey(lhs.toIntern())) {
10391049 .ptr => |ptr| if (ptr.byte_offset > 0) .gt else switch (ptr.base_addr) {
10401050 .decl, .comptime_alloc, .comptime_field => .gt,
10411051 .int => .eq,
......@@ -1046,7 +1056,7 @@ pub fn orderAgainstZeroAdvanced(
10461056 inline .u64, .i64 => |x| std.math.order(x, 0),
10471057 .lazy_align => .gt, // alignment is never 0
10481058 .lazy_size => |ty| return if (Type.fromInterned(ty).hasRuntimeBitsAdvanced(
1049 mod,
1059 pt,
10501060 false,
10511061 strat.toLazy(),
10521062 ) catch |err| switch (err) {
......@@ -1054,7 +1064,7 @@ pub fn orderAgainstZeroAdvanced(
10541064 else => |e| return e,
10551065 }) .gt else .eq,
10561066 },
1057 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).orderAgainstZeroAdvanced(mod, strat),
1067 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).orderAgainstZeroAdvanced(pt, strat),
10581068 .float => |float| switch (float.storage) {
10591069 inline else => |x| std.math.order(x, 0),
10601070 },
......@@ -1064,14 +1074,14 @@ pub fn orderAgainstZeroAdvanced(
10641074}
10651075
10661076/// Asserts the value is comparable.
1067pub fn order(lhs: Value, rhs: Value, mod: *Module) std.math.Order {
1068 return orderAdvanced(lhs, rhs, mod, .normal) catch unreachable;
1077pub fn order(lhs: Value, rhs: Value, pt: Zcu.PerThread) std.math.Order {
1078 return orderAdvanced(lhs, rhs, pt, .normal) catch unreachable;
10691079}
10701080
10711081/// Asserts the value is comparable.
1072pub fn orderAdvanced(lhs: Value, rhs: Value, mod: *Module, strat: ResolveStrat) !std.math.Order {
1073 const lhs_against_zero = try lhs.orderAgainstZeroAdvanced(mod, strat);
1074 const rhs_against_zero = try rhs.orderAgainstZeroAdvanced(mod, strat);
1082pub fn orderAdvanced(lhs: Value, rhs: Value, pt: Zcu.PerThread, strat: ResolveStrat) !std.math.Order {
1083 const lhs_against_zero = try lhs.orderAgainstZeroAdvanced(pt, strat);
1084 const rhs_against_zero = try rhs.orderAgainstZeroAdvanced(pt, strat);
10751085 switch (lhs_against_zero) {
10761086 .lt => if (rhs_against_zero != .lt) return .lt,
10771087 .eq => return rhs_against_zero.invert(),
......@@ -1083,34 +1093,34 @@ pub fn orderAdvanced(lhs: Value, rhs: Value, mod: *Module, strat: ResolveStrat)
10831093 .gt => {},
10841094 }
10851095
1086 if (lhs.isFloat(mod) or rhs.isFloat(mod)) {
1087 const lhs_f128 = lhs.toFloat(f128, mod);
1088 const rhs_f128 = rhs.toFloat(f128, mod);
1096 if (lhs.isFloat(pt.zcu) or rhs.isFloat(pt.zcu)) {
1097 const lhs_f128 = lhs.toFloat(f128, pt);
1098 const rhs_f128 = rhs.toFloat(f128, pt);
10891099 return std.math.order(lhs_f128, rhs_f128);
10901100 }
10911101
10921102 var lhs_bigint_space: BigIntSpace = undefined;
10931103 var rhs_bigint_space: BigIntSpace = undefined;
1094 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_bigint_space, mod, strat);
1095 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_bigint_space, mod, strat);
1104 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_bigint_space, pt, strat);
1105 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_bigint_space, pt, strat);
10961106 return lhs_bigint.order(rhs_bigint);
10971107}
10981108
10991109/// Asserts the value is comparable. Does not take a type parameter because it supports
11001110/// comparisons between heterogeneous types.
1101pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value, mod: *Module) bool {
1102 return compareHeteroAdvanced(lhs, op, rhs, mod, .normal) catch unreachable;
1111pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value, pt: Zcu.PerThread) bool {
1112 return compareHeteroAdvanced(lhs, op, rhs, pt, .normal) catch unreachable;
11031113}
11041114
11051115pub fn compareHeteroAdvanced(
11061116 lhs: Value,
11071117 op: std.math.CompareOperator,
11081118 rhs: Value,
1109 mod: *Module,
1119 pt: Zcu.PerThread,
11101120 strat: ResolveStrat,
11111121) !bool {
1112 if (lhs.pointerDecl(mod)) |lhs_decl| {
1113 if (rhs.pointerDecl(mod)) |rhs_decl| {
1122 if (lhs.pointerDecl(pt.zcu)) |lhs_decl| {
1123 if (rhs.pointerDecl(pt.zcu)) |rhs_decl| {
11141124 switch (op) {
11151125 .eq => return lhs_decl == rhs_decl,
11161126 .neq => return lhs_decl != rhs_decl,
......@@ -1123,31 +1133,32 @@ pub fn compareHeteroAdvanced(
11231133 else => {},
11241134 }
11251135 }
1126 } else if (rhs.pointerDecl(mod)) |_| {
1136 } else if (rhs.pointerDecl(pt.zcu)) |_| {
11271137 switch (op) {
11281138 .eq => return false,
11291139 .neq => return true,
11301140 else => {},
11311141 }
11321142 }
1133 return (try orderAdvanced(lhs, rhs, mod, strat)).compare(op);
1143 return (try orderAdvanced(lhs, rhs, pt, strat)).compare(op);
11341144}
11351145
11361146/// Asserts the values are comparable. Both operands have type `ty`.
11371147/// For vectors, returns true if comparison is true for ALL elements.
1138pub fn compareAll(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, mod: *Module) !bool {
1148pub fn compareAll(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, pt: Zcu.PerThread) !bool {
1149 const mod = pt.zcu;
11391150 if (ty.zigTypeTag(mod) == .Vector) {
11401151 const scalar_ty = ty.scalarType(mod);
11411152 for (0..ty.vectorLen(mod)) |i| {
1142 const lhs_elem = try lhs.elemValue(mod, i);
1143 const rhs_elem = try rhs.elemValue(mod, i);
1144 if (!compareScalar(lhs_elem, op, rhs_elem, scalar_ty, mod)) {
1153 const lhs_elem = try lhs.elemValue(pt, i);
1154 const rhs_elem = try rhs.elemValue(pt, i);
1155 if (!compareScalar(lhs_elem, op, rhs_elem, scalar_ty, pt)) {
11451156 return false;
11461157 }
11471158 }
11481159 return true;
11491160 }
1150 return compareScalar(lhs, op, rhs, ty, mod);
1161 return compareScalar(lhs, op, rhs, ty, pt);
11511162}
11521163
11531164/// Asserts the values are comparable. Both operands have type `ty`.
......@@ -1156,12 +1167,12 @@ pub fn compareScalar(
11561167 op: std.math.CompareOperator,
11571168 rhs: Value,
11581169 ty: Type,
1159 mod: *Module,
1170 pt: Zcu.PerThread,
11601171) bool {
11611172 return switch (op) {
1162 .eq => lhs.eql(rhs, ty, mod),
1163 .neq => !lhs.eql(rhs, ty, mod),
1164 else => compareHetero(lhs, op, rhs, mod),
1173 .eq => lhs.eql(rhs, ty, pt.zcu),
1174 .neq => !lhs.eql(rhs, ty, pt.zcu),
1175 else => compareHetero(lhs, op, rhs, pt),
11651176 };
11661177}
11671178
......@@ -1170,24 +1181,25 @@ pub fn compareScalar(
11701181/// Returns `false` if the value or any vector element is undefined.
11711182///
11721183/// Note that `!compareAllWithZero(.eq, ...) != compareAllWithZero(.neq, ...)`
1173pub fn compareAllWithZero(lhs: Value, op: std.math.CompareOperator, mod: *Module) bool {
1174 return compareAllWithZeroAdvancedExtra(lhs, op, mod, .normal) catch unreachable;
1184pub fn compareAllWithZero(lhs: Value, op: std.math.CompareOperator, pt: Zcu.PerThread) bool {
1185 return compareAllWithZeroAdvancedExtra(lhs, op, pt, .normal) catch unreachable;
11751186}
11761187
11771188pub fn compareAllWithZeroSema(
11781189 lhs: Value,
11791190 op: std.math.CompareOperator,
1180 zcu: *Zcu,
1191 pt: Zcu.PerThread,
11811192) Module.CompileError!bool {
1182 return compareAllWithZeroAdvancedExtra(lhs, op, zcu, .sema);
1193 return compareAllWithZeroAdvancedExtra(lhs, op, pt, .sema);
11831194}
11841195
11851196pub fn compareAllWithZeroAdvancedExtra(
11861197 lhs: Value,
11871198 op: std.math.CompareOperator,
1188 mod: *Module,
1199 pt: Zcu.PerThread,
11891200 strat: ResolveStrat,
11901201) Module.CompileError!bool {
1202 const mod = pt.zcu;
11911203 if (lhs.isInf(mod)) {
11921204 switch (op) {
11931205 .neq => return true,
......@@ -1206,14 +1218,14 @@ pub fn compareAllWithZeroAdvancedExtra(
12061218 if (!std.math.order(byte, 0).compare(op)) break false;
12071219 } else true,
12081220 .elems => |elems| for (elems) |elem| {
1209 if (!try Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, mod, strat)) break false;
1221 if (!try Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, pt, strat)) break false;
12101222 } else true,
1211 .repeated_elem => |elem| Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, mod, strat),
1223 .repeated_elem => |elem| Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, pt, strat),
12121224 },
12131225 .undef => return false,
12141226 else => {},
12151227 }
1216 return (try orderAgainstZeroAdvanced(lhs, mod, strat)).compare(op);
1228 return (try orderAgainstZeroAdvanced(lhs, pt, strat)).compare(op);
12171229}
12181230
12191231pub fn eql(a: Value, b: Value, ty: Type, mod: *Module) bool {
......@@ -1275,21 +1287,22 @@ pub fn slicePtr(val: Value, mod: *Module) Value {
12751287
12761288/// Gets the `len` field of a slice value as a `u64`.
12771289/// Resolves the length using `Sema` if necessary.
1278pub fn sliceLen(val: Value, zcu: *Zcu) !u64 {
1279 return Value.fromInterned(zcu.intern_pool.sliceLen(val.toIntern())).toUnsignedIntSema(zcu);
1290pub fn sliceLen(val: Value, pt: Zcu.PerThread) !u64 {
1291 return Value.fromInterned(pt.zcu.intern_pool.sliceLen(val.toIntern())).toUnsignedIntSema(pt);
12801292}
12811293
12821294/// Asserts the value is an aggregate, and returns the element value at the given index.
1283pub fn elemValue(val: Value, zcu: *Zcu, index: usize) Allocator.Error!Value {
1295pub fn elemValue(val: Value, pt: Zcu.PerThread, index: usize) Allocator.Error!Value {
1296 const zcu = pt.zcu;
12841297 const ip = &zcu.intern_pool;
12851298 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
12861299 .undef => |ty| {
1287 return Value.fromInterned(try zcu.intern(.{ .undef = Type.fromInterned(ty).childType(zcu).toIntern() }));
1300 return Value.fromInterned(try pt.intern(.{ .undef = Type.fromInterned(ty).childType(zcu).toIntern() }));
12881301 },
12891302 .aggregate => |aggregate| {
12901303 const len = ip.aggregateTypeLen(aggregate.ty);
12911304 if (index < len) return Value.fromInterned(switch (aggregate.storage) {
1292 .bytes => |bytes| try zcu.intern(.{ .int = .{
1305 .bytes => |bytes| try pt.intern(.{ .int = .{
12931306 .ty = .u8_type,
12941307 .storage = .{ .u64 = bytes.at(index, ip) },
12951308 } }),
......@@ -1330,17 +1343,17 @@ pub fn sliceArray(
13301343 start: usize,
13311344 end: usize,
13321345) error{OutOfMemory}!Value {
1333 const mod = sema.mod;
1334 const ip = &mod.intern_pool;
1335 return Value.fromInterned(try mod.intern(.{
1346 const pt = sema.pt;
1347 const ip = &pt.zcu.intern_pool;
1348 return Value.fromInterned(try pt.intern(.{
13361349 .aggregate = .{
1337 .ty = switch (mod.intern_pool.indexToKey(mod.intern_pool.typeOf(val.toIntern()))) {
1338 .array_type => |array_type| try mod.arrayType(.{
1350 .ty = switch (pt.zcu.intern_pool.indexToKey(pt.zcu.intern_pool.typeOf(val.toIntern()))) {
1351 .array_type => |array_type| try pt.arrayType(.{
13391352 .len = @intCast(end - start),
13401353 .child = array_type.child,
13411354 .sentinel = if (end == array_type.len) array_type.sentinel else .none,
13421355 }),
1343 .vector_type => |vector_type| try mod.vectorType(.{
1356 .vector_type => |vector_type| try pt.vectorType(.{
13441357 .len = @intCast(end - start),
13451358 .child = vector_type.child,
13461359 }),
......@@ -1363,13 +1376,14 @@ pub fn sliceArray(
13631376 }));
13641377}
13651378
1366pub fn fieldValue(val: Value, mod: *Module, index: usize) !Value {
1379pub fn fieldValue(val: Value, pt: Zcu.PerThread, index: usize) !Value {
1380 const mod = pt.zcu;
13671381 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
1368 .undef => |ty| Value.fromInterned((try mod.intern(.{
1382 .undef => |ty| Value.fromInterned(try pt.intern(.{
13691383 .undef = Type.fromInterned(ty).structFieldType(index, mod).toIntern(),
1370 }))),
1384 })),
13711385 .aggregate => |aggregate| Value.fromInterned(switch (aggregate.storage) {
1372 .bytes => |bytes| try mod.intern(.{ .int = .{
1386 .bytes => |bytes| try pt.intern(.{ .int = .{
13731387 .ty = .u8_type,
13741388 .storage = .{ .u64 = bytes.at(index, &mod.intern_pool) },
13751389 } }),
......@@ -1483,40 +1497,49 @@ pub fn floatFromInt(val: Value, arena: Allocator, int_ty: Type, float_ty: Type,
14831497 };
14841498}
14851499
1486pub fn floatFromIntAdvanced(val: Value, arena: Allocator, int_ty: Type, float_ty: Type, mod: *Module, strat: ResolveStrat) !Value {
1500pub fn floatFromIntAdvanced(
1501 val: Value,
1502 arena: Allocator,
1503 int_ty: Type,
1504 float_ty: Type,
1505 pt: Zcu.PerThread,
1506 strat: ResolveStrat,
1507) !Value {
1508 const mod = pt.zcu;
14871509 if (int_ty.zigTypeTag(mod) == .Vector) {
14881510 const result_data = try arena.alloc(InternPool.Index, int_ty.vectorLen(mod));
14891511 const scalar_ty = float_ty.scalarType(mod);
14901512 for (result_data, 0..) |*scalar, i| {
1491 const elem_val = try val.elemValue(mod, i);
1492 scalar.* = (try floatFromIntScalar(elem_val, scalar_ty, mod, strat)).toIntern();
1513 const elem_val = try val.elemValue(pt, i);
1514 scalar.* = (try floatFromIntScalar(elem_val, scalar_ty, pt, strat)).toIntern();
14931515 }
1494 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1516 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
14951517 .ty = float_ty.toIntern(),
14961518 .storage = .{ .elems = result_data },
1497 } })));
1519 } }));
14981520 }
1499 return floatFromIntScalar(val, float_ty, mod, strat);
1521 return floatFromIntScalar(val, float_ty, pt, strat);
15001522}
15011523
1502pub fn floatFromIntScalar(val: Value, float_ty: Type, mod: *Module, strat: ResolveStrat) !Value {
1524pub fn floatFromIntScalar(val: Value, float_ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) !Value {
1525 const mod = pt.zcu;
15031526 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
1504 .undef => try mod.undefValue(float_ty),
1527 .undef => try pt.undefValue(float_ty),
15051528 .int => |int| switch (int.storage) {
15061529 .big_int => |big_int| {
15071530 const float = bigIntToFloat(big_int.limbs, big_int.positive);
1508 return mod.floatValue(float_ty, float);
1531 return pt.floatValue(float_ty, float);
15091532 },
1510 inline .u64, .i64 => |x| floatFromIntInner(x, float_ty, mod),
1511 .lazy_align => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiAlignmentAdvanced(mod, strat.toLazy())).scalar.toByteUnits() orelse 0, float_ty, mod),
1512 .lazy_size => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiSizeAdvanced(mod, strat.toLazy())).scalar, float_ty, mod),
1533 inline .u64, .i64 => |x| floatFromIntInner(x, float_ty, pt),
1534 .lazy_align => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiAlignmentAdvanced(pt, strat.toLazy())).scalar.toByteUnits() orelse 0, float_ty, pt),
1535 .lazy_size => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiSizeAdvanced(pt, strat.toLazy())).scalar, float_ty, pt),
15131536 },
15141537 else => unreachable,
15151538 };
15161539}
15171540
1518fn floatFromIntInner(x: anytype, dest_ty: Type, mod: *Module) !Value {
1519 const target = mod.getTarget();
1541fn floatFromIntInner(x: anytype, dest_ty: Type, pt: Zcu.PerThread) !Value {
1542 const target = pt.zcu.getTarget();
15201543 const storage: InternPool.Key.Float.Storage = switch (dest_ty.floatBits(target)) {
15211544 16 => .{ .f16 = @floatFromInt(x) },
15221545 32 => .{ .f32 = @floatFromInt(x) },
......@@ -1525,10 +1548,10 @@ fn floatFromIntInner(x: anytype, dest_ty: Type, mod: *Module) !Value {
15251548 128 => .{ .f128 = @floatFromInt(x) },
15261549 else => unreachable,
15271550 };
1528 return Value.fromInterned((try mod.intern(.{ .float = .{
1551 return Value.fromInterned(try pt.intern(.{ .float = .{
15291552 .ty = dest_ty.toIntern(),
15301553 .storage = storage,
1531 } })));
1554 } }));
15321555}
15331556
15341557fn calcLimbLenFloat(scalar: anytype) usize {
......@@ -1551,22 +1574,22 @@ pub fn intAddSat(
15511574 rhs: Value,
15521575 ty: Type,
15531576 arena: Allocator,
1554 mod: *Module,
1577 pt: Zcu.PerThread,
15551578) !Value {
1556 if (ty.zigTypeTag(mod) == .Vector) {
1557 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1558 const scalar_ty = ty.scalarType(mod);
1579 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1580 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1581 const scalar_ty = ty.scalarType(pt.zcu);
15591582 for (result_data, 0..) |*scalar, i| {
1560 const lhs_elem = try lhs.elemValue(mod, i);
1561 const rhs_elem = try rhs.elemValue(mod, i);
1562 scalar.* = (try intAddSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1583 const lhs_elem = try lhs.elemValue(pt, i);
1584 const rhs_elem = try rhs.elemValue(pt, i);
1585 scalar.* = (try intAddSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
15631586 }
1564 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1587 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
15651588 .ty = ty.toIntern(),
15661589 .storage = .{ .elems = result_data },
1567 } })));
1590 } }));
15681591 }
1569 return intAddSatScalar(lhs, rhs, ty, arena, mod);
1592 return intAddSatScalar(lhs, rhs, ty, arena, pt);
15701593}
15711594
15721595/// Supports integers only; asserts neither operand is undefined.
......@@ -1575,24 +1598,24 @@ pub fn intAddSatScalar(
15751598 rhs: Value,
15761599 ty: Type,
15771600 arena: Allocator,
1578 mod: *Module,
1601 pt: Zcu.PerThread,
15791602) !Value {
1580 assert(!lhs.isUndef(mod));
1581 assert(!rhs.isUndef(mod));
1603 assert(!lhs.isUndef(pt.zcu));
1604 assert(!rhs.isUndef(pt.zcu));
15821605
1583 const info = ty.intInfo(mod);
1606 const info = ty.intInfo(pt.zcu);
15841607
15851608 var lhs_space: Value.BigIntSpace = undefined;
15861609 var rhs_space: Value.BigIntSpace = undefined;
1587 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1588 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1610 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1611 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
15891612 const limbs = try arena.alloc(
15901613 std.math.big.Limb,
15911614 std.math.big.int.calcTwosCompLimbCount(info.bits),
15921615 );
15931616 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
15941617 result_bigint.addSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
1595 return mod.intValue_big(ty, result_bigint.toConst());
1618 return pt.intValue_big(ty, result_bigint.toConst());
15961619}
15971620
15981621/// Supports (vectors of) integers only; asserts neither operand is undefined.
......@@ -1601,22 +1624,22 @@ pub fn intSubSat(
16011624 rhs: Value,
16021625 ty: Type,
16031626 arena: Allocator,
1604 mod: *Module,
1627 pt: Zcu.PerThread,
16051628) !Value {
1606 if (ty.zigTypeTag(mod) == .Vector) {
1607 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1608 const scalar_ty = ty.scalarType(mod);
1629 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1630 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1631 const scalar_ty = ty.scalarType(pt.zcu);
16091632 for (result_data, 0..) |*scalar, i| {
1610 const lhs_elem = try lhs.elemValue(mod, i);
1611 const rhs_elem = try rhs.elemValue(mod, i);
1612 scalar.* = (try intSubSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1633 const lhs_elem = try lhs.elemValue(pt, i);
1634 const rhs_elem = try rhs.elemValue(pt, i);
1635 scalar.* = (try intSubSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
16131636 }
1614 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1637 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
16151638 .ty = ty.toIntern(),
16161639 .storage = .{ .elems = result_data },
1617 } })));
1640 } }));
16181641 }
1619 return intSubSatScalar(lhs, rhs, ty, arena, mod);
1642 return intSubSatScalar(lhs, rhs, ty, arena, pt);
16201643}
16211644
16221645/// Supports integers only; asserts neither operand is undefined.
......@@ -1625,24 +1648,24 @@ pub fn intSubSatScalar(
16251648 rhs: Value,
16261649 ty: Type,
16271650 arena: Allocator,
1628 mod: *Module,
1651 pt: Zcu.PerThread,
16291652) !Value {
1630 assert(!lhs.isUndef(mod));
1631 assert(!rhs.isUndef(mod));
1653 assert(!lhs.isUndef(pt.zcu));
1654 assert(!rhs.isUndef(pt.zcu));
16321655
1633 const info = ty.intInfo(mod);
1656 const info = ty.intInfo(pt.zcu);
16341657
16351658 var lhs_space: Value.BigIntSpace = undefined;
16361659 var rhs_space: Value.BigIntSpace = undefined;
1637 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1638 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1660 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1661 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
16391662 const limbs = try arena.alloc(
16401663 std.math.big.Limb,
16411664 std.math.big.int.calcTwosCompLimbCount(info.bits),
16421665 );
16431666 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
16441667 result_bigint.subSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
1645 return mod.intValue_big(ty, result_bigint.toConst());
1668 return pt.intValue_big(ty, result_bigint.toConst());
16461669}
16471670
16481671pub fn intMulWithOverflow(
......@@ -1650,32 +1673,33 @@ pub fn intMulWithOverflow(
16501673 rhs: Value,
16511674 ty: Type,
16521675 arena: Allocator,
1653 mod: *Module,
1676 pt: Zcu.PerThread,
16541677) !OverflowArithmeticResult {
1678 const mod = pt.zcu;
16551679 if (ty.zigTypeTag(mod) == .Vector) {
16561680 const vec_len = ty.vectorLen(mod);
16571681 const overflowed_data = try arena.alloc(InternPool.Index, vec_len);
16581682 const result_data = try arena.alloc(InternPool.Index, vec_len);
16591683 const scalar_ty = ty.scalarType(mod);
16601684 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
1661 const lhs_elem = try lhs.elemValue(mod, i);
1662 const rhs_elem = try rhs.elemValue(mod, i);
1663 const of_math_result = try intMulWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod);
1685 const lhs_elem = try lhs.elemValue(pt, i);
1686 const rhs_elem = try rhs.elemValue(pt, i);
1687 const of_math_result = try intMulWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt);
16641688 of.* = of_math_result.overflow_bit.toIntern();
16651689 scalar.* = of_math_result.wrapped_result.toIntern();
16661690 }
16671691 return OverflowArithmeticResult{
1668 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
1669 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
1692 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
1693 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
16701694 .storage = .{ .elems = overflowed_data },
1671 } }))),
1672 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
1695 } })),
1696 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
16731697 .ty = ty.toIntern(),
16741698 .storage = .{ .elems = result_data },
1675 } }))),
1699 } })),
16761700 };
16771701 }
1678 return intMulWithOverflowScalar(lhs, rhs, ty, arena, mod);
1702 return intMulWithOverflowScalar(lhs, rhs, ty, arena, pt);
16791703}
16801704
16811705pub fn intMulWithOverflowScalar(
......@@ -1683,21 +1707,22 @@ pub fn intMulWithOverflowScalar(
16831707 rhs: Value,
16841708 ty: Type,
16851709 arena: Allocator,
1686 mod: *Module,
1710 pt: Zcu.PerThread,
16871711) !OverflowArithmeticResult {
1712 const mod = pt.zcu;
16881713 const info = ty.intInfo(mod);
16891714
16901715 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
16911716 return .{
1692 .overflow_bit = try mod.undefValue(Type.u1),
1693 .wrapped_result = try mod.undefValue(ty),
1717 .overflow_bit = try pt.undefValue(Type.u1),
1718 .wrapped_result = try pt.undefValue(ty),
16941719 };
16951720 }
16961721
16971722 var lhs_space: Value.BigIntSpace = undefined;
16981723 var rhs_space: Value.BigIntSpace = undefined;
1699 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1700 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1724 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1725 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
17011726 const limbs = try arena.alloc(
17021727 std.math.big.Limb,
17031728 lhs_bigint.limbs.len + rhs_bigint.limbs.len,
......@@ -1715,8 +1740,8 @@ pub fn intMulWithOverflowScalar(
17151740 }
17161741
17171742 return OverflowArithmeticResult{
1718 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
1719 .wrapped_result = try mod.intValue_big(ty, result_bigint.toConst()),
1743 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
1744 .wrapped_result = try pt.intValue_big(ty, result_bigint.toConst()),
17201745 };
17211746}
17221747
......@@ -1726,22 +1751,23 @@ pub fn numberMulWrap(
17261751 rhs: Value,
17271752 ty: Type,
17281753 arena: Allocator,
1729 mod: *Module,
1754 pt: Zcu.PerThread,
17301755) !Value {
1756 const mod = pt.zcu;
17311757 if (ty.zigTypeTag(mod) == .Vector) {
17321758 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
17331759 const scalar_ty = ty.scalarType(mod);
17341760 for (result_data, 0..) |*scalar, i| {
1735 const lhs_elem = try lhs.elemValue(mod, i);
1736 const rhs_elem = try rhs.elemValue(mod, i);
1737 scalar.* = (try numberMulWrapScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1761 const lhs_elem = try lhs.elemValue(pt, i);
1762 const rhs_elem = try rhs.elemValue(pt, i);
1763 scalar.* = (try numberMulWrapScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
17381764 }
1739 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1765 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
17401766 .ty = ty.toIntern(),
17411767 .storage = .{ .elems = result_data },
1742 } })));
1768 } }));
17431769 }
1744 return numberMulWrapScalar(lhs, rhs, ty, arena, mod);
1770 return numberMulWrapScalar(lhs, rhs, ty, arena, pt);
17451771}
17461772
17471773/// Supports both floats and ints; handles undefined.
......@@ -1750,19 +1776,20 @@ pub fn numberMulWrapScalar(
17501776 rhs: Value,
17511777 ty: Type,
17521778 arena: Allocator,
1753 mod: *Module,
1779 pt: Zcu.PerThread,
17541780) !Value {
1781 const mod = pt.zcu;
17551782 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.undef;
17561783
17571784 if (ty.zigTypeTag(mod) == .ComptimeInt) {
1758 return intMul(lhs, rhs, ty, undefined, arena, mod);
1785 return intMul(lhs, rhs, ty, undefined, arena, pt);
17591786 }
17601787
17611788 if (ty.isAnyFloat()) {
1762 return floatMul(lhs, rhs, ty, arena, mod);
1789 return floatMul(lhs, rhs, ty, arena, pt);
17631790 }
17641791
1765 const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, mod);
1792 const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, pt);
17661793 return overflow_result.wrapped_result;
17671794}
17681795
......@@ -1772,22 +1799,22 @@ pub fn intMulSat(
17721799 rhs: Value,
17731800 ty: Type,
17741801 arena: Allocator,
1775 mod: *Module,
1802 pt: Zcu.PerThread,
17761803) !Value {
1777 if (ty.zigTypeTag(mod) == .Vector) {
1778 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1779 const scalar_ty = ty.scalarType(mod);
1804 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1805 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1806 const scalar_ty = ty.scalarType(pt.zcu);
17801807 for (result_data, 0..) |*scalar, i| {
1781 const lhs_elem = try lhs.elemValue(mod, i);
1782 const rhs_elem = try rhs.elemValue(mod, i);
1783 scalar.* = (try intMulSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1808 const lhs_elem = try lhs.elemValue(pt, i);
1809 const rhs_elem = try rhs.elemValue(pt, i);
1810 scalar.* = (try intMulSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
17841811 }
1785 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1812 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
17861813 .ty = ty.toIntern(),
17871814 .storage = .{ .elems = result_data },
1788 } })));
1815 } }));
17891816 }
1790 return intMulSatScalar(lhs, rhs, ty, arena, mod);
1817 return intMulSatScalar(lhs, rhs, ty, arena, pt);
17911818}
17921819
17931820/// Supports (vectors of) integers only; asserts neither operand is undefined.
......@@ -1796,17 +1823,17 @@ pub fn intMulSatScalar(
17961823 rhs: Value,
17971824 ty: Type,
17981825 arena: Allocator,
1799 mod: *Module,
1826 pt: Zcu.PerThread,
18001827) !Value {
1801 assert(!lhs.isUndef(mod));
1802 assert(!rhs.isUndef(mod));
1828 assert(!lhs.isUndef(pt.zcu));
1829 assert(!rhs.isUndef(pt.zcu));
18031830
1804 const info = ty.intInfo(mod);
1831 const info = ty.intInfo(pt.zcu);
18051832
18061833 var lhs_space: Value.BigIntSpace = undefined;
18071834 var rhs_space: Value.BigIntSpace = undefined;
1808 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1809 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1835 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1836 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
18101837 const limbs = try arena.alloc(
18111838 std.math.big.Limb,
18121839 @max(
......@@ -1822,53 +1849,55 @@ pub fn intMulSatScalar(
18221849 );
18231850 result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);
18241851 result_bigint.saturate(result_bigint.toConst(), info.signedness, info.bits);
1825 return mod.intValue_big(ty, result_bigint.toConst());
1852 return pt.intValue_big(ty, result_bigint.toConst());
18261853}
18271854
18281855/// Supports both floats and ints; handles undefined.
1829pub fn numberMax(lhs: Value, rhs: Value, mod: *Module) Value {
1830 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return undef;
1831 if (lhs.isNan(mod)) return rhs;
1832 if (rhs.isNan(mod)) return lhs;
1856pub fn numberMax(lhs: Value, rhs: Value, pt: Zcu.PerThread) Value {
1857 if (lhs.isUndef(pt.zcu) or rhs.isUndef(pt.zcu)) return undef;
1858 if (lhs.isNan(pt.zcu)) return rhs;
1859 if (rhs.isNan(pt.zcu)) return lhs;
18331860
1834 return switch (order(lhs, rhs, mod)) {
1861 return switch (order(lhs, rhs, pt)) {
18351862 .lt => rhs,
18361863 .gt, .eq => lhs,
18371864 };
18381865}
18391866
18401867/// Supports both floats and ints; handles undefined.
1841pub fn numberMin(lhs: Value, rhs: Value, mod: *Module) Value {
1842 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return undef;
1843 if (lhs.isNan(mod)) return rhs;
1844 if (rhs.isNan(mod)) return lhs;
1868pub fn numberMin(lhs: Value, rhs: Value, pt: Zcu.PerThread) Value {
1869 if (lhs.isUndef(pt.zcu) or rhs.isUndef(pt.zcu)) return undef;
1870 if (lhs.isNan(pt.zcu)) return rhs;
1871 if (rhs.isNan(pt.zcu)) return lhs;
18451872
1846 return switch (order(lhs, rhs, mod)) {
1873 return switch (order(lhs, rhs, pt)) {
18471874 .lt => lhs,
18481875 .gt, .eq => rhs,
18491876 };
18501877}
18511878
18521879/// operands must be (vectors of) integers; handles undefined scalars.
1853pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1880pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1881 const mod = pt.zcu;
18541882 if (ty.zigTypeTag(mod) == .Vector) {
18551883 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
18561884 const scalar_ty = ty.scalarType(mod);
18571885 for (result_data, 0..) |*scalar, i| {
1858 const elem_val = try val.elemValue(mod, i);
1859 scalar.* = (try bitwiseNotScalar(elem_val, scalar_ty, arena, mod)).toIntern();
1886 const elem_val = try val.elemValue(pt, i);
1887 scalar.* = (try bitwiseNotScalar(elem_val, scalar_ty, arena, pt)).toIntern();
18601888 }
1861 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1889 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
18621890 .ty = ty.toIntern(),
18631891 .storage = .{ .elems = result_data },
1864 } })));
1892 } }));
18651893 }
1866 return bitwiseNotScalar(val, ty, arena, mod);
1894 return bitwiseNotScalar(val, ty, arena, pt);
18671895}
18681896
18691897/// operands must be integers; handles undefined.
1870pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1871 if (val.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
1898pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1899 const mod = pt.zcu;
1900 if (val.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
18721901 if (ty.toIntern() == .bool_type) return makeBool(!val.toBool());
18731902
18741903 const info = ty.intInfo(mod);
......@@ -1880,7 +1909,7 @@ pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !V
18801909 // TODO is this a performance issue? maybe we should try the operation without
18811910 // resorting to BigInt first.
18821911 var val_space: Value.BigIntSpace = undefined;
1883 const val_bigint = val.toBigInt(&val_space, mod);
1912 const val_bigint = val.toBigInt(&val_space, pt);
18841913 const limbs = try arena.alloc(
18851914 std.math.big.Limb,
18861915 std.math.big.int.calcTwosCompLimbCount(info.bits),
......@@ -1888,29 +1917,31 @@ pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !V
18881917
18891918 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
18901919 result_bigint.bitNotWrap(val_bigint, info.signedness, info.bits);
1891 return mod.intValue_big(ty, result_bigint.toConst());
1920 return pt.intValue_big(ty, result_bigint.toConst());
18921921}
18931922
18941923/// operands must be (vectors of) integers; handles undefined scalars.
1895pub fn bitwiseAnd(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
1924pub fn bitwiseAnd(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
1925 const mod = pt.zcu;
18961926 if (ty.zigTypeTag(mod) == .Vector) {
18971927 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
18981928 const scalar_ty = ty.scalarType(mod);
18991929 for (result_data, 0..) |*scalar, i| {
1900 const lhs_elem = try lhs.elemValue(mod, i);
1901 const rhs_elem = try rhs.elemValue(mod, i);
1902 scalar.* = (try bitwiseAndScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
1930 const lhs_elem = try lhs.elemValue(pt, i);
1931 const rhs_elem = try rhs.elemValue(pt, i);
1932 scalar.* = (try bitwiseAndScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
19031933 }
1904 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1934 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
19051935 .ty = ty.toIntern(),
19061936 .storage = .{ .elems = result_data },
1907 } })));
1937 } }));
19081938 }
1909 return bitwiseAndScalar(lhs, rhs, ty, allocator, mod);
1939 return bitwiseAndScalar(lhs, rhs, ty, allocator, pt);
19101940}
19111941
19121942/// operands must be integers; handles undefined.
1913pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, zcu: *Zcu) !Value {
1943pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1944 const zcu = pt.zcu;
19141945 // If one operand is defined, we turn the other into `0xAA` so the bitwise AND can
19151946 // still zero out some bits.
19161947 // TODO: ideally we'd still like tracking for the undef bits. Related: #19634.
......@@ -1919,9 +1950,9 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19191950 const rhs_undef = orig_rhs.isUndef(zcu);
19201951 break :make_defined switch ((@as(u2, @intFromBool(lhs_undef)) << 1) | @intFromBool(rhs_undef)) {
19211952 0b00 => .{ orig_lhs, orig_rhs },
1922 0b01 => .{ orig_lhs, try intValueAa(ty, arena, zcu) },
1923 0b10 => .{ try intValueAa(ty, arena, zcu), orig_rhs },
1924 0b11 => return zcu.undefValue(ty),
1953 0b01 => .{ orig_lhs, try intValueAa(ty, arena, pt) },
1954 0b10 => .{ try intValueAa(ty, arena, pt), orig_rhs },
1955 0b11 => return pt.undefValue(ty),
19251956 };
19261957 };
19271958
......@@ -1931,8 +1962,8 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19311962 // resorting to BigInt first.
19321963 var lhs_space: Value.BigIntSpace = undefined;
19331964 var rhs_space: Value.BigIntSpace = undefined;
1934 const lhs_bigint = lhs.toBigInt(&lhs_space, zcu);
1935 const rhs_bigint = rhs.toBigInt(&rhs_space, zcu);
1965 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1966 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
19361967 const limbs = try arena.alloc(
19371968 std.math.big.Limb,
19381969 // + 1 for negatives
......@@ -1940,12 +1971,13 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19401971 );
19411972 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
19421973 result_bigint.bitAnd(lhs_bigint, rhs_bigint);
1943 return zcu.intValue_big(ty, result_bigint.toConst());
1974 return pt.intValue_big(ty, result_bigint.toConst());
19441975}
19451976
19461977/// Given an integer or boolean type, creates an value of that with the bit pattern 0xAA.
19471978/// This is used to convert undef values into 0xAA when performing e.g. bitwise operations.
1948fn intValueAa(ty: Type, arena: Allocator, zcu: *Zcu) !Value {
1979fn intValueAa(ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1980 const zcu = pt.zcu;
19491981 if (ty.toIntern() == .bool_type) return Value.true;
19501982 const info = ty.intInfo(zcu);
19511983
......@@ -1958,68 +1990,71 @@ fn intValueAa(ty: Type, arena: Allocator, zcu: *Zcu) !Value {
19581990 );
19591991 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
19601992 result_bigint.readTwosComplement(buf, info.bits, zcu.getTarget().cpu.arch.endian(), info.signedness);
1961 return zcu.intValue_big(ty, result_bigint.toConst());
1993 return pt.intValue_big(ty, result_bigint.toConst());
19621994}
19631995
19641996/// operands must be (vectors of) integers; handles undefined scalars.
1965pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1997pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1998 const mod = pt.zcu;
19661999 if (ty.zigTypeTag(mod) == .Vector) {
19672000 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
19682001 const scalar_ty = ty.scalarType(mod);
19692002 for (result_data, 0..) |*scalar, i| {
1970 const lhs_elem = try lhs.elemValue(mod, i);
1971 const rhs_elem = try rhs.elemValue(mod, i);
1972 scalar.* = (try bitwiseNandScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2003 const lhs_elem = try lhs.elemValue(pt, i);
2004 const rhs_elem = try rhs.elemValue(pt, i);
2005 scalar.* = (try bitwiseNandScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
19732006 }
1974 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2007 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
19752008 .ty = ty.toIntern(),
19762009 .storage = .{ .elems = result_data },
1977 } })));
2010 } }));
19782011 }
1979 return bitwiseNandScalar(lhs, rhs, ty, arena, mod);
2012 return bitwiseNandScalar(lhs, rhs, ty, arena, pt);
19802013}
19812014
19822015/// operands must be integers; handles undefined.
1983pub fn bitwiseNandScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1984 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
2016pub fn bitwiseNandScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2017 const mod = pt.zcu;
2018 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
19852019 if (ty.toIntern() == .bool_type) return makeBool(!(lhs.toBool() and rhs.toBool()));
19862020
1987 const anded = try bitwiseAnd(lhs, rhs, ty, arena, mod);
1988 const all_ones = if (ty.isSignedInt(mod)) try mod.intValue(ty, -1) else try ty.maxIntScalar(mod, ty);
1989 return bitwiseXor(anded, all_ones, ty, arena, mod);
2021 const anded = try bitwiseAnd(lhs, rhs, ty, arena, pt);
2022 const all_ones = if (ty.isSignedInt(mod)) try pt.intValue(ty, -1) else try ty.maxIntScalar(pt, ty);
2023 return bitwiseXor(anded, all_ones, ty, arena, pt);
19902024}
19912025
19922026/// operands must be (vectors of) integers; handles undefined scalars.
1993pub fn bitwiseOr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2027pub fn bitwiseOr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2028 const mod = pt.zcu;
19942029 if (ty.zigTypeTag(mod) == .Vector) {
19952030 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
19962031 const scalar_ty = ty.scalarType(mod);
19972032 for (result_data, 0..) |*scalar, i| {
1998 const lhs_elem = try lhs.elemValue(mod, i);
1999 const rhs_elem = try rhs.elemValue(mod, i);
2000 scalar.* = (try bitwiseOrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2033 const lhs_elem = try lhs.elemValue(pt, i);
2034 const rhs_elem = try rhs.elemValue(pt, i);
2035 scalar.* = (try bitwiseOrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
20012036 }
2002 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2037 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
20032038 .ty = ty.toIntern(),
20042039 .storage = .{ .elems = result_data },
2005 } })));
2040 } }));
20062041 }
2007 return bitwiseOrScalar(lhs, rhs, ty, allocator, mod);
2042 return bitwiseOrScalar(lhs, rhs, ty, allocator, pt);
20082043}
20092044
20102045/// operands must be integers; handles undefined.
2011pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, zcu: *Zcu) !Value {
2046pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
20122047 // If one operand is defined, we turn the other into `0xAA` so the bitwise AND can
20132048 // still zero out some bits.
20142049 // TODO: ideally we'd still like tracking for the undef bits. Related: #19634.
20152050 const lhs: Value, const rhs: Value = make_defined: {
2016 const lhs_undef = orig_lhs.isUndef(zcu);
2017 const rhs_undef = orig_rhs.isUndef(zcu);
2051 const lhs_undef = orig_lhs.isUndef(pt.zcu);
2052 const rhs_undef = orig_rhs.isUndef(pt.zcu);
20182053 break :make_defined switch ((@as(u2, @intFromBool(lhs_undef)) << 1) | @intFromBool(rhs_undef)) {
20192054 0b00 => .{ orig_lhs, orig_rhs },
2020 0b01 => .{ orig_lhs, try intValueAa(ty, arena, zcu) },
2021 0b10 => .{ try intValueAa(ty, arena, zcu), orig_rhs },
2022 0b11 => return zcu.undefValue(ty),
2055 0b01 => .{ orig_lhs, try intValueAa(ty, arena, pt) },
2056 0b10 => .{ try intValueAa(ty, arena, pt), orig_rhs },
2057 0b11 => return pt.undefValue(ty),
20232058 };
20242059 };
20252060
......@@ -2029,46 +2064,48 @@ pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloca
20292064 // resorting to BigInt first.
20302065 var lhs_space: Value.BigIntSpace = undefined;
20312066 var rhs_space: Value.BigIntSpace = undefined;
2032 const lhs_bigint = lhs.toBigInt(&lhs_space, zcu);
2033 const rhs_bigint = rhs.toBigInt(&rhs_space, zcu);
2067 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2068 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
20342069 const limbs = try arena.alloc(
20352070 std.math.big.Limb,
20362071 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
20372072 );
20382073 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
20392074 result_bigint.bitOr(lhs_bigint, rhs_bigint);
2040 return zcu.intValue_big(ty, result_bigint.toConst());
2075 return pt.intValue_big(ty, result_bigint.toConst());
20412076}
20422077
20432078/// operands must be (vectors of) integers; handles undefined scalars.
2044pub fn bitwiseXor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2079pub fn bitwiseXor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2080 const mod = pt.zcu;
20452081 if (ty.zigTypeTag(mod) == .Vector) {
20462082 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
20472083 const scalar_ty = ty.scalarType(mod);
20482084 for (result_data, 0..) |*scalar, i| {
2049 const lhs_elem = try lhs.elemValue(mod, i);
2050 const rhs_elem = try rhs.elemValue(mod, i);
2051 scalar.* = (try bitwiseXorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2085 const lhs_elem = try lhs.elemValue(pt, i);
2086 const rhs_elem = try rhs.elemValue(pt, i);
2087 scalar.* = (try bitwiseXorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
20522088 }
2053 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2089 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
20542090 .ty = ty.toIntern(),
20552091 .storage = .{ .elems = result_data },
2056 } })));
2092 } }));
20572093 }
2058 return bitwiseXorScalar(lhs, rhs, ty, allocator, mod);
2094 return bitwiseXorScalar(lhs, rhs, ty, allocator, pt);
20592095}
20602096
20612097/// operands must be integers; handles undefined.
2062pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
2063 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
2098pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2099 const mod = pt.zcu;
2100 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
20642101 if (ty.toIntern() == .bool_type) return makeBool(lhs.toBool() != rhs.toBool());
20652102
20662103 // TODO is this a performance issue? maybe we should try the operation without
20672104 // resorting to BigInt first.
20682105 var lhs_space: Value.BigIntSpace = undefined;
20692106 var rhs_space: Value.BigIntSpace = undefined;
2070 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2071 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2107 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2108 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
20722109 const limbs = try arena.alloc(
20732110 std.math.big.Limb,
20742111 // + 1 for negatives
......@@ -2076,22 +2113,22 @@ pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod:
20762113 );
20772114 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
20782115 result_bigint.bitXor(lhs_bigint, rhs_bigint);
2079 return mod.intValue_big(ty, result_bigint.toConst());
2116 return pt.intValue_big(ty, result_bigint.toConst());
20802117}
20812118
20822119/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
20832120/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
2084pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, mod: *Module) !Value {
2121pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
20852122 var overflow: usize = undefined;
2086 return intDivInner(lhs, rhs, ty, &overflow, allocator, mod) catch |err| switch (err) {
2123 return intDivInner(lhs, rhs, ty, &overflow, allocator, pt) catch |err| switch (err) {
20872124 error.Overflow => {
2088 const is_vec = ty.isVector(mod);
2125 const is_vec = ty.isVector(pt.zcu);
20892126 overflow_idx.* = if (is_vec) overflow else 0;
2090 const safe_ty = if (is_vec) try mod.vectorType(.{
2091 .len = ty.vectorLen(mod),
2127 const safe_ty = if (is_vec) try pt.vectorType(.{
2128 .len = ty.vectorLen(pt.zcu),
20922129 .child = .comptime_int_type,
20932130 }) else Type.comptime_int;
2094 return intDivInner(lhs, rhs, safe_ty, undefined, allocator, mod) catch |err1| switch (err1) {
2131 return intDivInner(lhs, rhs, safe_ty, undefined, allocator, pt) catch |err1| switch (err1) {
20952132 error.Overflow => unreachable,
20962133 else => |e| return e,
20972134 };
......@@ -2100,14 +2137,14 @@ pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator
21002137 };
21012138}
21022139
2103fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, mod: *Module) !Value {
2104 if (ty.zigTypeTag(mod) == .Vector) {
2105 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2106 const scalar_ty = ty.scalarType(mod);
2140fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2141 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2142 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2143 const scalar_ty = ty.scalarType(pt.zcu);
21072144 for (result_data, 0..) |*scalar, i| {
2108 const lhs_elem = try lhs.elemValue(mod, i);
2109 const rhs_elem = try rhs.elemValue(mod, i);
2110 const val = intDivScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod) catch |err| switch (err) {
2145 const lhs_elem = try lhs.elemValue(pt, i);
2146 const rhs_elem = try rhs.elemValue(pt, i);
2147 const val = intDivScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt) catch |err| switch (err) {
21112148 error.Overflow => {
21122149 overflow_idx.* = i;
21132150 return error.Overflow;
......@@ -2116,21 +2153,21 @@ fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator
21162153 };
21172154 scalar.* = val.toIntern();
21182155 }
2119 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2156 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
21202157 .ty = ty.toIntern(),
21212158 .storage = .{ .elems = result_data },
2122 } })));
2159 } }));
21232160 }
2124 return intDivScalar(lhs, rhs, ty, allocator, mod);
2161 return intDivScalar(lhs, rhs, ty, allocator, pt);
21252162}
21262163
2127pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2164pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
21282165 // TODO is this a performance issue? maybe we should try the operation without
21292166 // resorting to BigInt first.
21302167 var lhs_space: Value.BigIntSpace = undefined;
21312168 var rhs_space: Value.BigIntSpace = undefined;
2132 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2133 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2169 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2170 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
21342171 const limbs_q = try allocator.alloc(
21352172 std.math.big.Limb,
21362173 lhs_bigint.limbs.len,
......@@ -2147,38 +2184,38 @@ pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
21472184 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
21482185 result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
21492186 if (ty.toIntern() != .comptime_int_type) {
2150 const info = ty.intInfo(mod);
2187 const info = ty.intInfo(pt.zcu);
21512188 if (!result_q.toConst().fitsInTwosComp(info.signedness, info.bits)) {
21522189 return error.Overflow;
21532190 }
21542191 }
2155 return mod.intValue_big(ty, result_q.toConst());
2192 return pt.intValue_big(ty, result_q.toConst());
21562193}
21572194
2158pub fn intDivFloor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2159 if (ty.zigTypeTag(mod) == .Vector) {
2160 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2161 const scalar_ty = ty.scalarType(mod);
2195pub fn intDivFloor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2196 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2197 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2198 const scalar_ty = ty.scalarType(pt.zcu);
21622199 for (result_data, 0..) |*scalar, i| {
2163 const lhs_elem = try lhs.elemValue(mod, i);
2164 const rhs_elem = try rhs.elemValue(mod, i);
2165 scalar.* = (try intDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2200 const lhs_elem = try lhs.elemValue(pt, i);
2201 const rhs_elem = try rhs.elemValue(pt, i);
2202 scalar.* = (try intDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
21662203 }
2167 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2204 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
21682205 .ty = ty.toIntern(),
21692206 .storage = .{ .elems = result_data },
2170 } })));
2207 } }));
21712208 }
2172 return intDivFloorScalar(lhs, rhs, ty, allocator, mod);
2209 return intDivFloorScalar(lhs, rhs, ty, allocator, pt);
21732210}
21742211
2175pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2212pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
21762213 // TODO is this a performance issue? maybe we should try the operation without
21772214 // resorting to BigInt first.
21782215 var lhs_space: Value.BigIntSpace = undefined;
21792216 var rhs_space: Value.BigIntSpace = undefined;
2180 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2181 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2217 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2218 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
21822219 const limbs_q = try allocator.alloc(
21832220 std.math.big.Limb,
21842221 lhs_bigint.limbs.len,
......@@ -2194,33 +2231,33 @@ pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator,
21942231 var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
21952232 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
21962233 result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
2197 return mod.intValue_big(ty, result_q.toConst());
2234 return pt.intValue_big(ty, result_q.toConst());
21982235}
21992236
2200pub fn intMod(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2201 if (ty.zigTypeTag(mod) == .Vector) {
2202 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2203 const scalar_ty = ty.scalarType(mod);
2237pub fn intMod(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2238 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2239 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2240 const scalar_ty = ty.scalarType(pt.zcu);
22042241 for (result_data, 0..) |*scalar, i| {
2205 const lhs_elem = try lhs.elemValue(mod, i);
2206 const rhs_elem = try rhs.elemValue(mod, i);
2207 scalar.* = (try intModScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2242 const lhs_elem = try lhs.elemValue(pt, i);
2243 const rhs_elem = try rhs.elemValue(pt, i);
2244 scalar.* = (try intModScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
22082245 }
2209 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2246 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
22102247 .ty = ty.toIntern(),
22112248 .storage = .{ .elems = result_data },
2212 } })));
2249 } }));
22132250 }
2214 return intModScalar(lhs, rhs, ty, allocator, mod);
2251 return intModScalar(lhs, rhs, ty, allocator, pt);
22152252}
22162253
2217pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2254pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
22182255 // TODO is this a performance issue? maybe we should try the operation without
22192256 // resorting to BigInt first.
22202257 var lhs_space: Value.BigIntSpace = undefined;
22212258 var rhs_space: Value.BigIntSpace = undefined;
2222 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2223 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2259 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2260 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
22242261 const limbs_q = try allocator.alloc(
22252262 std.math.big.Limb,
22262263 lhs_bigint.limbs.len,
......@@ -2236,7 +2273,7 @@ pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
22362273 var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
22372274 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
22382275 result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
2239 return mod.intValue_big(ty, result_r.toConst());
2276 return pt.intValue_big(ty, result_r.toConst());
22402277}
22412278
22422279/// Returns true if the value is a floating point type and is NaN. Returns false otherwise.
......@@ -2268,85 +2305,86 @@ pub fn isNegativeInf(val: Value, mod: *const Module) bool {
22682305 };
22692306}
22702307
2271pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
2272 if (float_type.zigTypeTag(mod) == .Vector) {
2273 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2274 const scalar_ty = float_type.scalarType(mod);
2308pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2309 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2310 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2311 const scalar_ty = float_type.scalarType(pt.zcu);
22752312 for (result_data, 0..) |*scalar, i| {
2276 const lhs_elem = try lhs.elemValue(mod, i);
2277 const rhs_elem = try rhs.elemValue(mod, i);
2278 scalar.* = (try floatRemScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2313 const lhs_elem = try lhs.elemValue(pt, i);
2314 const rhs_elem = try rhs.elemValue(pt, i);
2315 scalar.* = (try floatRemScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
22792316 }
2280 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2317 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
22812318 .ty = float_type.toIntern(),
22822319 .storage = .{ .elems = result_data },
2283 } })));
2320 } }));
22842321 }
2285 return floatRemScalar(lhs, rhs, float_type, mod);
2322 return floatRemScalar(lhs, rhs, float_type, pt);
22862323}
22872324
2288pub fn floatRemScalar(lhs: Value, rhs: Value, float_type: Type, mod: *Module) !Value {
2289 const target = mod.getTarget();
2325pub fn floatRemScalar(lhs: Value, rhs: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2326 const target = pt.zcu.getTarget();
22902327 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2291 16 => .{ .f16 = @rem(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2292 32 => .{ .f32 = @rem(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2293 64 => .{ .f64 = @rem(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2294 80 => .{ .f80 = @rem(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2295 128 => .{ .f128 = @rem(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2328 16 => .{ .f16 = @rem(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2329 32 => .{ .f32 = @rem(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2330 64 => .{ .f64 = @rem(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2331 80 => .{ .f80 = @rem(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2332 128 => .{ .f128 = @rem(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
22962333 else => unreachable,
22972334 };
2298 return Value.fromInterned((try mod.intern(.{ .float = .{
2335 return Value.fromInterned(try pt.intern(.{ .float = .{
22992336 .ty = float_type.toIntern(),
23002337 .storage = storage,
2301 } })));
2338 } }));
23022339}
23032340
2304pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
2305 if (float_type.zigTypeTag(mod) == .Vector) {
2306 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2307 const scalar_ty = float_type.scalarType(mod);
2341pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2342 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2343 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2344 const scalar_ty = float_type.scalarType(pt.zcu);
23082345 for (result_data, 0..) |*scalar, i| {
2309 const lhs_elem = try lhs.elemValue(mod, i);
2310 const rhs_elem = try rhs.elemValue(mod, i);
2311 scalar.* = (try floatModScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2346 const lhs_elem = try lhs.elemValue(pt, i);
2347 const rhs_elem = try rhs.elemValue(pt, i);
2348 scalar.* = (try floatModScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
23122349 }
2313 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2350 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
23142351 .ty = float_type.toIntern(),
23152352 .storage = .{ .elems = result_data },
2316 } })));
2353 } }));
23172354 }
2318 return floatModScalar(lhs, rhs, float_type, mod);
2355 return floatModScalar(lhs, rhs, float_type, pt);
23192356}
23202357
2321pub fn floatModScalar(lhs: Value, rhs: Value, float_type: Type, mod: *Module) !Value {
2322 const target = mod.getTarget();
2358pub fn floatModScalar(lhs: Value, rhs: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2359 const target = pt.zcu.getTarget();
23232360 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2324 16 => .{ .f16 = @mod(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2325 32 => .{ .f32 = @mod(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2326 64 => .{ .f64 = @mod(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2327 80 => .{ .f80 = @mod(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2328 128 => .{ .f128 = @mod(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2361 16 => .{ .f16 = @mod(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2362 32 => .{ .f32 = @mod(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2363 64 => .{ .f64 = @mod(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2364 80 => .{ .f80 = @mod(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2365 128 => .{ .f128 = @mod(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
23292366 else => unreachable,
23302367 };
2331 return Value.fromInterned((try mod.intern(.{ .float = .{
2368 return Value.fromInterned(try pt.intern(.{ .float = .{
23322369 .ty = float_type.toIntern(),
23332370 .storage = storage,
2334 } })));
2371 } }));
23352372}
23362373
23372374/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
23382375/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
2339pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, mod: *Module) !Value {
2376pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2377 const mod = pt.zcu;
23402378 var overflow: usize = undefined;
2341 return intMulInner(lhs, rhs, ty, &overflow, allocator, mod) catch |err| switch (err) {
2379 return intMulInner(lhs, rhs, ty, &overflow, allocator, pt) catch |err| switch (err) {
23422380 error.Overflow => {
23432381 const is_vec = ty.isVector(mod);
23442382 overflow_idx.* = if (is_vec) overflow else 0;
2345 const safe_ty = if (is_vec) try mod.vectorType(.{
2383 const safe_ty = if (is_vec) try pt.vectorType(.{
23462384 .len = ty.vectorLen(mod),
23472385 .child = .comptime_int_type,
23482386 }) else Type.comptime_int;
2349 return intMulInner(lhs, rhs, safe_ty, undefined, allocator, mod) catch |err1| switch (err1) {
2387 return intMulInner(lhs, rhs, safe_ty, undefined, allocator, pt) catch |err1| switch (err1) {
23502388 error.Overflow => unreachable,
23512389 else => |e| return e,
23522390 };
......@@ -2355,14 +2393,15 @@ pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator
23552393 };
23562394}
23572395
2358fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, mod: *Module) !Value {
2396fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2397 const mod = pt.zcu;
23592398 if (ty.zigTypeTag(mod) == .Vector) {
23602399 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
23612400 const scalar_ty = ty.scalarType(mod);
23622401 for (result_data, 0..) |*scalar, i| {
2363 const lhs_elem = try lhs.elemValue(mod, i);
2364 const rhs_elem = try rhs.elemValue(mod, i);
2365 const val = intMulScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod) catch |err| switch (err) {
2402 const lhs_elem = try lhs.elemValue(pt, i);
2403 const rhs_elem = try rhs.elemValue(pt, i);
2404 const val = intMulScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt) catch |err| switch (err) {
23662405 error.Overflow => {
23672406 overflow_idx.* = i;
23682407 return error.Overflow;
......@@ -2371,26 +2410,26 @@ fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator
23712410 };
23722411 scalar.* = val.toIntern();
23732412 }
2374 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2413 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
23752414 .ty = ty.toIntern(),
23762415 .storage = .{ .elems = result_data },
2377 } })));
2416 } }));
23782417 }
2379 return intMulScalar(lhs, rhs, ty, allocator, mod);
2418 return intMulScalar(lhs, rhs, ty, allocator, pt);
23802419}
23812420
2382pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2421pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
23832422 if (ty.toIntern() != .comptime_int_type) {
2384 const res = try intMulWithOverflowScalar(lhs, rhs, ty, allocator, mod);
2385 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
2423 const res = try intMulWithOverflowScalar(lhs, rhs, ty, allocator, pt);
2424 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
23862425 return res.wrapped_result;
23872426 }
23882427 // TODO is this a performance issue? maybe we should try the operation without
23892428 // resorting to BigInt first.
23902429 var lhs_space: Value.BigIntSpace = undefined;
23912430 var rhs_space: Value.BigIntSpace = undefined;
2392 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2393 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2431 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2432 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
23942433 const limbs = try allocator.alloc(
23952434 std.math.big.Limb,
23962435 lhs_bigint.limbs.len + rhs_bigint.limbs.len,
......@@ -2402,23 +2441,24 @@ pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
24022441 );
24032442 defer allocator.free(limbs_buffer);
24042443 result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, allocator);
2405 return mod.intValue_big(ty, result_bigint.toConst());
2444 return pt.intValue_big(ty, result_bigint.toConst());
24062445}
24072446
2408pub fn intTrunc(val: Value, ty: Type, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16, mod: *Module) !Value {
2447pub fn intTrunc(val: Value, ty: Type, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16, pt: Zcu.PerThread) !Value {
2448 const mod = pt.zcu;
24092449 if (ty.zigTypeTag(mod) == .Vector) {
24102450 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
24112451 const scalar_ty = ty.scalarType(mod);
24122452 for (result_data, 0..) |*scalar, i| {
2413 const elem_val = try val.elemValue(mod, i);
2414 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, bits, mod)).toIntern();
2453 const elem_val = try val.elemValue(pt, i);
2454 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, bits, pt)).toIntern();
24152455 }
2416 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2456 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24172457 .ty = ty.toIntern(),
24182458 .storage = .{ .elems = result_data },
2419 } })));
2459 } }));
24202460 }
2421 return intTruncScalar(val, ty, allocator, signedness, bits, mod);
2461 return intTruncScalar(val, ty, allocator, signedness, bits, pt);
24222462}
24232463
24242464/// This variant may vectorize on `bits`. Asserts that `bits` is a (vector of) `u16`.
......@@ -2428,22 +2468,22 @@ pub fn intTruncBitsAsValue(
24282468 allocator: Allocator,
24292469 signedness: std.builtin.Signedness,
24302470 bits: Value,
2431 mod: *Module,
2471 pt: Zcu.PerThread,
24322472) !Value {
2433 if (ty.zigTypeTag(mod) == .Vector) {
2434 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2435 const scalar_ty = ty.scalarType(mod);
2473 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2474 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2475 const scalar_ty = ty.scalarType(pt.zcu);
24362476 for (result_data, 0..) |*scalar, i| {
2437 const elem_val = try val.elemValue(mod, i);
2438 const bits_elem = try bits.elemValue(mod, i);
2439 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, @intCast(bits_elem.toUnsignedInt(mod)), mod)).toIntern();
2477 const elem_val = try val.elemValue(pt, i);
2478 const bits_elem = try bits.elemValue(pt, i);
2479 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, @intCast(bits_elem.toUnsignedInt(pt)), pt)).toIntern();
24402480 }
2441 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2481 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24422482 .ty = ty.toIntern(),
24432483 .storage = .{ .elems = result_data },
2444 } })));
2484 } }));
24452485 }
2446 return intTruncScalar(val, ty, allocator, signedness, @intCast(bits.toUnsignedInt(mod)), mod);
2486 return intTruncScalar(val, ty, allocator, signedness, @intCast(bits.toUnsignedInt(pt)), pt);
24472487}
24482488
24492489pub fn intTruncScalar(
......@@ -2452,14 +2492,15 @@ pub fn intTruncScalar(
24522492 allocator: Allocator,
24532493 signedness: std.builtin.Signedness,
24542494 bits: u16,
2455 zcu: *Zcu,
2495 pt: Zcu.PerThread,
24562496) !Value {
2457 if (bits == 0) return zcu.intValue(ty, 0);
2497 const zcu = pt.zcu;
2498 if (bits == 0) return pt.intValue(ty, 0);
24582499
2459 if (val.isUndef(zcu)) return zcu.undefValue(ty);
2500 if (val.isUndef(zcu)) return pt.undefValue(ty);
24602501
24612502 var val_space: Value.BigIntSpace = undefined;
2462 const val_bigint = val.toBigInt(&val_space, zcu);
2503 const val_bigint = val.toBigInt(&val_space, pt);
24632504
24642505 const limbs = try allocator.alloc(
24652506 std.math.big.Limb,
......@@ -2468,32 +2509,33 @@ pub fn intTruncScalar(
24682509 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
24692510
24702511 result_bigint.truncate(val_bigint, signedness, bits);
2471 return zcu.intValue_big(ty, result_bigint.toConst());
2512 return pt.intValue_big(ty, result_bigint.toConst());
24722513}
24732514
2474pub fn shl(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2515pub fn shl(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2516 const mod = pt.zcu;
24752517 if (ty.zigTypeTag(mod) == .Vector) {
24762518 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
24772519 const scalar_ty = ty.scalarType(mod);
24782520 for (result_data, 0..) |*scalar, i| {
2479 const lhs_elem = try lhs.elemValue(mod, i);
2480 const rhs_elem = try rhs.elemValue(mod, i);
2481 scalar.* = (try shlScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2521 const lhs_elem = try lhs.elemValue(pt, i);
2522 const rhs_elem = try rhs.elemValue(pt, i);
2523 scalar.* = (try shlScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
24822524 }
2483 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2525 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24842526 .ty = ty.toIntern(),
24852527 .storage = .{ .elems = result_data },
2486 } })));
2528 } }));
24872529 }
2488 return shlScalar(lhs, rhs, ty, allocator, mod);
2530 return shlScalar(lhs, rhs, ty, allocator, pt);
24892531}
24902532
2491pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2533pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
24922534 // TODO is this a performance issue? maybe we should try the operation without
24932535 // resorting to BigInt first.
24942536 var lhs_space: Value.BigIntSpace = undefined;
2495 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2496 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2537 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2538 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
24972539 const limbs = try allocator.alloc(
24982540 std.math.big.Limb,
24992541 lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
......@@ -2505,11 +2547,11 @@ pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *M
25052547 };
25062548 result_bigint.shiftLeft(lhs_bigint, shift);
25072549 if (ty.toIntern() != .comptime_int_type) {
2508 const int_info = ty.intInfo(mod);
2550 const int_info = ty.intInfo(pt.zcu);
25092551 result_bigint.truncate(result_bigint.toConst(), int_info.signedness, int_info.bits);
25102552 }
25112553
2512 return mod.intValue_big(ty, result_bigint.toConst());
2554 return pt.intValue_big(ty, result_bigint.toConst());
25132555}
25142556
25152557pub fn shlWithOverflow(
......@@ -2517,32 +2559,32 @@ pub fn shlWithOverflow(
25172559 rhs: Value,
25182560 ty: Type,
25192561 allocator: Allocator,
2520 mod: *Module,
2562 pt: Zcu.PerThread,
25212563) !OverflowArithmeticResult {
2522 if (ty.zigTypeTag(mod) == .Vector) {
2523 const vec_len = ty.vectorLen(mod);
2564 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2565 const vec_len = ty.vectorLen(pt.zcu);
25242566 const overflowed_data = try allocator.alloc(InternPool.Index, vec_len);
25252567 const result_data = try allocator.alloc(InternPool.Index, vec_len);
2526 const scalar_ty = ty.scalarType(mod);
2568 const scalar_ty = ty.scalarType(pt.zcu);
25272569 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
2528 const lhs_elem = try lhs.elemValue(mod, i);
2529 const rhs_elem = try rhs.elemValue(mod, i);
2530 const of_math_result = try shlWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod);
2570 const lhs_elem = try lhs.elemValue(pt, i);
2571 const rhs_elem = try rhs.elemValue(pt, i);
2572 const of_math_result = try shlWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt);
25312573 of.* = of_math_result.overflow_bit.toIntern();
25322574 scalar.* = of_math_result.wrapped_result.toIntern();
25332575 }
25342576 return OverflowArithmeticResult{
2535 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
2536 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
2577 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
2578 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
25372579 .storage = .{ .elems = overflowed_data },
2538 } }))),
2539 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
2580 } })),
2581 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
25402582 .ty = ty.toIntern(),
25412583 .storage = .{ .elems = result_data },
2542 } }))),
2584 } })),
25432585 };
25442586 }
2545 return shlWithOverflowScalar(lhs, rhs, ty, allocator, mod);
2587 return shlWithOverflowScalar(lhs, rhs, ty, allocator, pt);
25462588}
25472589
25482590pub fn shlWithOverflowScalar(
......@@ -2550,12 +2592,12 @@ pub fn shlWithOverflowScalar(
25502592 rhs: Value,
25512593 ty: Type,
25522594 allocator: Allocator,
2553 mod: *Module,
2595 pt: Zcu.PerThread,
25542596) !OverflowArithmeticResult {
2555 const info = ty.intInfo(mod);
2597 const info = ty.intInfo(pt.zcu);
25562598 var lhs_space: Value.BigIntSpace = undefined;
2557 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2558 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2599 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2600 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
25592601 const limbs = try allocator.alloc(
25602602 std.math.big.Limb,
25612603 lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
......@@ -2571,8 +2613,8 @@ pub fn shlWithOverflowScalar(
25712613 result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
25722614 }
25732615 return OverflowArithmeticResult{
2574 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
2575 .wrapped_result = try mod.intValue_big(ty, result_bigint.toConst()),
2616 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
2617 .wrapped_result = try pt.intValue_big(ty, result_bigint.toConst()),
25762618 };
25772619}
25782620
......@@ -2581,22 +2623,22 @@ pub fn shlSat(
25812623 rhs: Value,
25822624 ty: Type,
25832625 arena: Allocator,
2584 mod: *Module,
2626 pt: Zcu.PerThread,
25852627) !Value {
2586 if (ty.zigTypeTag(mod) == .Vector) {
2587 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
2588 const scalar_ty = ty.scalarType(mod);
2628 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2629 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2630 const scalar_ty = ty.scalarType(pt.zcu);
25892631 for (result_data, 0..) |*scalar, i| {
2590 const lhs_elem = try lhs.elemValue(mod, i);
2591 const rhs_elem = try rhs.elemValue(mod, i);
2592 scalar.* = (try shlSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2632 const lhs_elem = try lhs.elemValue(pt, i);
2633 const rhs_elem = try rhs.elemValue(pt, i);
2634 scalar.* = (try shlSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
25932635 }
2594 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2636 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25952637 .ty = ty.toIntern(),
25962638 .storage = .{ .elems = result_data },
2597 } })));
2639 } }));
25982640 }
2599 return shlSatScalar(lhs, rhs, ty, arena, mod);
2641 return shlSatScalar(lhs, rhs, ty, arena, pt);
26002642}
26012643
26022644pub fn shlSatScalar(
......@@ -2604,15 +2646,15 @@ pub fn shlSatScalar(
26042646 rhs: Value,
26052647 ty: Type,
26062648 arena: Allocator,
2607 mod: *Module,
2649 pt: Zcu.PerThread,
26082650) !Value {
26092651 // TODO is this a performance issue? maybe we should try the operation without
26102652 // resorting to BigInt first.
2611 const info = ty.intInfo(mod);
2653 const info = ty.intInfo(pt.zcu);
26122654
26132655 var lhs_space: Value.BigIntSpace = undefined;
2614 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2615 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2656 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2657 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
26162658 const limbs = try arena.alloc(
26172659 std.math.big.Limb,
26182660 std.math.big.int.calcTwosCompLimbCount(info.bits) + 1,
......@@ -2623,7 +2665,7 @@ pub fn shlSatScalar(
26232665 .len = undefined,
26242666 };
26252667 result_bigint.shiftLeftSat(lhs_bigint, shift, info.signedness, info.bits);
2626 return mod.intValue_big(ty, result_bigint.toConst());
2668 return pt.intValue_big(ty, result_bigint.toConst());
26272669}
26282670
26292671pub fn shlTrunc(
......@@ -2631,22 +2673,22 @@ pub fn shlTrunc(
26312673 rhs: Value,
26322674 ty: Type,
26332675 arena: Allocator,
2634 mod: *Module,
2676 pt: Zcu.PerThread,
26352677) !Value {
2636 if (ty.zigTypeTag(mod) == .Vector) {
2637 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
2638 const scalar_ty = ty.scalarType(mod);
2678 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2679 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2680 const scalar_ty = ty.scalarType(pt.zcu);
26392681 for (result_data, 0..) |*scalar, i| {
2640 const lhs_elem = try lhs.elemValue(mod, i);
2641 const rhs_elem = try rhs.elemValue(mod, i);
2642 scalar.* = (try shlTruncScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2682 const lhs_elem = try lhs.elemValue(pt, i);
2683 const rhs_elem = try rhs.elemValue(pt, i);
2684 scalar.* = (try shlTruncScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
26432685 }
2644 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2686 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26452687 .ty = ty.toIntern(),
26462688 .storage = .{ .elems = result_data },
2647 } })));
2689 } }));
26482690 }
2649 return shlTruncScalar(lhs, rhs, ty, arena, mod);
2691 return shlTruncScalar(lhs, rhs, ty, arena, pt);
26502692}
26512693
26522694pub fn shlTruncScalar(
......@@ -2654,46 +2696,46 @@ pub fn shlTruncScalar(
26542696 rhs: Value,
26552697 ty: Type,
26562698 arena: Allocator,
2657 mod: *Module,
2699 pt: Zcu.PerThread,
26582700) !Value {
2659 const shifted = try lhs.shl(rhs, ty, arena, mod);
2660 const int_info = ty.intInfo(mod);
2661 const truncated = try shifted.intTrunc(ty, arena, int_info.signedness, int_info.bits, mod);
2701 const shifted = try lhs.shl(rhs, ty, arena, pt);
2702 const int_info = ty.intInfo(pt.zcu);
2703 const truncated = try shifted.intTrunc(ty, arena, int_info.signedness, int_info.bits, pt);
26622704 return truncated;
26632705}
26642706
2665pub fn shr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2666 if (ty.zigTypeTag(mod) == .Vector) {
2667 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2668 const scalar_ty = ty.scalarType(mod);
2707pub fn shr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2708 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2709 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2710 const scalar_ty = ty.scalarType(pt.zcu);
26692711 for (result_data, 0..) |*scalar, i| {
2670 const lhs_elem = try lhs.elemValue(mod, i);
2671 const rhs_elem = try rhs.elemValue(mod, i);
2672 scalar.* = (try shrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2712 const lhs_elem = try lhs.elemValue(pt, i);
2713 const rhs_elem = try rhs.elemValue(pt, i);
2714 scalar.* = (try shrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
26732715 }
2674 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2716 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26752717 .ty = ty.toIntern(),
26762718 .storage = .{ .elems = result_data },
2677 } })));
2719 } }));
26782720 }
2679 return shrScalar(lhs, rhs, ty, allocator, mod);
2721 return shrScalar(lhs, rhs, ty, allocator, pt);
26802722}
26812723
2682pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2724pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
26832725 // TODO is this a performance issue? maybe we should try the operation without
26842726 // resorting to BigInt first.
26852727 var lhs_space: Value.BigIntSpace = undefined;
2686 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2687 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2728 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2729 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
26882730
26892731 const result_limbs = lhs_bigint.limbs.len -| (shift / (@sizeOf(std.math.big.Limb) * 8));
26902732 if (result_limbs == 0) {
26912733 // The shift is enough to remove all the bits from the number, which means the
26922734 // result is 0 or -1 depending on the sign.
26932735 if (lhs_bigint.positive) {
2694 return mod.intValue(ty, 0);
2736 return pt.intValue(ty, 0);
26952737 } else {
2696 return mod.intValue(ty, -1);
2738 return pt.intValue(ty, -1);
26972739 }
26982740 }
26992741
......@@ -2707,48 +2749,45 @@ pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *M
27072749 .len = undefined,
27082750 };
27092751 result_bigint.shiftRight(lhs_bigint, shift);
2710 return mod.intValue_big(ty, result_bigint.toConst());
2752 return pt.intValue_big(ty, result_bigint.toConst());
27112753}
27122754
27132755pub fn floatNeg(
27142756 val: Value,
27152757 float_type: Type,
27162758 arena: Allocator,
2717 mod: *Module,
2759 pt: Zcu.PerThread,
27182760) !Value {
2761 const mod = pt.zcu;
27192762 if (float_type.zigTypeTag(mod) == .Vector) {
27202763 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
27212764 const scalar_ty = float_type.scalarType(mod);
27222765 for (result_data, 0..) |*scalar, i| {
2723 const elem_val = try val.elemValue(mod, i);
2724 scalar.* = (try floatNegScalar(elem_val, scalar_ty, mod)).toIntern();
2766 const elem_val = try val.elemValue(pt, i);
2767 scalar.* = (try floatNegScalar(elem_val, scalar_ty, pt)).toIntern();
27252768 }
2726 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2769 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
27272770 .ty = float_type.toIntern(),
27282771 .storage = .{ .elems = result_data },
2729 } })));
2772 } }));
27302773 }
2731 return floatNegScalar(val, float_type, mod);
2774 return floatNegScalar(val, float_type, pt);
27322775}
27332776
2734pub fn floatNegScalar(
2735 val: Value,
2736 float_type: Type,
2737 mod: *Module,
2738) !Value {
2739 const target = mod.getTarget();
2777pub fn floatNegScalar(val: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2778 const target = pt.zcu.getTarget();
27402779 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2741 16 => .{ .f16 = -val.toFloat(f16, mod) },
2742 32 => .{ .f32 = -val.toFloat(f32, mod) },
2743 64 => .{ .f64 = -val.toFloat(f64, mod) },
2744 80 => .{ .f80 = -val.toFloat(f80, mod) },
2745 128 => .{ .f128 = -val.toFloat(f128, mod) },
2780 16 => .{ .f16 = -val.toFloat(f16, pt) },
2781 32 => .{ .f32 = -val.toFloat(f32, pt) },
2782 64 => .{ .f64 = -val.toFloat(f64, pt) },
2783 80 => .{ .f80 = -val.toFloat(f80, pt) },
2784 128 => .{ .f128 = -val.toFloat(f128, pt) },
27462785 else => unreachable,
27472786 };
2748 return Value.fromInterned((try mod.intern(.{ .float = .{
2787 return Value.fromInterned(try pt.intern(.{ .float = .{
27492788 .ty = float_type.toIntern(),
27502789 .storage = storage,
2751 } })));
2790 } }));
27522791}
27532792
27542793pub fn floatAdd(
......@@ -2756,43 +2795,45 @@ pub fn floatAdd(
27562795 rhs: Value,
27572796 float_type: Type,
27582797 arena: Allocator,
2759 mod: *Module,
2798 pt: Zcu.PerThread,
27602799) !Value {
2800 const mod = pt.zcu;
27612801 if (float_type.zigTypeTag(mod) == .Vector) {
27622802 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
27632803 const scalar_ty = float_type.scalarType(mod);
27642804 for (result_data, 0..) |*scalar, i| {
2765 const lhs_elem = try lhs.elemValue(mod, i);
2766 const rhs_elem = try rhs.elemValue(mod, i);
2767 scalar.* = (try floatAddScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2805 const lhs_elem = try lhs.elemValue(pt, i);
2806 const rhs_elem = try rhs.elemValue(pt, i);
2807 scalar.* = (try floatAddScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
27682808 }
2769 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2809 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
27702810 .ty = float_type.toIntern(),
27712811 .storage = .{ .elems = result_data },
2772 } })));
2812 } }));
27732813 }
2774 return floatAddScalar(lhs, rhs, float_type, mod);
2814 return floatAddScalar(lhs, rhs, float_type, pt);
27752815}
27762816
27772817pub fn floatAddScalar(
27782818 lhs: Value,
27792819 rhs: Value,
27802820 float_type: Type,
2781 mod: *Module,
2821 pt: Zcu.PerThread,
27822822) !Value {
2823 const mod = pt.zcu;
27832824 const target = mod.getTarget();
27842825 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2785 16 => .{ .f16 = lhs.toFloat(f16, mod) + rhs.toFloat(f16, mod) },
2786 32 => .{ .f32 = lhs.toFloat(f32, mod) + rhs.toFloat(f32, mod) },
2787 64 => .{ .f64 = lhs.toFloat(f64, mod) + rhs.toFloat(f64, mod) },
2788 80 => .{ .f80 = lhs.toFloat(f80, mod) + rhs.toFloat(f80, mod) },
2789 128 => .{ .f128 = lhs.toFloat(f128, mod) + rhs.toFloat(f128, mod) },
2826 16 => .{ .f16 = lhs.toFloat(f16, pt) + rhs.toFloat(f16, pt) },
2827 32 => .{ .f32 = lhs.toFloat(f32, pt) + rhs.toFloat(f32, pt) },
2828 64 => .{ .f64 = lhs.toFloat(f64, pt) + rhs.toFloat(f64, pt) },
2829 80 => .{ .f80 = lhs.toFloat(f80, pt) + rhs.toFloat(f80, pt) },
2830 128 => .{ .f128 = lhs.toFloat(f128, pt) + rhs.toFloat(f128, pt) },
27902831 else => unreachable,
27912832 };
2792 return Value.fromInterned((try mod.intern(.{ .float = .{
2833 return Value.fromInterned(try pt.intern(.{ .float = .{
27932834 .ty = float_type.toIntern(),
27942835 .storage = storage,
2795 } })));
2836 } }));
27962837}
27972838
27982839pub fn floatSub(
......@@ -2800,43 +2841,45 @@ pub fn floatSub(
28002841 rhs: Value,
28012842 float_type: Type,
28022843 arena: Allocator,
2803 mod: *Module,
2844 pt: Zcu.PerThread,
28042845) !Value {
2846 const mod = pt.zcu;
28052847 if (float_type.zigTypeTag(mod) == .Vector) {
28062848 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
28072849 const scalar_ty = float_type.scalarType(mod);
28082850 for (result_data, 0..) |*scalar, i| {
2809 const lhs_elem = try lhs.elemValue(mod, i);
2810 const rhs_elem = try rhs.elemValue(mod, i);
2811 scalar.* = (try floatSubScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2851 const lhs_elem = try lhs.elemValue(pt, i);
2852 const rhs_elem = try rhs.elemValue(pt, i);
2853 scalar.* = (try floatSubScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
28122854 }
2813 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2855 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
28142856 .ty = float_type.toIntern(),
28152857 .storage = .{ .elems = result_data },
2816 } })));
2858 } }));
28172859 }
2818 return floatSubScalar(lhs, rhs, float_type, mod);
2860 return floatSubScalar(lhs, rhs, float_type, pt);
28192861}
28202862
28212863pub fn floatSubScalar(
28222864 lhs: Value,
28232865 rhs: Value,
28242866 float_type: Type,
2825 mod: *Module,
2867 pt: Zcu.PerThread,
28262868) !Value {
2869 const mod = pt.zcu;
28272870 const target = mod.getTarget();
28282871 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2829 16 => .{ .f16 = lhs.toFloat(f16, mod) - rhs.toFloat(f16, mod) },
2830 32 => .{ .f32 = lhs.toFloat(f32, mod) - rhs.toFloat(f32, mod) },
2831 64 => .{ .f64 = lhs.toFloat(f64, mod) - rhs.toFloat(f64, mod) },
2832 80 => .{ .f80 = lhs.toFloat(f80, mod) - rhs.toFloat(f80, mod) },
2833 128 => .{ .f128 = lhs.toFloat(f128, mod) - rhs.toFloat(f128, mod) },
2872 16 => .{ .f16 = lhs.toFloat(f16, pt) - rhs.toFloat(f16, pt) },
2873 32 => .{ .f32 = lhs.toFloat(f32, pt) - rhs.toFloat(f32, pt) },
2874 64 => .{ .f64 = lhs.toFloat(f64, pt) - rhs.toFloat(f64, pt) },
2875 80 => .{ .f80 = lhs.toFloat(f80, pt) - rhs.toFloat(f80, pt) },
2876 128 => .{ .f128 = lhs.toFloat(f128, pt) - rhs.toFloat(f128, pt) },
28342877 else => unreachable,
28352878 };
2836 return Value.fromInterned((try mod.intern(.{ .float = .{
2879 return Value.fromInterned(try pt.intern(.{ .float = .{
28372880 .ty = float_type.toIntern(),
28382881 .storage = storage,
2839 } })));
2882 } }));
28402883}
28412884
28422885pub fn floatDiv(
......@@ -2844,43 +2887,43 @@ pub fn floatDiv(
28442887 rhs: Value,
28452888 float_type: Type,
28462889 arena: Allocator,
2847 mod: *Module,
2890 pt: Zcu.PerThread,
28482891) !Value {
2849 if (float_type.zigTypeTag(mod) == .Vector) {
2850 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2851 const scalar_ty = float_type.scalarType(mod);
2892 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2893 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2894 const scalar_ty = float_type.scalarType(pt.zcu);
28522895 for (result_data, 0..) |*scalar, i| {
2853 const lhs_elem = try lhs.elemValue(mod, i);
2854 const rhs_elem = try rhs.elemValue(mod, i);
2855 scalar.* = (try floatDivScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2896 const lhs_elem = try lhs.elemValue(pt, i);
2897 const rhs_elem = try rhs.elemValue(pt, i);
2898 scalar.* = (try floatDivScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
28562899 }
2857 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2900 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
28582901 .ty = float_type.toIntern(),
28592902 .storage = .{ .elems = result_data },
2860 } })));
2903 } }));
28612904 }
2862 return floatDivScalar(lhs, rhs, float_type, mod);
2905 return floatDivScalar(lhs, rhs, float_type, pt);
28632906}
28642907
28652908pub fn floatDivScalar(
28662909 lhs: Value,
28672910 rhs: Value,
28682911 float_type: Type,
2869 mod: *Module,
2912 pt: Zcu.PerThread,
28702913) !Value {
2871 const target = mod.getTarget();
2914 const target = pt.zcu.getTarget();
28722915 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2873 16 => .{ .f16 = lhs.toFloat(f16, mod) / rhs.toFloat(f16, mod) },
2874 32 => .{ .f32 = lhs.toFloat(f32, mod) / rhs.toFloat(f32, mod) },
2875 64 => .{ .f64 = lhs.toFloat(f64, mod) / rhs.toFloat(f64, mod) },
2876 80 => .{ .f80 = lhs.toFloat(f80, mod) / rhs.toFloat(f80, mod) },
2877 128 => .{ .f128 = lhs.toFloat(f128, mod) / rhs.toFloat(f128, mod) },
2916 16 => .{ .f16 = lhs.toFloat(f16, pt) / rhs.toFloat(f16, pt) },
2917 32 => .{ .f32 = lhs.toFloat(f32, pt) / rhs.toFloat(f32, pt) },
2918 64 => .{ .f64 = lhs.toFloat(f64, pt) / rhs.toFloat(f64, pt) },
2919 80 => .{ .f80 = lhs.toFloat(f80, pt) / rhs.toFloat(f80, pt) },
2920 128 => .{ .f128 = lhs.toFloat(f128, pt) / rhs.toFloat(f128, pt) },
28782921 else => unreachable,
28792922 };
2880 return Value.fromInterned((try mod.intern(.{ .float = .{
2923 return Value.fromInterned(try pt.intern(.{ .float = .{
28812924 .ty = float_type.toIntern(),
28822925 .storage = storage,
2883 } })));
2926 } }));
28842927}
28852928
28862929pub fn floatDivFloor(
......@@ -2888,43 +2931,43 @@ pub fn floatDivFloor(
28882931 rhs: Value,
28892932 float_type: Type,
28902933 arena: Allocator,
2891 mod: *Module,
2934 pt: Zcu.PerThread,
28922935) !Value {
2893 if (float_type.zigTypeTag(mod) == .Vector) {
2894 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2895 const scalar_ty = float_type.scalarType(mod);
2936 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2937 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2938 const scalar_ty = float_type.scalarType(pt.zcu);
28962939 for (result_data, 0..) |*scalar, i| {
2897 const lhs_elem = try lhs.elemValue(mod, i);
2898 const rhs_elem = try rhs.elemValue(mod, i);
2899 scalar.* = (try floatDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2940 const lhs_elem = try lhs.elemValue(pt, i);
2941 const rhs_elem = try rhs.elemValue(pt, i);
2942 scalar.* = (try floatDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29002943 }
2901 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2944 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29022945 .ty = float_type.toIntern(),
29032946 .storage = .{ .elems = result_data },
2904 } })));
2947 } }));
29052948 }
2906 return floatDivFloorScalar(lhs, rhs, float_type, mod);
2949 return floatDivFloorScalar(lhs, rhs, float_type, pt);
29072950}
29082951
29092952pub fn floatDivFloorScalar(
29102953 lhs: Value,
29112954 rhs: Value,
29122955 float_type: Type,
2913 mod: *Module,
2956 pt: Zcu.PerThread,
29142957) !Value {
2915 const target = mod.getTarget();
2958 const target = pt.zcu.getTarget();
29162959 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2917 16 => .{ .f16 = @divFloor(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2918 32 => .{ .f32 = @divFloor(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2919 64 => .{ .f64 = @divFloor(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2920 80 => .{ .f80 = @divFloor(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2921 128 => .{ .f128 = @divFloor(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2960 16 => .{ .f16 = @divFloor(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2961 32 => .{ .f32 = @divFloor(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2962 64 => .{ .f64 = @divFloor(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2963 80 => .{ .f80 = @divFloor(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2964 128 => .{ .f128 = @divFloor(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
29222965 else => unreachable,
29232966 };
2924 return Value.fromInterned((try mod.intern(.{ .float = .{
2967 return Value.fromInterned(try pt.intern(.{ .float = .{
29252968 .ty = float_type.toIntern(),
29262969 .storage = storage,
2927 } })));
2970 } }));
29282971}
29292972
29302973pub fn floatDivTrunc(
......@@ -2932,43 +2975,43 @@ pub fn floatDivTrunc(
29322975 rhs: Value,
29332976 float_type: Type,
29342977 arena: Allocator,
2935 mod: *Module,
2978 pt: Zcu.PerThread,
29362979) !Value {
2937 if (float_type.zigTypeTag(mod) == .Vector) {
2938 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2939 const scalar_ty = float_type.scalarType(mod);
2980 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2981 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2982 const scalar_ty = float_type.scalarType(pt.zcu);
29402983 for (result_data, 0..) |*scalar, i| {
2941 const lhs_elem = try lhs.elemValue(mod, i);
2942 const rhs_elem = try rhs.elemValue(mod, i);
2943 scalar.* = (try floatDivTruncScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2984 const lhs_elem = try lhs.elemValue(pt, i);
2985 const rhs_elem = try rhs.elemValue(pt, i);
2986 scalar.* = (try floatDivTruncScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29442987 }
2945 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2988 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29462989 .ty = float_type.toIntern(),
29472990 .storage = .{ .elems = result_data },
2948 } })));
2991 } }));
29492992 }
2950 return floatDivTruncScalar(lhs, rhs, float_type, mod);
2993 return floatDivTruncScalar(lhs, rhs, float_type, pt);
29512994}
29522995
29532996pub fn floatDivTruncScalar(
29542997 lhs: Value,
29552998 rhs: Value,
29562999 float_type: Type,
2957 mod: *Module,
3000 pt: Zcu.PerThread,
29583001) !Value {
2959 const target = mod.getTarget();
3002 const target = pt.zcu.getTarget();
29603003 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2961 16 => .{ .f16 = @divTrunc(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2962 32 => .{ .f32 = @divTrunc(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2963 64 => .{ .f64 = @divTrunc(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2964 80 => .{ .f80 = @divTrunc(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2965 128 => .{ .f128 = @divTrunc(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
3004 16 => .{ .f16 = @divTrunc(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
3005 32 => .{ .f32 = @divTrunc(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
3006 64 => .{ .f64 = @divTrunc(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
3007 80 => .{ .f80 = @divTrunc(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
3008 128 => .{ .f128 = @divTrunc(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
29663009 else => unreachable,
29673010 };
2968 return Value.fromInterned((try mod.intern(.{ .float = .{
3011 return Value.fromInterned(try pt.intern(.{ .float = .{
29693012 .ty = float_type.toIntern(),
29703013 .storage = storage,
2971 } })));
3014 } }));
29723015}
29733016
29743017pub fn floatMul(
......@@ -2976,510 +3019,539 @@ pub fn floatMul(
29763019 rhs: Value,
29773020 float_type: Type,
29783021 arena: Allocator,
2979 mod: *Module,
3022 pt: Zcu.PerThread,
29803023) !Value {
3024 const mod = pt.zcu;
29813025 if (float_type.zigTypeTag(mod) == .Vector) {
29823026 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
29833027 const scalar_ty = float_type.scalarType(mod);
29843028 for (result_data, 0..) |*scalar, i| {
2985 const lhs_elem = try lhs.elemValue(mod, i);
2986 const rhs_elem = try rhs.elemValue(mod, i);
2987 scalar.* = (try floatMulScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
3029 const lhs_elem = try lhs.elemValue(pt, i);
3030 const rhs_elem = try rhs.elemValue(pt, i);
3031 scalar.* = (try floatMulScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29883032 }
2989 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3033 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29903034 .ty = float_type.toIntern(),
29913035 .storage = .{ .elems = result_data },
2992 } })));
3036 } }));
29933037 }
2994 return floatMulScalar(lhs, rhs, float_type, mod);
3038 return floatMulScalar(lhs, rhs, float_type, pt);
29953039}
29963040
29973041pub fn floatMulScalar(
29983042 lhs: Value,
29993043 rhs: Value,
30003044 float_type: Type,
3001 mod: *Module,
3045 pt: Zcu.PerThread,
30023046) !Value {
3047 const mod = pt.zcu;
30033048 const target = mod.getTarget();
30043049 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3005 16 => .{ .f16 = lhs.toFloat(f16, mod) * rhs.toFloat(f16, mod) },
3006 32 => .{ .f32 = lhs.toFloat(f32, mod) * rhs.toFloat(f32, mod) },
3007 64 => .{ .f64 = lhs.toFloat(f64, mod) * rhs.toFloat(f64, mod) },
3008 80 => .{ .f80 = lhs.toFloat(f80, mod) * rhs.toFloat(f80, mod) },
3009 128 => .{ .f128 = lhs.toFloat(f128, mod) * rhs.toFloat(f128, mod) },
3050 16 => .{ .f16 = lhs.toFloat(f16, pt) * rhs.toFloat(f16, pt) },
3051 32 => .{ .f32 = lhs.toFloat(f32, pt) * rhs.toFloat(f32, pt) },
3052 64 => .{ .f64 = lhs.toFloat(f64, pt) * rhs.toFloat(f64, pt) },
3053 80 => .{ .f80 = lhs.toFloat(f80, pt) * rhs.toFloat(f80, pt) },
3054 128 => .{ .f128 = lhs.toFloat(f128, pt) * rhs.toFloat(f128, pt) },
30103055 else => unreachable,
30113056 };
3012 return Value.fromInterned((try mod.intern(.{ .float = .{
3057 return Value.fromInterned(try pt.intern(.{ .float = .{
30133058 .ty = float_type.toIntern(),
30143059 .storage = storage,
3015 } })));
3060 } }));
30163061}
30173062
3018pub fn sqrt(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3019 if (float_type.zigTypeTag(mod) == .Vector) {
3020 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
3021 const scalar_ty = float_type.scalarType(mod);
3063pub fn sqrt(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3064 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
3065 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
3066 const scalar_ty = float_type.scalarType(pt.zcu);
30223067 for (result_data, 0..) |*scalar, i| {
3023 const elem_val = try val.elemValue(mod, i);
3024 scalar.* = (try sqrtScalar(elem_val, scalar_ty, mod)).toIntern();
3068 const elem_val = try val.elemValue(pt, i);
3069 scalar.* = (try sqrtScalar(elem_val, scalar_ty, pt)).toIntern();
30253070 }
3026 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3071 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30273072 .ty = float_type.toIntern(),
30283073 .storage = .{ .elems = result_data },
3029 } })));
3074 } }));
30303075 }
3031 return sqrtScalar(val, float_type, mod);
3076 return sqrtScalar(val, float_type, pt);
30323077}
30333078
3034pub fn sqrtScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3079pub fn sqrtScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3080 const mod = pt.zcu;
30353081 const target = mod.getTarget();
30363082 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3037 16 => .{ .f16 = @sqrt(val.toFloat(f16, mod)) },
3038 32 => .{ .f32 = @sqrt(val.toFloat(f32, mod)) },
3039 64 => .{ .f64 = @sqrt(val.toFloat(f64, mod)) },
3040 80 => .{ .f80 = @sqrt(val.toFloat(f80, mod)) },
3041 128 => .{ .f128 = @sqrt(val.toFloat(f128, mod)) },
3083 16 => .{ .f16 = @sqrt(val.toFloat(f16, pt)) },
3084 32 => .{ .f32 = @sqrt(val.toFloat(f32, pt)) },
3085 64 => .{ .f64 = @sqrt(val.toFloat(f64, pt)) },
3086 80 => .{ .f80 = @sqrt(val.toFloat(f80, pt)) },
3087 128 => .{ .f128 = @sqrt(val.toFloat(f128, pt)) },
30423088 else => unreachable,
30433089 };
3044 return Value.fromInterned((try mod.intern(.{ .float = .{
3090 return Value.fromInterned(try pt.intern(.{ .float = .{
30453091 .ty = float_type.toIntern(),
30463092 .storage = storage,
3047 } })));
3093 } }));
30483094}
30493095
3050pub fn sin(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3096pub fn sin(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3097 const mod = pt.zcu;
30513098 if (float_type.zigTypeTag(mod) == .Vector) {
30523099 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
30533100 const scalar_ty = float_type.scalarType(mod);
30543101 for (result_data, 0..) |*scalar, i| {
3055 const elem_val = try val.elemValue(mod, i);
3056 scalar.* = (try sinScalar(elem_val, scalar_ty, mod)).toIntern();
3102 const elem_val = try val.elemValue(pt, i);
3103 scalar.* = (try sinScalar(elem_val, scalar_ty, pt)).toIntern();
30573104 }
3058 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3105 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30593106 .ty = float_type.toIntern(),
30603107 .storage = .{ .elems = result_data },
3061 } })));
3108 } }));
30623109 }
3063 return sinScalar(val, float_type, mod);
3110 return sinScalar(val, float_type, pt);
30643111}
30653112
3066pub fn sinScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3113pub fn sinScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3114 const mod = pt.zcu;
30673115 const target = mod.getTarget();
30683116 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3069 16 => .{ .f16 = @sin(val.toFloat(f16, mod)) },
3070 32 => .{ .f32 = @sin(val.toFloat(f32, mod)) },
3071 64 => .{ .f64 = @sin(val.toFloat(f64, mod)) },
3072 80 => .{ .f80 = @sin(val.toFloat(f80, mod)) },
3073 128 => .{ .f128 = @sin(val.toFloat(f128, mod)) },
3117 16 => .{ .f16 = @sin(val.toFloat(f16, pt)) },
3118 32 => .{ .f32 = @sin(val.toFloat(f32, pt)) },
3119 64 => .{ .f64 = @sin(val.toFloat(f64, pt)) },
3120 80 => .{ .f80 = @sin(val.toFloat(f80, pt)) },
3121 128 => .{ .f128 = @sin(val.toFloat(f128, pt)) },
30743122 else => unreachable,
30753123 };
3076 return Value.fromInterned((try mod.intern(.{ .float = .{
3124 return Value.fromInterned(try pt.intern(.{ .float = .{
30773125 .ty = float_type.toIntern(),
30783126 .storage = storage,
3079 } })));
3127 } }));
30803128}
30813129
3082pub fn cos(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3130pub fn cos(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3131 const mod = pt.zcu;
30833132 if (float_type.zigTypeTag(mod) == .Vector) {
30843133 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
30853134 const scalar_ty = float_type.scalarType(mod);
30863135 for (result_data, 0..) |*scalar, i| {
3087 const elem_val = try val.elemValue(mod, i);
3088 scalar.* = (try cosScalar(elem_val, scalar_ty, mod)).toIntern();
3136 const elem_val = try val.elemValue(pt, i);
3137 scalar.* = (try cosScalar(elem_val, scalar_ty, pt)).toIntern();
30893138 }
3090 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3139 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30913140 .ty = float_type.toIntern(),
30923141 .storage = .{ .elems = result_data },
3093 } })));
3142 } }));
30943143 }
3095 return cosScalar(val, float_type, mod);
3144 return cosScalar(val, float_type, pt);
30963145}
30973146
3098pub fn cosScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3147pub fn cosScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3148 const mod = pt.zcu;
30993149 const target = mod.getTarget();
31003150 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3101 16 => .{ .f16 = @cos(val.toFloat(f16, mod)) },
3102 32 => .{ .f32 = @cos(val.toFloat(f32, mod)) },
3103 64 => .{ .f64 = @cos(val.toFloat(f64, mod)) },
3104 80 => .{ .f80 = @cos(val.toFloat(f80, mod)) },
3105 128 => .{ .f128 = @cos(val.toFloat(f128, mod)) },
3151 16 => .{ .f16 = @cos(val.toFloat(f16, pt)) },
3152 32 => .{ .f32 = @cos(val.toFloat(f32, pt)) },
3153 64 => .{ .f64 = @cos(val.toFloat(f64, pt)) },
3154 80 => .{ .f80 = @cos(val.toFloat(f80, pt)) },
3155 128 => .{ .f128 = @cos(val.toFloat(f128, pt)) },
31063156 else => unreachable,
31073157 };
3108 return Value.fromInterned((try mod.intern(.{ .float = .{
3158 return Value.fromInterned(try pt.intern(.{ .float = .{
31093159 .ty = float_type.toIntern(),
31103160 .storage = storage,
3111 } })));
3161 } }));
31123162}
31133163
3114pub fn tan(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3164pub fn tan(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3165 const mod = pt.zcu;
31153166 if (float_type.zigTypeTag(mod) == .Vector) {
31163167 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31173168 const scalar_ty = float_type.scalarType(mod);
31183169 for (result_data, 0..) |*scalar, i| {
3119 const elem_val = try val.elemValue(mod, i);
3120 scalar.* = (try tanScalar(elem_val, scalar_ty, mod)).toIntern();
3170 const elem_val = try val.elemValue(pt, i);
3171 scalar.* = (try tanScalar(elem_val, scalar_ty, pt)).toIntern();
31213172 }
3122 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3173 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31233174 .ty = float_type.toIntern(),
31243175 .storage = .{ .elems = result_data },
3125 } })));
3176 } }));
31263177 }
3127 return tanScalar(val, float_type, mod);
3178 return tanScalar(val, float_type, pt);
31283179}
31293180
3130pub fn tanScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3181pub fn tanScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3182 const mod = pt.zcu;
31313183 const target = mod.getTarget();
31323184 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3133 16 => .{ .f16 = @tan(val.toFloat(f16, mod)) },
3134 32 => .{ .f32 = @tan(val.toFloat(f32, mod)) },
3135 64 => .{ .f64 = @tan(val.toFloat(f64, mod)) },
3136 80 => .{ .f80 = @tan(val.toFloat(f80, mod)) },
3137 128 => .{ .f128 = @tan(val.toFloat(f128, mod)) },
3185 16 => .{ .f16 = @tan(val.toFloat(f16, pt)) },
3186 32 => .{ .f32 = @tan(val.toFloat(f32, pt)) },
3187 64 => .{ .f64 = @tan(val.toFloat(f64, pt)) },
3188 80 => .{ .f80 = @tan(val.toFloat(f80, pt)) },
3189 128 => .{ .f128 = @tan(val.toFloat(f128, pt)) },
31383190 else => unreachable,
31393191 };
3140 return Value.fromInterned((try mod.intern(.{ .float = .{
3192 return Value.fromInterned(try pt.intern(.{ .float = .{
31413193 .ty = float_type.toIntern(),
31423194 .storage = storage,
3143 } })));
3195 } }));
31443196}
31453197
3146pub fn exp(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3198pub fn exp(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3199 const mod = pt.zcu;
31473200 if (float_type.zigTypeTag(mod) == .Vector) {
31483201 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31493202 const scalar_ty = float_type.scalarType(mod);
31503203 for (result_data, 0..) |*scalar, i| {
3151 const elem_val = try val.elemValue(mod, i);
3152 scalar.* = (try expScalar(elem_val, scalar_ty, mod)).toIntern();
3204 const elem_val = try val.elemValue(pt, i);
3205 scalar.* = (try expScalar(elem_val, scalar_ty, pt)).toIntern();
31533206 }
3154 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3207 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31553208 .ty = float_type.toIntern(),
31563209 .storage = .{ .elems = result_data },
3157 } })));
3210 } }));
31583211 }
3159 return expScalar(val, float_type, mod);
3212 return expScalar(val, float_type, pt);
31603213}
31613214
3162pub fn expScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3215pub fn expScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3216 const mod = pt.zcu;
31633217 const target = mod.getTarget();
31643218 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3165 16 => .{ .f16 = @exp(val.toFloat(f16, mod)) },
3166 32 => .{ .f32 = @exp(val.toFloat(f32, mod)) },
3167 64 => .{ .f64 = @exp(val.toFloat(f64, mod)) },
3168 80 => .{ .f80 = @exp(val.toFloat(f80, mod)) },
3169 128 => .{ .f128 = @exp(val.toFloat(f128, mod)) },
3219 16 => .{ .f16 = @exp(val.toFloat(f16, pt)) },
3220 32 => .{ .f32 = @exp(val.toFloat(f32, pt)) },
3221 64 => .{ .f64 = @exp(val.toFloat(f64, pt)) },
3222 80 => .{ .f80 = @exp(val.toFloat(f80, pt)) },
3223 128 => .{ .f128 = @exp(val.toFloat(f128, pt)) },
31703224 else => unreachable,
31713225 };
3172 return Value.fromInterned((try mod.intern(.{ .float = .{
3226 return Value.fromInterned(try pt.intern(.{ .float = .{
31733227 .ty = float_type.toIntern(),
31743228 .storage = storage,
3175 } })));
3229 } }));
31763230}
31773231
3178pub fn exp2(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3232pub fn exp2(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3233 const mod = pt.zcu;
31793234 if (float_type.zigTypeTag(mod) == .Vector) {
31803235 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31813236 const scalar_ty = float_type.scalarType(mod);
31823237 for (result_data, 0..) |*scalar, i| {
3183 const elem_val = try val.elemValue(mod, i);
3184 scalar.* = (try exp2Scalar(elem_val, scalar_ty, mod)).toIntern();
3238 const elem_val = try val.elemValue(pt, i);
3239 scalar.* = (try exp2Scalar(elem_val, scalar_ty, pt)).toIntern();
31853240 }
3186 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3241 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31873242 .ty = float_type.toIntern(),
31883243 .storage = .{ .elems = result_data },
3189 } })));
3244 } }));
31903245 }
3191 return exp2Scalar(val, float_type, mod);
3246 return exp2Scalar(val, float_type, pt);
31923247}
31933248
3194pub fn exp2Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3249pub fn exp2Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3250 const mod = pt.zcu;
31953251 const target = mod.getTarget();
31963252 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3197 16 => .{ .f16 = @exp2(val.toFloat(f16, mod)) },
3198 32 => .{ .f32 = @exp2(val.toFloat(f32, mod)) },
3199 64 => .{ .f64 = @exp2(val.toFloat(f64, mod)) },
3200 80 => .{ .f80 = @exp2(val.toFloat(f80, mod)) },
3201 128 => .{ .f128 = @exp2(val.toFloat(f128, mod)) },
3253 16 => .{ .f16 = @exp2(val.toFloat(f16, pt)) },
3254 32 => .{ .f32 = @exp2(val.toFloat(f32, pt)) },
3255 64 => .{ .f64 = @exp2(val.toFloat(f64, pt)) },
3256 80 => .{ .f80 = @exp2(val.toFloat(f80, pt)) },
3257 128 => .{ .f128 = @exp2(val.toFloat(f128, pt)) },
32023258 else => unreachable,
32033259 };
3204 return Value.fromInterned((try mod.intern(.{ .float = .{
3260 return Value.fromInterned(try pt.intern(.{ .float = .{
32053261 .ty = float_type.toIntern(),
32063262 .storage = storage,
3207 } })));
3263 } }));
32083264}
32093265
3210pub fn log(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3266pub fn log(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3267 const mod = pt.zcu;
32113268 if (float_type.zigTypeTag(mod) == .Vector) {
32123269 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32133270 const scalar_ty = float_type.scalarType(mod);
32143271 for (result_data, 0..) |*scalar, i| {
3215 const elem_val = try val.elemValue(mod, i);
3216 scalar.* = (try logScalar(elem_val, scalar_ty, mod)).toIntern();
3272 const elem_val = try val.elemValue(pt, i);
3273 scalar.* = (try logScalar(elem_val, scalar_ty, pt)).toIntern();
32173274 }
3218 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3275 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32193276 .ty = float_type.toIntern(),
32203277 .storage = .{ .elems = result_data },
3221 } })));
3278 } }));
32223279 }
3223 return logScalar(val, float_type, mod);
3280 return logScalar(val, float_type, pt);
32243281}
32253282
3226pub fn logScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3283pub fn logScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3284 const mod = pt.zcu;
32273285 const target = mod.getTarget();
32283286 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3229 16 => .{ .f16 = @log(val.toFloat(f16, mod)) },
3230 32 => .{ .f32 = @log(val.toFloat(f32, mod)) },
3231 64 => .{ .f64 = @log(val.toFloat(f64, mod)) },
3232 80 => .{ .f80 = @log(val.toFloat(f80, mod)) },
3233 128 => .{ .f128 = @log(val.toFloat(f128, mod)) },
3287 16 => .{ .f16 = @log(val.toFloat(f16, pt)) },
3288 32 => .{ .f32 = @log(val.toFloat(f32, pt)) },
3289 64 => .{ .f64 = @log(val.toFloat(f64, pt)) },
3290 80 => .{ .f80 = @log(val.toFloat(f80, pt)) },
3291 128 => .{ .f128 = @log(val.toFloat(f128, pt)) },
32343292 else => unreachable,
32353293 };
3236 return Value.fromInterned((try mod.intern(.{ .float = .{
3294 return Value.fromInterned(try pt.intern(.{ .float = .{
32373295 .ty = float_type.toIntern(),
32383296 .storage = storage,
3239 } })));
3297 } }));
32403298}
32413299
3242pub fn log2(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3300pub fn log2(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3301 const mod = pt.zcu;
32433302 if (float_type.zigTypeTag(mod) == .Vector) {
32443303 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32453304 const scalar_ty = float_type.scalarType(mod);
32463305 for (result_data, 0..) |*scalar, i| {
3247 const elem_val = try val.elemValue(mod, i);
3248 scalar.* = (try log2Scalar(elem_val, scalar_ty, mod)).toIntern();
3306 const elem_val = try val.elemValue(pt, i);
3307 scalar.* = (try log2Scalar(elem_val, scalar_ty, pt)).toIntern();
32493308 }
3250 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3309 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32513310 .ty = float_type.toIntern(),
32523311 .storage = .{ .elems = result_data },
3253 } })));
3312 } }));
32543313 }
3255 return log2Scalar(val, float_type, mod);
3314 return log2Scalar(val, float_type, pt);
32563315}
32573316
3258pub fn log2Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3317pub fn log2Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3318 const mod = pt.zcu;
32593319 const target = mod.getTarget();
32603320 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3261 16 => .{ .f16 = @log2(val.toFloat(f16, mod)) },
3262 32 => .{ .f32 = @log2(val.toFloat(f32, mod)) },
3263 64 => .{ .f64 = @log2(val.toFloat(f64, mod)) },
3264 80 => .{ .f80 = @log2(val.toFloat(f80, mod)) },
3265 128 => .{ .f128 = @log2(val.toFloat(f128, mod)) },
3321 16 => .{ .f16 = @log2(val.toFloat(f16, pt)) },
3322 32 => .{ .f32 = @log2(val.toFloat(f32, pt)) },
3323 64 => .{ .f64 = @log2(val.toFloat(f64, pt)) },
3324 80 => .{ .f80 = @log2(val.toFloat(f80, pt)) },
3325 128 => .{ .f128 = @log2(val.toFloat(f128, pt)) },
32663326 else => unreachable,
32673327 };
3268 return Value.fromInterned((try mod.intern(.{ .float = .{
3328 return Value.fromInterned(try pt.intern(.{ .float = .{
32693329 .ty = float_type.toIntern(),
32703330 .storage = storage,
3271 } })));
3331 } }));
32723332}
32733333
3274pub fn log10(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3334pub fn log10(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3335 const mod = pt.zcu;
32753336 if (float_type.zigTypeTag(mod) == .Vector) {
32763337 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32773338 const scalar_ty = float_type.scalarType(mod);
32783339 for (result_data, 0..) |*scalar, i| {
3279 const elem_val = try val.elemValue(mod, i);
3280 scalar.* = (try log10Scalar(elem_val, scalar_ty, mod)).toIntern();
3340 const elem_val = try val.elemValue(pt, i);
3341 scalar.* = (try log10Scalar(elem_val, scalar_ty, pt)).toIntern();
32813342 }
3282 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3343 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32833344 .ty = float_type.toIntern(),
32843345 .storage = .{ .elems = result_data },
3285 } })));
3346 } }));
32863347 }
3287 return log10Scalar(val, float_type, mod);
3348 return log10Scalar(val, float_type, pt);
32883349}
32893350
3290pub fn log10Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3351pub fn log10Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3352 const mod = pt.zcu;
32913353 const target = mod.getTarget();
32923354 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3293 16 => .{ .f16 = @log10(val.toFloat(f16, mod)) },
3294 32 => .{ .f32 = @log10(val.toFloat(f32, mod)) },
3295 64 => .{ .f64 = @log10(val.toFloat(f64, mod)) },
3296 80 => .{ .f80 = @log10(val.toFloat(f80, mod)) },
3297 128 => .{ .f128 = @log10(val.toFloat(f128, mod)) },
3355 16 => .{ .f16 = @log10(val.toFloat(f16, pt)) },
3356 32 => .{ .f32 = @log10(val.toFloat(f32, pt)) },
3357 64 => .{ .f64 = @log10(val.toFloat(f64, pt)) },
3358 80 => .{ .f80 = @log10(val.toFloat(f80, pt)) },
3359 128 => .{ .f128 = @log10(val.toFloat(f128, pt)) },
32983360 else => unreachable,
32993361 };
3300 return Value.fromInterned((try mod.intern(.{ .float = .{
3362 return Value.fromInterned(try pt.intern(.{ .float = .{
33013363 .ty = float_type.toIntern(),
33023364 .storage = storage,
3303 } })));
3365 } }));
33043366}
33053367
3306pub fn abs(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
3368pub fn abs(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3369 const mod = pt.zcu;
33073370 if (ty.zigTypeTag(mod) == .Vector) {
33083371 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
33093372 const scalar_ty = ty.scalarType(mod);
33103373 for (result_data, 0..) |*scalar, i| {
3311 const elem_val = try val.elemValue(mod, i);
3312 scalar.* = (try absScalar(elem_val, scalar_ty, mod, arena)).toIntern();
3374 const elem_val = try val.elemValue(pt, i);
3375 scalar.* = (try absScalar(elem_val, scalar_ty, pt, arena)).toIntern();
33133376 }
3314 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3377 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33153378 .ty = ty.toIntern(),
33163379 .storage = .{ .elems = result_data },
3317 } })));
3380 } }));
33183381 }
3319 return absScalar(val, ty, mod, arena);
3382 return absScalar(val, ty, pt, arena);
33203383}
33213384
3322pub fn absScalar(val: Value, ty: Type, mod: *Module, arena: Allocator) Allocator.Error!Value {
3385pub fn absScalar(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) Allocator.Error!Value {
3386 const mod = pt.zcu;
33233387 switch (ty.zigTypeTag(mod)) {
33243388 .Int => {
33253389 var buffer: Value.BigIntSpace = undefined;
3326 var operand_bigint = try val.toBigInt(&buffer, mod).toManaged(arena);
3390 var operand_bigint = try val.toBigInt(&buffer, pt).toManaged(arena);
33273391 operand_bigint.abs();
33283392
3329 return mod.intValue_big(try ty.toUnsigned(mod), operand_bigint.toConst());
3393 return pt.intValue_big(try ty.toUnsigned(pt), operand_bigint.toConst());
33303394 },
33313395 .ComptimeInt => {
33323396 var buffer: Value.BigIntSpace = undefined;
3333 var operand_bigint = try val.toBigInt(&buffer, mod).toManaged(arena);
3397 var operand_bigint = try val.toBigInt(&buffer, pt).toManaged(arena);
33343398 operand_bigint.abs();
33353399
3336 return mod.intValue_big(ty, operand_bigint.toConst());
3400 return pt.intValue_big(ty, operand_bigint.toConst());
33373401 },
33383402 .ComptimeFloat, .Float => {
33393403 const target = mod.getTarget();
33403404 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(target)) {
3341 16 => .{ .f16 = @abs(val.toFloat(f16, mod)) },
3342 32 => .{ .f32 = @abs(val.toFloat(f32, mod)) },
3343 64 => .{ .f64 = @abs(val.toFloat(f64, mod)) },
3344 80 => .{ .f80 = @abs(val.toFloat(f80, mod)) },
3345 128 => .{ .f128 = @abs(val.toFloat(f128, mod)) },
3405 16 => .{ .f16 = @abs(val.toFloat(f16, pt)) },
3406 32 => .{ .f32 = @abs(val.toFloat(f32, pt)) },
3407 64 => .{ .f64 = @abs(val.toFloat(f64, pt)) },
3408 80 => .{ .f80 = @abs(val.toFloat(f80, pt)) },
3409 128 => .{ .f128 = @abs(val.toFloat(f128, pt)) },
33463410 else => unreachable,
33473411 };
3348 return Value.fromInterned((try mod.intern(.{ .float = .{
3412 return Value.fromInterned(try pt.intern(.{ .float = .{
33493413 .ty = ty.toIntern(),
33503414 .storage = storage,
3351 } })));
3415 } }));
33523416 },
33533417 else => unreachable,
33543418 }
33553419}
33563420
3357pub fn floor(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3421pub fn floor(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3422 const mod = pt.zcu;
33583423 if (float_type.zigTypeTag(mod) == .Vector) {
33593424 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
33603425 const scalar_ty = float_type.scalarType(mod);
33613426 for (result_data, 0..) |*scalar, i| {
3362 const elem_val = try val.elemValue(mod, i);
3363 scalar.* = (try floorScalar(elem_val, scalar_ty, mod)).toIntern();
3427 const elem_val = try val.elemValue(pt, i);
3428 scalar.* = (try floorScalar(elem_val, scalar_ty, pt)).toIntern();
33643429 }
3365 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3430 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33663431 .ty = float_type.toIntern(),
33673432 .storage = .{ .elems = result_data },
3368 } })));
3433 } }));
33693434 }
3370 return floorScalar(val, float_type, mod);
3435 return floorScalar(val, float_type, pt);
33713436}
33723437
3373pub fn floorScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3438pub fn floorScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3439 const mod = pt.zcu;
33743440 const target = mod.getTarget();
33753441 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3376 16 => .{ .f16 = @floor(val.toFloat(f16, mod)) },
3377 32 => .{ .f32 = @floor(val.toFloat(f32, mod)) },
3378 64 => .{ .f64 = @floor(val.toFloat(f64, mod)) },
3379 80 => .{ .f80 = @floor(val.toFloat(f80, mod)) },
3380 128 => .{ .f128 = @floor(val.toFloat(f128, mod)) },
3442 16 => .{ .f16 = @floor(val.toFloat(f16, pt)) },
3443 32 => .{ .f32 = @floor(val.toFloat(f32, pt)) },
3444 64 => .{ .f64 = @floor(val.toFloat(f64, pt)) },
3445 80 => .{ .f80 = @floor(val.toFloat(f80, pt)) },
3446 128 => .{ .f128 = @floor(val.toFloat(f128, pt)) },
33813447 else => unreachable,
33823448 };
3383 return Value.fromInterned((try mod.intern(.{ .float = .{
3449 return Value.fromInterned(try pt.intern(.{ .float = .{
33843450 .ty = float_type.toIntern(),
33853451 .storage = storage,
3386 } })));
3452 } }));
33873453}
33883454
3389pub fn ceil(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3455pub fn ceil(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3456 const mod = pt.zcu;
33903457 if (float_type.zigTypeTag(mod) == .Vector) {
33913458 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
33923459 const scalar_ty = float_type.scalarType(mod);
33933460 for (result_data, 0..) |*scalar, i| {
3394 const elem_val = try val.elemValue(mod, i);
3395 scalar.* = (try ceilScalar(elem_val, scalar_ty, mod)).toIntern();
3461 const elem_val = try val.elemValue(pt, i);
3462 scalar.* = (try ceilScalar(elem_val, scalar_ty, pt)).toIntern();
33963463 }
3397 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3464 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33983465 .ty = float_type.toIntern(),
33993466 .storage = .{ .elems = result_data },
3400 } })));
3467 } }));
34013468 }
3402 return ceilScalar(val, float_type, mod);
3469 return ceilScalar(val, float_type, pt);
34033470}
34043471
3405pub fn ceilScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3472pub fn ceilScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3473 const mod = pt.zcu;
34063474 const target = mod.getTarget();
34073475 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3408 16 => .{ .f16 = @ceil(val.toFloat(f16, mod)) },
3409 32 => .{ .f32 = @ceil(val.toFloat(f32, mod)) },
3410 64 => .{ .f64 = @ceil(val.toFloat(f64, mod)) },
3411 80 => .{ .f80 = @ceil(val.toFloat(f80, mod)) },
3412 128 => .{ .f128 = @ceil(val.toFloat(f128, mod)) },
3476 16 => .{ .f16 = @ceil(val.toFloat(f16, pt)) },
3477 32 => .{ .f32 = @ceil(val.toFloat(f32, pt)) },
3478 64 => .{ .f64 = @ceil(val.toFloat(f64, pt)) },
3479 80 => .{ .f80 = @ceil(val.toFloat(f80, pt)) },
3480 128 => .{ .f128 = @ceil(val.toFloat(f128, pt)) },
34133481 else => unreachable,
34143482 };
3415 return Value.fromInterned((try mod.intern(.{ .float = .{
3483 return Value.fromInterned(try pt.intern(.{ .float = .{
34163484 .ty = float_type.toIntern(),
34173485 .storage = storage,
3418 } })));
3486 } }));
34193487}
34203488
3421pub fn round(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3489pub fn round(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3490 const mod = pt.zcu;
34223491 if (float_type.zigTypeTag(mod) == .Vector) {
34233492 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34243493 const scalar_ty = float_type.scalarType(mod);
34253494 for (result_data, 0..) |*scalar, i| {
3426 const elem_val = try val.elemValue(mod, i);
3427 scalar.* = (try roundScalar(elem_val, scalar_ty, mod)).toIntern();
3495 const elem_val = try val.elemValue(pt, i);
3496 scalar.* = (try roundScalar(elem_val, scalar_ty, pt)).toIntern();
34283497 }
3429 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3498 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
34303499 .ty = float_type.toIntern(),
34313500 .storage = .{ .elems = result_data },
3432 } })));
3501 } }));
34333502 }
3434 return roundScalar(val, float_type, mod);
3503 return roundScalar(val, float_type, pt);
34353504}
34363505
3437pub fn roundScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3506pub fn roundScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3507 const mod = pt.zcu;
34383508 const target = mod.getTarget();
34393509 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3440 16 => .{ .f16 = @round(val.toFloat(f16, mod)) },
3441 32 => .{ .f32 = @round(val.toFloat(f32, mod)) },
3442 64 => .{ .f64 = @round(val.toFloat(f64, mod)) },
3443 80 => .{ .f80 = @round(val.toFloat(f80, mod)) },
3444 128 => .{ .f128 = @round(val.toFloat(f128, mod)) },
3510 16 => .{ .f16 = @round(val.toFloat(f16, pt)) },
3511 32 => .{ .f32 = @round(val.toFloat(f32, pt)) },
3512 64 => .{ .f64 = @round(val.toFloat(f64, pt)) },
3513 80 => .{ .f80 = @round(val.toFloat(f80, pt)) },
3514 128 => .{ .f128 = @round(val.toFloat(f128, pt)) },
34453515 else => unreachable,
34463516 };
3447 return Value.fromInterned((try mod.intern(.{ .float = .{
3517 return Value.fromInterned(try pt.intern(.{ .float = .{
34483518 .ty = float_type.toIntern(),
34493519 .storage = storage,
3450 } })));
3520 } }));
34513521}
34523522
3453pub fn trunc(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3523pub fn trunc(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3524 const mod = pt.zcu;
34543525 if (float_type.zigTypeTag(mod) == .Vector) {
34553526 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34563527 const scalar_ty = float_type.scalarType(mod);
34573528 for (result_data, 0..) |*scalar, i| {
3458 const elem_val = try val.elemValue(mod, i);
3459 scalar.* = (try truncScalar(elem_val, scalar_ty, mod)).toIntern();
3529 const elem_val = try val.elemValue(pt, i);
3530 scalar.* = (try truncScalar(elem_val, scalar_ty, pt)).toIntern();
34603531 }
3461 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3532 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
34623533 .ty = float_type.toIntern(),
34633534 .storage = .{ .elems = result_data },
3464 } })));
3535 } }));
34653536 }
3466 return truncScalar(val, float_type, mod);
3537 return truncScalar(val, float_type, pt);
34673538}
34683539
3469pub fn truncScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3540pub fn truncScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3541 const mod = pt.zcu;
34703542 const target = mod.getTarget();
34713543 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3472 16 => .{ .f16 = @trunc(val.toFloat(f16, mod)) },
3473 32 => .{ .f32 = @trunc(val.toFloat(f32, mod)) },
3474 64 => .{ .f64 = @trunc(val.toFloat(f64, mod)) },
3475 80 => .{ .f80 = @trunc(val.toFloat(f80, mod)) },
3476 128 => .{ .f128 = @trunc(val.toFloat(f128, mod)) },
3544 16 => .{ .f16 = @trunc(val.toFloat(f16, pt)) },
3545 32 => .{ .f32 = @trunc(val.toFloat(f32, pt)) },
3546 64 => .{ .f64 = @trunc(val.toFloat(f64, pt)) },
3547 80 => .{ .f80 = @trunc(val.toFloat(f80, pt)) },
3548 128 => .{ .f128 = @trunc(val.toFloat(f128, pt)) },
34773549 else => unreachable,
34783550 };
3479 return Value.fromInterned((try mod.intern(.{ .float = .{
3551 return Value.fromInterned(try pt.intern(.{ .float = .{
34803552 .ty = float_type.toIntern(),
34813553 .storage = storage,
3482 } })));
3554 } }));
34833555}
34843556
34853557pub fn mulAdd(
......@@ -3488,23 +3560,24 @@ pub fn mulAdd(
34883560 mulend2: Value,
34893561 addend: Value,
34903562 arena: Allocator,
3491 mod: *Module,
3563 pt: Zcu.PerThread,
34923564) !Value {
3565 const mod = pt.zcu;
34933566 if (float_type.zigTypeTag(mod) == .Vector) {
34943567 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34953568 const scalar_ty = float_type.scalarType(mod);
34963569 for (result_data, 0..) |*scalar, i| {
3497 const mulend1_elem = try mulend1.elemValue(mod, i);
3498 const mulend2_elem = try mulend2.elemValue(mod, i);
3499 const addend_elem = try addend.elemValue(mod, i);
3500 scalar.* = (try mulAddScalar(scalar_ty, mulend1_elem, mulend2_elem, addend_elem, mod)).toIntern();
3570 const mulend1_elem = try mulend1.elemValue(pt, i);
3571 const mulend2_elem = try mulend2.elemValue(pt, i);
3572 const addend_elem = try addend.elemValue(pt, i);
3573 scalar.* = (try mulAddScalar(scalar_ty, mulend1_elem, mulend2_elem, addend_elem, pt)).toIntern();
35013574 }
3502 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3575 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
35033576 .ty = float_type.toIntern(),
35043577 .storage = .{ .elems = result_data },
3505 } })));
3578 } }));
35063579 }
3507 return mulAddScalar(float_type, mulend1, mulend2, addend, mod);
3580 return mulAddScalar(float_type, mulend1, mulend2, addend, pt);
35083581}
35093582
35103583pub fn mulAddScalar(
......@@ -3512,32 +3585,33 @@ pub fn mulAddScalar(
35123585 mulend1: Value,
35133586 mulend2: Value,
35143587 addend: Value,
3515 mod: *Module,
3588 pt: Zcu.PerThread,
35163589) Allocator.Error!Value {
3590 const mod = pt.zcu;
35173591 const target = mod.getTarget();
35183592 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3519 16 => .{ .f16 = @mulAdd(f16, mulend1.toFloat(f16, mod), mulend2.toFloat(f16, mod), addend.toFloat(f16, mod)) },
3520 32 => .{ .f32 = @mulAdd(f32, mulend1.toFloat(f32, mod), mulend2.toFloat(f32, mod), addend.toFloat(f32, mod)) },
3521 64 => .{ .f64 = @mulAdd(f64, mulend1.toFloat(f64, mod), mulend2.toFloat(f64, mod), addend.toFloat(f64, mod)) },
3522 80 => .{ .f80 = @mulAdd(f80, mulend1.toFloat(f80, mod), mulend2.toFloat(f80, mod), addend.toFloat(f80, mod)) },
3523 128 => .{ .f128 = @mulAdd(f128, mulend1.toFloat(f128, mod), mulend2.toFloat(f128, mod), addend.toFloat(f128, mod)) },
3593 16 => .{ .f16 = @mulAdd(f16, mulend1.toFloat(f16, pt), mulend2.toFloat(f16, pt), addend.toFloat(f16, pt)) },
3594 32 => .{ .f32 = @mulAdd(f32, mulend1.toFloat(f32, pt), mulend2.toFloat(f32, pt), addend.toFloat(f32, pt)) },
3595 64 => .{ .f64 = @mulAdd(f64, mulend1.toFloat(f64, pt), mulend2.toFloat(f64, pt), addend.toFloat(f64, pt)) },
3596 80 => .{ .f80 = @mulAdd(f80, mulend1.toFloat(f80, pt), mulend2.toFloat(f80, pt), addend.toFloat(f80, pt)) },
3597 128 => .{ .f128 = @mulAdd(f128, mulend1.toFloat(f128, pt), mulend2.toFloat(f128, pt), addend.toFloat(f128, pt)) },
35243598 else => unreachable,
35253599 };
3526 return Value.fromInterned((try mod.intern(.{ .float = .{
3600 return Value.fromInterned(try pt.intern(.{ .float = .{
35273601 .ty = float_type.toIntern(),
35283602 .storage = storage,
3529 } })));
3603 } }));
35303604}
35313605
35323606/// If the value is represented in-memory as a series of bytes that all
35333607/// have the same value, return that byte value, otherwise null.
3534pub fn hasRepeatedByteRepr(val: Value, ty: Type, mod: *Module) !?u8 {
3535 const abi_size = std.math.cast(usize, ty.abiSize(mod)) orelse return null;
3608pub fn hasRepeatedByteRepr(val: Value, ty: Type, pt: Zcu.PerThread) !?u8 {
3609 const abi_size = std.math.cast(usize, ty.abiSize(pt)) orelse return null;
35363610 assert(abi_size >= 1);
3537 const byte_buffer = try mod.gpa.alloc(u8, abi_size);
3538 defer mod.gpa.free(byte_buffer);
3611 const byte_buffer = try pt.zcu.gpa.alloc(u8, abi_size);
3612 defer pt.zcu.gpa.free(byte_buffer);
35393613
3540 writeToMemory(val, ty, mod, byte_buffer) catch |err| switch (err) {
3614 writeToMemory(val, ty, pt, byte_buffer) catch |err| switch (err) {
35413615 error.OutOfMemory => return error.OutOfMemory,
35423616 error.ReinterpretDeclRef => return null,
35433617 // TODO: The writeToMemory function was originally created for the purpose
......@@ -3567,13 +3641,13 @@ pub fn typeOf(val: Value, zcu: *const Zcu) Type {
35673641/// If `val` is not undef, the bounds are both `val`.
35683642/// If `val` is undef and has a fixed-width type, the bounds are the bounds of the type.
35693643/// If `val` is undef and is a `comptime_int`, returns null.
3570pub fn intValueBounds(val: Value, mod: *Module) !?[2]Value {
3571 if (!val.isUndef(mod)) return .{ val, val };
3572 const ty = mod.intern_pool.typeOf(val.toIntern());
3644pub fn intValueBounds(val: Value, pt: Zcu.PerThread) !?[2]Value {
3645 if (!val.isUndef(pt.zcu)) return .{ val, val };
3646 const ty = pt.zcu.intern_pool.typeOf(val.toIntern());
35733647 if (ty == .comptime_int_type) return null;
35743648 return .{
3575 try Type.fromInterned(ty).minInt(mod, Type.fromInterned(ty)),
3576 try Type.fromInterned(ty).maxInt(mod, Type.fromInterned(ty)),
3649 try Type.fromInterned(ty).minInt(pt, Type.fromInterned(ty)),
3650 try Type.fromInterned(ty).maxInt(pt, Type.fromInterned(ty)),
35773651 };
35783652}
35793653
......@@ -3604,14 +3678,15 @@ pub const RuntimeIndex = InternPool.RuntimeIndex;
36043678/// `parent_ptr` must be a single-pointer to some optional.
36053679/// Returns a pointer to the payload of the optional.
36063680/// May perform type resolution.
3607pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
3681pub fn ptrOptPayload(parent_ptr: Value, pt: Zcu.PerThread) !Value {
3682 const zcu = pt.zcu;
36083683 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36093684 const opt_ty = parent_ptr_ty.childType(zcu);
36103685
36113686 assert(parent_ptr_ty.ptrSize(zcu) == .One);
36123687 assert(opt_ty.zigTypeTag(zcu) == .Optional);
36133688
3614 const result_ty = try zcu.ptrTypeSema(info: {
3689 const result_ty = try pt.ptrTypeSema(info: {
36153690 var new = parent_ptr_ty.ptrInfo(zcu);
36163691 // We can correctly preserve alignment `.none`, since an optional has the same
36173692 // natural alignment as its child type.
......@@ -3619,15 +3694,15 @@ pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36193694 break :info new;
36203695 });
36213696
3622 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3697 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
36233698
36243699 if (opt_ty.isPtrLikeOptional(zcu)) {
36253700 // Just reinterpret the pointer, since the layout is well-defined
3626 return zcu.getCoerced(parent_ptr, result_ty);
3701 return pt.getCoerced(parent_ptr, result_ty);
36273702 }
36283703
3629 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, opt_ty, zcu);
3630 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3704 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, opt_ty, pt);
3705 return Value.fromInterned(try pt.intern(.{ .ptr = .{
36313706 .ty = result_ty.toIntern(),
36323707 .base_addr = .{ .opt_payload = base_ptr.toIntern() },
36333708 .byte_offset = 0,
......@@ -3637,14 +3712,15 @@ pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36373712/// `parent_ptr` must be a single-pointer to some error union.
36383713/// Returns a pointer to the payload of the error union.
36393714/// May perform type resolution.
3640pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
3715pub fn ptrEuPayload(parent_ptr: Value, pt: Zcu.PerThread) !Value {
3716 const zcu = pt.zcu;
36413717 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36423718 const eu_ty = parent_ptr_ty.childType(zcu);
36433719
36443720 assert(parent_ptr_ty.ptrSize(zcu) == .One);
36453721 assert(eu_ty.zigTypeTag(zcu) == .ErrorUnion);
36463722
3647 const result_ty = try zcu.ptrTypeSema(info: {
3723 const result_ty = try pt.ptrTypeSema(info: {
36483724 var new = parent_ptr_ty.ptrInfo(zcu);
36493725 // We can correctly preserve alignment `.none`, since an error union has a
36503726 // natural alignment greater than or equal to that of its payload type.
......@@ -3652,10 +3728,10 @@ pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36523728 break :info new;
36533729 });
36543730
3655 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3731 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
36563732
3657 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, eu_ty, zcu);
3658 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3733 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, eu_ty, pt);
3734 return Value.fromInterned(try pt.intern(.{ .ptr = .{
36593735 .ty = result_ty.toIntern(),
36603736 .base_addr = .{ .eu_payload = base_ptr.toIntern() },
36613737 .byte_offset = 0,
......@@ -3666,7 +3742,8 @@ pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36663742/// Returns a pointer to the aggregate field at the specified index.
36673743/// For slices, uses `slice_ptr_index` and `slice_len_index`.
36683744/// May perform type resolution.
3669pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
3745pub fn ptrField(parent_ptr: Value, field_idx: u32, pt: Zcu.PerThread) !Value {
3746 const zcu = pt.zcu;
36703747 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36713748 const aggregate_ty = parent_ptr_ty.childType(zcu);
36723749
......@@ -3679,39 +3756,39 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
36793756 .Struct => field: {
36803757 const field_ty = aggregate_ty.structFieldType(field_idx, zcu);
36813758 switch (aggregate_ty.containerLayout(zcu)) {
3682 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), zcu, .sema) },
3759 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), pt, .sema) },
36833760 .@"extern" => {
36843761 // Well-defined layout, so just offset the pointer appropriately.
3685 const byte_off = aggregate_ty.structFieldOffset(field_idx, zcu);
3762 const byte_off = aggregate_ty.structFieldOffset(field_idx, pt);
36863763 const field_align = a: {
36873764 const parent_align = if (parent_ptr_info.flags.alignment == .none) pa: {
3688 break :pa (try aggregate_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3765 break :pa (try aggregate_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
36893766 } else parent_ptr_info.flags.alignment;
36903767 break :a InternPool.Alignment.fromLog2Units(@min(parent_align.toLog2Units(), @ctz(byte_off)));
36913768 };
3692 const result_ty = try zcu.ptrTypeSema(info: {
3769 const result_ty = try pt.ptrTypeSema(info: {
36933770 var new = parent_ptr_info;
36943771 new.child = field_ty.toIntern();
36953772 new.flags.alignment = field_align;
36963773 break :info new;
36973774 });
3698 return parent_ptr.getOffsetPtr(byte_off, result_ty, zcu);
3775 return parent_ptr.getOffsetPtr(byte_off, result_ty, pt);
36993776 },
3700 .@"packed" => switch (aggregate_ty.packedStructFieldPtrInfo(parent_ptr_ty, field_idx, zcu)) {
3777 .@"packed" => switch (aggregate_ty.packedStructFieldPtrInfo(parent_ptr_ty, field_idx, pt)) {
37013778 .bit_ptr => |packed_offset| {
3702 const result_ty = try zcu.ptrType(info: {
3779 const result_ty = try pt.ptrType(info: {
37033780 var new = parent_ptr_info;
37043781 new.packed_offset = packed_offset;
37053782 new.child = field_ty.toIntern();
37063783 if (new.flags.alignment == .none) {
3707 new.flags.alignment = (try aggregate_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3784 new.flags.alignment = (try aggregate_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
37083785 }
37093786 break :info new;
37103787 });
3711 return zcu.getCoerced(parent_ptr, result_ty);
3788 return pt.getCoerced(parent_ptr, result_ty);
37123789 },
37133790 .byte_ptr => |ptr_info| {
3714 const result_ty = try zcu.ptrTypeSema(info: {
3791 const result_ty = try pt.ptrTypeSema(info: {
37153792 var new = parent_ptr_info;
37163793 new.child = field_ty.toIntern();
37173794 new.packed_offset = .{
......@@ -3721,7 +3798,7 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37213798 new.flags.alignment = ptr_info.alignment;
37223799 break :info new;
37233800 });
3724 return parent_ptr.getOffsetPtr(ptr_info.offset, result_ty, zcu);
3801 return parent_ptr.getOffsetPtr(ptr_info.offset, result_ty, pt);
37253802 },
37263803 },
37273804 }
......@@ -3730,46 +3807,46 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37303807 const union_obj = zcu.typeToUnion(aggregate_ty).?;
37313808 const field_ty = Type.fromInterned(union_obj.field_types.get(&zcu.intern_pool)[field_idx]);
37323809 switch (aggregate_ty.containerLayout(zcu)) {
3733 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), zcu, .sema) },
3810 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), pt, .sema) },
37343811 .@"extern" => {
37353812 // Point to the same address.
3736 const result_ty = try zcu.ptrTypeSema(info: {
3813 const result_ty = try pt.ptrTypeSema(info: {
37373814 var new = parent_ptr_info;
37383815 new.child = field_ty.toIntern();
37393816 break :info new;
37403817 });
3741 return zcu.getCoerced(parent_ptr, result_ty);
3818 return pt.getCoerced(parent_ptr, result_ty);
37423819 },
37433820 .@"packed" => {
37443821 // If the field has an ABI size matching its bit size, then we can continue to use a
37453822 // non-bit pointer if the parent pointer is also a non-bit pointer.
3746 if (parent_ptr_info.packed_offset.host_size == 0 and (try field_ty.abiSizeAdvanced(zcu, .sema)).scalar * 8 == try field_ty.bitSizeAdvanced(zcu, .sema)) {
3823 if (parent_ptr_info.packed_offset.host_size == 0 and (try field_ty.abiSizeAdvanced(pt, .sema)).scalar * 8 == try field_ty.bitSizeAdvanced(pt, .sema)) {
37473824 // We must offset the pointer on big-endian targets, since the bits of packed memory don't align nicely.
37483825 const byte_offset = switch (zcu.getTarget().cpu.arch.endian()) {
37493826 .little => 0,
3750 .big => (try aggregate_ty.abiSizeAdvanced(zcu, .sema)).scalar - (try field_ty.abiSizeAdvanced(zcu, .sema)).scalar,
3827 .big => (try aggregate_ty.abiSizeAdvanced(pt, .sema)).scalar - (try field_ty.abiSizeAdvanced(pt, .sema)).scalar,
37513828 };
3752 const result_ty = try zcu.ptrTypeSema(info: {
3829 const result_ty = try pt.ptrTypeSema(info: {
37533830 var new = parent_ptr_info;
37543831 new.child = field_ty.toIntern();
37553832 new.flags.alignment = InternPool.Alignment.fromLog2Units(
3756 @ctz(byte_offset | (try parent_ptr_ty.ptrAlignmentAdvanced(zcu, .sema)).toByteUnits().?),
3833 @ctz(byte_offset | (try parent_ptr_ty.ptrAlignmentAdvanced(pt, .sema)).toByteUnits().?),
37573834 );
37583835 break :info new;
37593836 });
3760 return parent_ptr.getOffsetPtr(byte_offset, result_ty, zcu);
3837 return parent_ptr.getOffsetPtr(byte_offset, result_ty, pt);
37613838 } else {
37623839 // The result must be a bit-pointer if it is not already.
3763 const result_ty = try zcu.ptrTypeSema(info: {
3840 const result_ty = try pt.ptrTypeSema(info: {
37643841 var new = parent_ptr_info;
37653842 new.child = field_ty.toIntern();
37663843 if (new.packed_offset.host_size == 0) {
3767 new.packed_offset.host_size = @intCast(((try aggregate_ty.bitSizeAdvanced(zcu, .sema)) + 7) / 8);
3844 new.packed_offset.host_size = @intCast(((try aggregate_ty.bitSizeAdvanced(pt, .sema)) + 7) / 8);
37683845 assert(new.packed_offset.bit_offset == 0);
37693846 }
37703847 break :info new;
37713848 });
3772 return zcu.getCoerced(parent_ptr, result_ty);
3849 return pt.getCoerced(parent_ptr, result_ty);
37733850 }
37743851 },
37753852 }
......@@ -3777,8 +3854,8 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37773854 .Pointer => field_ty: {
37783855 assert(aggregate_ty.isSlice(zcu));
37793856 break :field_ty switch (field_idx) {
3780 Value.slice_ptr_index => .{ aggregate_ty.slicePtrFieldType(zcu), Type.usize.abiAlignment(zcu) },
3781 Value.slice_len_index => .{ Type.usize, Type.usize.abiAlignment(zcu) },
3857 Value.slice_ptr_index => .{ aggregate_ty.slicePtrFieldType(zcu), Type.usize.abiAlignment(pt) },
3858 Value.slice_len_index => .{ Type.usize, Type.usize.abiAlignment(pt) },
37823859 else => unreachable,
37833860 };
37843861 },
......@@ -3786,24 +3863,24 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37863863 };
37873864
37883865 const new_align: InternPool.Alignment = if (parent_ptr_info.flags.alignment != .none) a: {
3789 const ty_align = (try field_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3866 const ty_align = (try field_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
37903867 const true_field_align = if (field_align == .none) ty_align else field_align;
37913868 const new_align = true_field_align.min(parent_ptr_info.flags.alignment);
37923869 if (new_align == ty_align) break :a .none;
37933870 break :a new_align;
37943871 } else field_align;
37953872
3796 const result_ty = try zcu.ptrTypeSema(info: {
3873 const result_ty = try pt.ptrTypeSema(info: {
37973874 var new = parent_ptr_info;
37983875 new.child = field_ty.toIntern();
37993876 new.flags.alignment = new_align;
38003877 break :info new;
38013878 });
38023879
3803 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3880 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
38043881
3805 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, aggregate_ty, zcu);
3806 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3882 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, aggregate_ty, pt);
3883 return Value.fromInterned(try pt.intern(.{ .ptr = .{
38073884 .ty = result_ty.toIntern(),
38083885 .base_addr = .{ .field = .{
38093886 .base = base_ptr.toIntern(),
......@@ -3816,7 +3893,8 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
38163893/// `orig_parent_ptr` must be either a single-pointer to an array or vector, or a many-pointer or C-pointer or slice.
38173894/// Returns a pointer to the element at the specified index.
38183895/// May perform type resolution.
3819pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
3896pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, pt: Zcu.PerThread) !Value {
3897 const zcu = pt.zcu;
38203898 const parent_ptr = switch (orig_parent_ptr.typeOf(zcu).ptrSize(zcu)) {
38213899 .One, .Many, .C => orig_parent_ptr,
38223900 .Slice => orig_parent_ptr.slicePtr(zcu),
......@@ -3824,14 +3902,14 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38243902
38253903 const parent_ptr_ty = parent_ptr.typeOf(zcu);
38263904 const elem_ty = parent_ptr_ty.childType(zcu);
3827 const result_ty = try parent_ptr_ty.elemPtrType(@intCast(field_idx), zcu);
3905 const result_ty = try parent_ptr_ty.elemPtrType(@intCast(field_idx), pt);
38283906
3829 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3907 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
38303908
38313909 if (result_ty.ptrInfo(zcu).packed_offset.host_size != 0) {
38323910 // Since we have a bit-pointer, the pointer address should be unchanged.
38333911 assert(elem_ty.zigTypeTag(zcu) == .Vector);
3834 return zcu.getCoerced(parent_ptr, result_ty);
3912 return pt.getCoerced(parent_ptr, result_ty);
38353913 }
38363914
38373915 const PtrStrat = union(enum) {
......@@ -3841,31 +3919,31 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38413919
38423920 const strat: PtrStrat = switch (parent_ptr_ty.ptrSize(zcu)) {
38433921 .One => switch (elem_ty.zigTypeTag(zcu)) {
3844 .Vector => .{ .offset = field_idx * @divExact(try elem_ty.childType(zcu).bitSizeAdvanced(zcu, .sema), 8) },
3922 .Vector => .{ .offset = field_idx * @divExact(try elem_ty.childType(zcu).bitSizeAdvanced(pt, .sema), 8) },
38453923 .Array => strat: {
38463924 const arr_elem_ty = elem_ty.childType(zcu);
3847 if (try arr_elem_ty.comptimeOnlyAdvanced(zcu, .sema)) {
3925 if (try arr_elem_ty.comptimeOnlyAdvanced(pt, .sema)) {
38483926 break :strat .{ .elem_ptr = arr_elem_ty };
38493927 }
3850 break :strat .{ .offset = field_idx * (try arr_elem_ty.abiSizeAdvanced(zcu, .sema)).scalar };
3928 break :strat .{ .offset = field_idx * (try arr_elem_ty.abiSizeAdvanced(pt, .sema)).scalar };
38513929 },
38523930 else => unreachable,
38533931 },
38543932
3855 .Many, .C => if (try elem_ty.comptimeOnlyAdvanced(zcu, .sema))
3933 .Many, .C => if (try elem_ty.comptimeOnlyAdvanced(pt, .sema))
38563934 .{ .elem_ptr = elem_ty }
38573935 else
3858 .{ .offset = field_idx * (try elem_ty.abiSizeAdvanced(zcu, .sema)).scalar },
3936 .{ .offset = field_idx * (try elem_ty.abiSizeAdvanced(pt, .sema)).scalar },
38593937
38603938 .Slice => unreachable,
38613939 };
38623940
38633941 switch (strat) {
38643942 .offset => |byte_offset| {
3865 return parent_ptr.getOffsetPtr(byte_offset, result_ty, zcu);
3943 return parent_ptr.getOffsetPtr(byte_offset, result_ty, pt);
38663944 },
38673945 .elem_ptr => |manyptr_elem_ty| if (field_idx == 0) {
3868 return zcu.getCoerced(parent_ptr, result_ty);
3946 return pt.getCoerced(parent_ptr, result_ty);
38693947 } else {
38703948 const arr_base_ty, const arr_base_len = manyptr_elem_ty.arrayBase(zcu);
38713949 const base_idx = arr_base_len * field_idx;
......@@ -3875,7 +3953,7 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38753953 if (Value.fromInterned(arr_elem.base).typeOf(zcu).childType(zcu).toIntern() == arr_base_ty.toIntern()) {
38763954 // We already have a pointer to an element of an array of this type.
38773955 // Just modify the index.
3878 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr: {
3956 return Value.fromInterned(try pt.intern(.{ .ptr = ptr: {
38793957 var new = parent_info;
38803958 new.base_addr.arr_elem.index += base_idx;
38813959 new.ty = result_ty.toIntern();
......@@ -3885,8 +3963,8 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38853963 },
38863964 else => {},
38873965 }
3888 const base_ptr = try parent_ptr.canonicalizeBasePtr(.Many, arr_base_ty, zcu);
3889 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3966 const base_ptr = try parent_ptr.canonicalizeBasePtr(.Many, arr_base_ty, pt);
3967 return Value.fromInterned(try pt.intern(.{ .ptr = .{
38903968 .ty = result_ty.toIntern(),
38913969 .base_addr = .{ .arr_elem = .{
38923970 .base = base_ptr.toIntern(),
......@@ -3898,9 +3976,9 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38983976 }
38993977}
39003978
3901fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size, want_child: Type, zcu: *Zcu) !Value {
3902 const ptr_ty = base_ptr.typeOf(zcu);
3903 const ptr_info = ptr_ty.ptrInfo(zcu);
3979fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size, want_child: Type, pt: Zcu.PerThread) !Value {
3980 const ptr_ty = base_ptr.typeOf(pt.zcu);
3981 const ptr_info = ptr_ty.ptrInfo(pt.zcu);
39043982
39053983 if (ptr_info.flags.size == want_size and
39063984 ptr_info.child == want_child.toIntern() and
......@@ -3914,7 +3992,7 @@ fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size
39143992 return base_ptr;
39153993 }
39163994
3917 const new_ty = try zcu.ptrType(.{
3995 const new_ty = try pt.ptrType(.{
39183996 .child = want_child.toIntern(),
39193997 .sentinel = .none,
39203998 .flags = .{
......@@ -3926,15 +4004,15 @@ fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size
39264004 .address_space = ptr_info.flags.address_space,
39274005 },
39284006 });
3929 return zcu.getCoerced(base_ptr, new_ty);
4007 return pt.getCoerced(base_ptr, new_ty);
39304008}
39314009
3932pub fn getOffsetPtr(ptr_val: Value, byte_off: u64, new_ty: Type, zcu: *Zcu) !Value {
3933 if (ptr_val.isUndef(zcu)) return ptr_val;
3934 var ptr = zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
4010pub fn getOffsetPtr(ptr_val: Value, byte_off: u64, new_ty: Type, pt: Zcu.PerThread) !Value {
4011 if (ptr_val.isUndef(pt.zcu)) return ptr_val;
4012 var ptr = pt.zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
39354013 ptr.ty = new_ty.toIntern();
39364014 ptr.byte_offset += byte_off;
3937 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr }));
4015 return Value.fromInterned(try pt.intern(.{ .ptr = ptr }));
39384016}
39394017
39404018pub const PointerDeriveStep = union(enum) {
......@@ -3977,21 +4055,21 @@ pub const PointerDeriveStep = union(enum) {
39774055 new_ptr_ty: Type,
39784056 },
39794057
3980 pub fn ptrType(step: PointerDeriveStep, zcu: *Zcu) !Type {
4058 pub fn ptrType(step: PointerDeriveStep, pt: Zcu.PerThread) !Type {
39814059 return switch (step) {
39824060 .int => |int| int.ptr_ty,
3983 .decl_ptr => |decl| try zcu.declPtr(decl).declPtrType(zcu),
4061 .decl_ptr => |decl| try pt.zcu.declPtr(decl).declPtrType(pt),
39844062 .anon_decl_ptr => |ad| Type.fromInterned(ad.orig_ty),
39854063 .comptime_alloc_ptr => |info| info.ptr_ty,
3986 .comptime_field_ptr => |val| try zcu.singleConstPtrType(val.typeOf(zcu)),
4064 .comptime_field_ptr => |val| try pt.singleConstPtrType(val.typeOf(pt.zcu)),
39874065 .offset_and_cast => |oac| oac.new_ptr_ty,
39884066 inline .eu_payload_ptr, .opt_payload_ptr, .field_ptr, .elem_ptr => |x| x.result_ptr_ty,
39894067 };
39904068 }
39914069};
39924070
3993pub fn pointerDerivation(ptr_val: Value, arena: Allocator, zcu: *Zcu) Allocator.Error!PointerDeriveStep {
3994 return ptr_val.pointerDerivationAdvanced(arena, zcu, null) catch |err| switch (err) {
4071pub fn pointerDerivation(ptr_val: Value, arena: Allocator, pt: Zcu.PerThread) Allocator.Error!PointerDeriveStep {
4072 return ptr_val.pointerDerivationAdvanced(arena, pt, null) catch |err| switch (err) {
39954073 error.OutOfMemory => |e| return e,
39964074 error.AnalysisFail => unreachable,
39974075 };
......@@ -4001,7 +4079,8 @@ pub fn pointerDerivation(ptr_val: Value, arena: Allocator, zcu: *Zcu) Allocator.
40014079/// only field and element pointers with no casts. This can be used by codegen backends
40024080/// which prefer field/elem accesses when lowering constant pointer values.
40034081/// It is also used by the Value printing logic for pointers.
4004pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, opt_sema: ?*Sema) !PointerDeriveStep {
4082pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, pt: Zcu.PerThread, opt_sema: ?*Sema) !PointerDeriveStep {
4083 const zcu = pt.zcu;
40054084 const ptr = zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
40064085 const base_derive: PointerDeriveStep = switch (ptr.base_addr) {
40074086 .int => return .{ .int = .{
......@@ -4012,7 +4091,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40124091 .anon_decl => |ad| base: {
40134092 // A slight tweak: `orig_ty` here is sometimes not `const`, but it ought to be.
40144093 // TODO: fix this in the sites interning anon decls!
4015 const const_ty = try zcu.ptrType(info: {
4094 const const_ty = try pt.ptrType(info: {
40164095 var info = Type.fromInterned(ad.orig_ty).ptrInfo(zcu);
40174096 info.flags.is_const = true;
40184097 break :info info;
......@@ -4024,11 +4103,11 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40244103 },
40254104 .comptime_alloc => |idx| base: {
40264105 const alloc = opt_sema.?.getComptimeAlloc(idx);
4027 const val = try alloc.val.intern(zcu, opt_sema.?.arena);
4106 const val = try alloc.val.intern(pt, opt_sema.?.arena);
40284107 const ty = val.typeOf(zcu);
40294108 break :base .{ .comptime_alloc_ptr = .{
40304109 .val = val,
4031 .ptr_ty = try zcu.ptrType(.{
4110 .ptr_ty = try pt.ptrType(.{
40324111 .child = ty.toIntern(),
40334112 .flags = .{
40344113 .alignment = alloc.alignment,
......@@ -4041,20 +4120,20 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40414120 const base_ptr = Value.fromInterned(eu_ptr);
40424121 const base_ptr_ty = base_ptr.typeOf(zcu);
40434122 const parent_step = try arena.create(PointerDeriveStep);
4044 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(eu_ptr), arena, zcu, opt_sema);
4123 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(eu_ptr), arena, pt, opt_sema);
40454124 break :base .{ .eu_payload_ptr = .{
40464125 .parent = parent_step,
4047 .result_ptr_ty = try zcu.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).errorUnionPayload(zcu)),
4126 .result_ptr_ty = try pt.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).errorUnionPayload(zcu)),
40484127 } };
40494128 },
40504129 .opt_payload => |opt_ptr| base: {
40514130 const base_ptr = Value.fromInterned(opt_ptr);
40524131 const base_ptr_ty = base_ptr.typeOf(zcu);
40534132 const parent_step = try arena.create(PointerDeriveStep);
4054 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(opt_ptr), arena, zcu, opt_sema);
4133 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(opt_ptr), arena, pt, opt_sema);
40554134 break :base .{ .opt_payload_ptr = .{
40564135 .parent = parent_step,
4057 .result_ptr_ty = try zcu.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).optionalChild(zcu)),
4136 .result_ptr_ty = try pt.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).optionalChild(zcu)),
40584137 } };
40594138 },
40604139 .field => |field| base: {
......@@ -4062,22 +4141,22 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40624141 const base_ptr_ty = base_ptr.typeOf(zcu);
40634142 const agg_ty = base_ptr_ty.childType(zcu);
40644143 const field_ty, const field_align = switch (agg_ty.zigTypeTag(zcu)) {
4065 .Struct => .{ agg_ty.structFieldType(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), zcu, .sema) },
4066 .Union => .{ agg_ty.unionFieldTypeByIndex(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), zcu, .sema) },
4144 .Struct => .{ agg_ty.structFieldType(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), pt, .sema) },
4145 .Union => .{ agg_ty.unionFieldTypeByIndex(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), pt, .sema) },
40674146 .Pointer => .{ switch (field.index) {
40684147 Value.slice_ptr_index => agg_ty.slicePtrFieldType(zcu),
40694148 Value.slice_len_index => Type.usize,
40704149 else => unreachable,
4071 }, Type.usize.abiAlignment(zcu) },
4150 }, Type.usize.abiAlignment(pt) },
40724151 else => unreachable,
40734152 };
4074 const base_align = base_ptr_ty.ptrAlignment(zcu);
4153 const base_align = base_ptr_ty.ptrAlignment(pt);
40754154 const result_align = field_align.minStrict(base_align);
4076 const result_ty = try zcu.ptrType(.{
4155 const result_ty = try pt.ptrType(.{
40774156 .child = field_ty.toIntern(),
40784157 .flags = flags: {
40794158 var flags = base_ptr_ty.ptrInfo(zcu).flags;
4080 if (result_align == field_ty.abiAlignment(zcu)) {
4159 if (result_align == field_ty.abiAlignment(pt)) {
40814160 flags.alignment = .none;
40824161 } else {
40834162 flags.alignment = result_align;
......@@ -4086,7 +4165,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40864165 },
40874166 });
40884167 const parent_step = try arena.create(PointerDeriveStep);
4089 parent_step.* = try pointerDerivationAdvanced(base_ptr, arena, zcu, opt_sema);
4168 parent_step.* = try pointerDerivationAdvanced(base_ptr, arena, pt, opt_sema);
40904169 break :base .{ .field_ptr = .{
40914170 .parent = parent_step,
40924171 .field_idx = @intCast(field.index),
......@@ -4095,9 +4174,9 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40954174 },
40964175 .arr_elem => |arr_elem| base: {
40974176 const parent_step = try arena.create(PointerDeriveStep);
4098 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(arr_elem.base), arena, zcu, opt_sema);
4099 const parent_ptr_info = (try parent_step.ptrType(zcu)).ptrInfo(zcu);
4100 const result_ptr_ty = try zcu.ptrType(.{
4177 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(arr_elem.base), arena, pt, opt_sema);
4178 const parent_ptr_info = (try parent_step.ptrType(pt)).ptrInfo(zcu);
4179 const result_ptr_ty = try pt.ptrType(.{
41014180 .child = parent_ptr_info.child,
41024181 .flags = flags: {
41034182 var flags = parent_ptr_info.flags;
......@@ -4113,12 +4192,12 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41134192 },
41144193 };
41154194
4116 if (ptr.byte_offset == 0 and ptr.ty == (try base_derive.ptrType(zcu)).toIntern()) {
4195 if (ptr.byte_offset == 0 and ptr.ty == (try base_derive.ptrType(pt)).toIntern()) {
41174196 return base_derive;
41184197 }
41194198
41204199 const need_child = Type.fromInterned(ptr.ty).childType(zcu);
4121 if (need_child.comptimeOnly(zcu)) {
4200 if (need_child.comptimeOnly(pt)) {
41224201 // No refinement can happen - this pointer is presumably invalid.
41234202 // Just offset it.
41244203 const parent = try arena.create(PointerDeriveStep);
......@@ -4129,7 +4208,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41294208 .new_ptr_ty = Type.fromInterned(ptr.ty),
41304209 } };
41314210 }
4132 const need_bytes = need_child.abiSize(zcu);
4211 const need_bytes = need_child.abiSize(pt);
41334212
41344213 var cur_derive = base_derive;
41354214 var cur_offset = ptr.byte_offset;
......@@ -4137,7 +4216,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41374216 // Refine through fields and array elements as much as possible.
41384217
41394218 if (need_bytes > 0) while (true) {
4140 const cur_ty = (try cur_derive.ptrType(zcu)).childType(zcu);
4219 const cur_ty = (try cur_derive.ptrType(pt)).childType(zcu);
41414220 if (cur_ty.toIntern() == need_child.toIntern() and cur_offset == 0) {
41424221 break;
41434222 }
......@@ -4168,7 +4247,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41684247
41694248 .Array => {
41704249 const elem_ty = cur_ty.childType(zcu);
4171 const elem_size = elem_ty.abiSize(zcu);
4250 const elem_size = elem_ty.abiSize(pt);
41724251 const start_idx = cur_offset / elem_size;
41734252 const end_idx = (cur_offset + need_bytes + elem_size - 1) / elem_size;
41744253 if (end_idx == start_idx + 1) {
......@@ -4177,7 +4256,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41774256 cur_derive = .{ .elem_ptr = .{
41784257 .parent = parent,
41794258 .elem_idx = start_idx,
4180 .result_ptr_ty = try zcu.adjustPtrTypeChild(try parent.ptrType(zcu), elem_ty),
4259 .result_ptr_ty = try pt.adjustPtrTypeChild(try parent.ptrType(pt), elem_ty),
41814260 } };
41824261 cur_offset -= start_idx * elem_size;
41834262 } else {
......@@ -4188,7 +4267,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41884267 cur_derive = .{ .elem_ptr = .{
41894268 .parent = parent,
41904269 .elem_idx = start_idx,
4191 .result_ptr_ty = try zcu.adjustPtrTypeChild(try parent.ptrType(zcu), elem_ty),
4270 .result_ptr_ty = try pt.adjustPtrTypeChild(try parent.ptrType(pt), elem_ty),
41924271 } };
41934272 cur_offset -= start_idx * elem_size;
41944273 }
......@@ -4199,19 +4278,19 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41994278 .auto, .@"packed" => break,
42004279 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
42014280 const field_ty = cur_ty.structFieldType(field_idx, zcu);
4202 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
4203 const end_off = start_off + field_ty.abiSize(zcu);
4281 const start_off = cur_ty.structFieldOffset(field_idx, pt);
4282 const end_off = start_off + field_ty.abiSize(pt);
42044283 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
4205 const old_ptr_ty = try cur_derive.ptrType(zcu);
4206 const parent_align = old_ptr_ty.ptrAlignment(zcu);
4284 const old_ptr_ty = try cur_derive.ptrType(pt);
4285 const parent_align = old_ptr_ty.ptrAlignment(pt);
42074286 const field_align = InternPool.Alignment.fromLog2Units(@min(parent_align.toLog2Units(), @ctz(start_off)));
42084287 const parent = try arena.create(PointerDeriveStep);
42094288 parent.* = cur_derive;
4210 const new_ptr_ty = try zcu.ptrType(.{
4289 const new_ptr_ty = try pt.ptrType(.{
42114290 .child = field_ty.toIntern(),
42124291 .flags = flags: {
42134292 var flags = old_ptr_ty.ptrInfo(zcu).flags;
4214 if (field_align == field_ty.abiAlignment(zcu)) {
4293 if (field_align == field_ty.abiAlignment(pt)) {
42154294 flags.alignment = .none;
42164295 } else {
42174296 flags.alignment = field_align;
......@@ -4232,7 +4311,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
42324311 }
42334312 };
42344313
4235 if (cur_offset == 0 and (try cur_derive.ptrType(zcu)).toIntern() == ptr.ty) {
4314 if (cur_offset == 0 and (try cur_derive.ptrType(pt)).toIntern() == ptr.ty) {
42364315 return cur_derive;
42374316 }
42384317
......@@ -4245,20 +4324,20 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
42454324 } };
42464325}
42474326
4248pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value {
4249 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
4327pub fn resolveLazy(val: Value, arena: Allocator, pt: Zcu.PerThread) Zcu.SemaError!Value {
4328 switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
42504329 .int => |int| switch (int.storage) {
42514330 .u64, .i64, .big_int => return val,
4252 .lazy_align, .lazy_size => return zcu.intValue(
4331 .lazy_align, .lazy_size => return pt.intValue(
42534332 Type.fromInterned(int.ty),
4254 (try val.getUnsignedIntAdvanced(zcu, .sema)).?,
4333 (try val.getUnsignedIntAdvanced(pt, .sema)).?,
42554334 ),
42564335 },
42574336 .slice => |slice| {
4258 const ptr = try Value.fromInterned(slice.ptr).resolveLazy(arena, zcu);
4259 const len = try Value.fromInterned(slice.len).resolveLazy(arena, zcu);
4337 const ptr = try Value.fromInterned(slice.ptr).resolveLazy(arena, pt);
4338 const len = try Value.fromInterned(slice.len).resolveLazy(arena, pt);
42604339 if (ptr.toIntern() == slice.ptr and len.toIntern() == slice.len) return val;
4261 return Value.fromInterned(try zcu.intern(.{ .slice = .{
4340 return Value.fromInterned(try pt.intern(.{ .slice = .{
42624341 .ty = slice.ty,
42634342 .ptr = ptr.toIntern(),
42644343 .len = len.toIntern(),
......@@ -4268,22 +4347,22 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
42684347 switch (ptr.base_addr) {
42694348 .decl, .comptime_alloc, .anon_decl, .int => return val,
42704349 .comptime_field => |field_val| {
4271 const resolved_field_val = (try Value.fromInterned(field_val).resolveLazy(arena, zcu)).toIntern();
4350 const resolved_field_val = (try Value.fromInterned(field_val).resolveLazy(arena, pt)).toIntern();
42724351 return if (resolved_field_val == field_val)
42734352 val
42744353 else
4275 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4354 Value.fromInterned(try pt.intern(.{ .ptr = .{
42764355 .ty = ptr.ty,
42774356 .base_addr = .{ .comptime_field = resolved_field_val },
42784357 .byte_offset = ptr.byte_offset,
4279 } })));
4358 } }));
42804359 },
42814360 .eu_payload, .opt_payload => |base| {
4282 const resolved_base = (try Value.fromInterned(base).resolveLazy(arena, zcu)).toIntern();
4361 const resolved_base = (try Value.fromInterned(base).resolveLazy(arena, pt)).toIntern();
42834362 return if (resolved_base == base)
42844363 val
42854364 else
4286 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4365 Value.fromInterned(try pt.intern(.{ .ptr = .{
42874366 .ty = ptr.ty,
42884367 .base_addr = switch (ptr.base_addr) {
42894368 .eu_payload => .{ .eu_payload = resolved_base },
......@@ -4291,14 +4370,14 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
42914370 else => unreachable,
42924371 },
42934372 .byte_offset = ptr.byte_offset,
4294 } })));
4373 } }));
42954374 },
42964375 .arr_elem, .field => |base_index| {
4297 const resolved_base = (try Value.fromInterned(base_index.base).resolveLazy(arena, zcu)).toIntern();
4376 const resolved_base = (try Value.fromInterned(base_index.base).resolveLazy(arena, pt)).toIntern();
42984377 return if (resolved_base == base_index.base)
42994378 val
43004379 else
4301 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4380 Value.fromInterned(try pt.intern(.{ .ptr = .{
43024381 .ty = ptr.ty,
43034382 .base_addr = switch (ptr.base_addr) {
43044383 .arr_elem => .{ .arr_elem = .{
......@@ -4312,7 +4391,7 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
43124391 else => unreachable,
43134392 },
43144393 .byte_offset = ptr.byte_offset,
4315 } })));
4394 } }));
43164395 },
43174396 }
43184397 },
......@@ -4321,40 +4400,40 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
43214400 .elems => |elems| {
43224401 var resolved_elems: []InternPool.Index = &.{};
43234402 for (elems, 0..) |elem, i| {
4324 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, zcu)).toIntern();
4403 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, pt)).toIntern();
43254404 if (resolved_elems.len == 0 and resolved_elem != elem) {
43264405 resolved_elems = try arena.alloc(InternPool.Index, elems.len);
43274406 @memcpy(resolved_elems[0..i], elems[0..i]);
43284407 }
43294408 if (resolved_elems.len > 0) resolved_elems[i] = resolved_elem;
43304409 }
4331 return if (resolved_elems.len == 0) val else Value.fromInterned((try zcu.intern(.{ .aggregate = .{
4410 return if (resolved_elems.len == 0) val else Value.fromInterned(try pt.intern(.{ .aggregate = .{
43324411 .ty = aggregate.ty,
43334412 .storage = .{ .elems = resolved_elems },
4334 } })));
4413 } }));
43354414 },
43364415 .repeated_elem => |elem| {
4337 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, zcu)).toIntern();
4338 return if (resolved_elem == elem) val else Value.fromInterned((try zcu.intern(.{ .aggregate = .{
4416 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, pt)).toIntern();
4417 return if (resolved_elem == elem) val else Value.fromInterned(try pt.intern(.{ .aggregate = .{
43394418 .ty = aggregate.ty,
43404419 .storage = .{ .repeated_elem = resolved_elem },
4341 } })));
4420 } }));
43424421 },
43434422 },
43444423 .un => |un| {
43454424 const resolved_tag = if (un.tag == .none)
43464425 .none
43474426 else
4348 (try Value.fromInterned(un.tag).resolveLazy(arena, zcu)).toIntern();
4349 const resolved_val = (try Value.fromInterned(un.val).resolveLazy(arena, zcu)).toIntern();
4427 (try Value.fromInterned(un.tag).resolveLazy(arena, pt)).toIntern();
4428 const resolved_val = (try Value.fromInterned(un.val).resolveLazy(arena, pt)).toIntern();
43504429 return if (resolved_tag == un.tag and resolved_val == un.val)
43514430 val
43524431 else
4353 Value.fromInterned((try zcu.intern(.{ .un = .{
4432 Value.fromInterned(try pt.intern(.{ .un = .{
43544433 .ty = un.ty,
43554434 .tag = resolved_tag,
43564435 .val = resolved_val,
4357 } })));
4436 } }));
43584437 },
43594438 else => return val,
43604439 }
src/Zcu.zig+103-2161
......@@ -6,7 +6,6 @@ const std = @import("std");
66const builtin = @import("builtin");
77const mem = std.mem;
88const Allocator = std.mem.Allocator;
9const ArrayListUnmanaged = std.ArrayListUnmanaged;
109const assert = std.debug.assert;
1110const log = std.log.scoped(.module);
1211const BigIntConst = std.math.big.int.Const;
......@@ -75,10 +74,10 @@ local_zir_cache: Compilation.Directory,
7574
7675/// This is where all `Export` values are stored. Not all values here are necessarily valid exports;
7776/// to enumerate all exports, `single_exports` and `multi_exports` must be consulted.
78all_exports: ArrayListUnmanaged(Export) = .{},
77all_exports: std.ArrayListUnmanaged(Export) = .{},
7978/// This is a list of free indices in `all_exports`. These indices may be reused by exports from
8079/// future semantic analysis.
81free_exports: ArrayListUnmanaged(u32) = .{},
80free_exports: std.ArrayListUnmanaged(u32) = .{},
8281/// Maps from an `AnalUnit` which performs a single export, to the index into `all_exports` of
8382/// the export it performs. Note that the key is not the `Decl` being exported, but the `AnalUnit`
8483/// whose analysis triggered the export.
......@@ -179,7 +178,7 @@ stage1_flags: packed struct {
179178 reserved: u2 = 0,
180179} = .{},
181180
182compile_log_text: ArrayListUnmanaged(u8) = .{},
181compile_log_text: std.ArrayListUnmanaged(u8) = .{},
183182
184183emit_h: ?*GlobalEmitH,
185184
......@@ -203,6 +202,8 @@ panic_messages: [PanicId.len]Decl.OptionalIndex = .{.none} ** PanicId.len,
203202panic_func_index: InternPool.Index = .none,
204203null_stack_trace: InternPool.Index = .none,
205204
205pub const PerThread = @import("Zcu/PerThread.zig");
206
206207pub const PanicId = enum {
207208 unreach,
208209 unwrap_null,
......@@ -519,24 +520,24 @@ pub const Decl = struct {
519520 return decl.getExternDecl(zcu) != .none;
520521 }
521522
522 pub fn getAlignment(decl: Decl, zcu: *Zcu) Alignment {
523 pub fn getAlignment(decl: Decl, pt: Zcu.PerThread) Alignment {
523524 assert(decl.has_tv);
524525 if (decl.alignment != .none) return decl.alignment;
525 return decl.typeOf(zcu).abiAlignment(zcu);
526 return decl.typeOf(pt.zcu).abiAlignment(pt);
526527 }
527528
528 pub fn declPtrType(decl: Decl, zcu: *Zcu) !Type {
529 pub fn declPtrType(decl: Decl, pt: Zcu.PerThread) !Type {
529530 assert(decl.has_tv);
530 const decl_ty = decl.typeOf(zcu);
531 return zcu.ptrType(.{
531 const decl_ty = decl.typeOf(pt.zcu);
532 return pt.ptrType(.{
532533 .child = decl_ty.toIntern(),
533534 .flags = .{
534 .alignment = if (decl.alignment == decl_ty.abiAlignment(zcu))
535 .alignment = if (decl.alignment == decl_ty.abiAlignment(pt))
535536 .none
536537 else
537538 decl.alignment,
538539 .address_space = decl.@"addrspace",
539 .is_const = decl.getOwnedVariable(zcu) == null,
540 .is_const = decl.getOwnedVariable(pt.zcu) == null,
540541 },
541542 });
542543 }
......@@ -589,7 +590,7 @@ pub const Decl = struct {
589590
590591/// This state is attached to every Decl when Module emit_h is non-null.
591592pub const EmitH = struct {
592 fwd_decl: ArrayListUnmanaged(u8) = .{},
593 fwd_decl: std.ArrayListUnmanaged(u8) = .{},
593594};
594595
595596pub const DeclAdapter = struct {
......@@ -622,8 +623,8 @@ pub const Namespace = struct {
622623 /// Value is whether the usingnamespace decl is marked `pub`.
623624 usingnamespace_set: std.AutoHashMapUnmanaged(Decl.Index, bool) = .{},
624625
625 const Index = InternPool.NamespaceIndex;
626 const OptionalIndex = InternPool.OptionalNamespaceIndex;
626 pub const Index = InternPool.NamespaceIndex;
627 pub const OptionalIndex = InternPool.OptionalNamespaceIndex;
627628
628629 const DeclContext = struct {
629630 zcu: *Zcu,
......@@ -3079,7 +3080,7 @@ pub fn markDependeeOutdated(zcu: *Zcu, dependee: InternPool.Dependee) !void {
30793080 }
30803081}
30813082
3082fn markPoDependeeUpToDate(zcu: *Zcu, dependee: InternPool.Dependee) !void {
3083pub fn markPoDependeeUpToDate(zcu: *Zcu, dependee: InternPool.Dependee) !void {
30833084 var it = zcu.intern_pool.dependencyIterator(dependee);
30843085 while (it.next()) |depender| {
30853086 if (zcu.outdated.getPtr(depender)) |po_dep_count| {
......@@ -3279,7 +3280,7 @@ pub fn mapOldZirToNew(
32793280 old_inst: Zir.Inst.Index,
32803281 new_inst: Zir.Inst.Index,
32813282 };
3282 var match_stack: ArrayListUnmanaged(MatchedZirDecl) = .{};
3283 var match_stack: std.ArrayListUnmanaged(MatchedZirDecl) = .{};
32833284 defer match_stack.deinit(gpa);
32843285
32853286 // Main struct inst is always matched
......@@ -3394,357 +3395,6 @@ pub fn mapOldZirToNew(
33943395 }
33953396}
33963397
3397/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
3398pub fn ensureFileAnalyzed(zcu: *Zcu, file_index: File.Index) SemaError!void {
3399 if (zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
3400 return zcu.ensureDeclAnalyzed(existing_root);
3401 } else {
3402 return zcu.semaFile(file_index);
3403 }
3404}
3405
3406/// This ensures that the Decl will have an up-to-date Type and Value populated.
3407/// However the resolution status of the Type may not be fully resolved.
3408/// For example an inferred error set is not resolved until after `analyzeFnBody`.
3409/// is called.
3410pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {
3411 const tracy = trace(@src());
3412 defer tracy.end();
3413
3414 const ip = &mod.intern_pool;
3415 const decl = mod.declPtr(decl_index);
3416
3417 log.debug("ensureDeclAnalyzed '{d}' (name '{}')", .{
3418 @intFromEnum(decl_index),
3419 decl.name.fmt(ip),
3420 });
3421
3422 // Determine whether or not this Decl is outdated, i.e. requires re-analysis
3423 // even if `complete`. If a Decl is PO, we pessismistically assume that it
3424 // *does* require re-analysis, to ensure that the Decl is definitely
3425 // up-to-date when this function returns.
3426
3427 // If analysis occurs in a poor order, this could result in over-analysis.
3428 // We do our best to avoid this by the other dependency logic in this file
3429 // which tries to limit re-analysis to Decls whose previously listed
3430 // dependencies are all up-to-date.
3431
3432 const decl_as_depender = AnalUnit.wrap(.{ .decl = decl_index });
3433 const decl_was_outdated = mod.outdated.swapRemove(decl_as_depender) or
3434 mod.potentially_outdated.swapRemove(decl_as_depender);
3435
3436 if (decl_was_outdated) {
3437 _ = mod.outdated_ready.swapRemove(decl_as_depender);
3438 }
3439
3440 const was_outdated = mod.outdated_file_root.swapRemove(decl_index) or decl_was_outdated;
3441
3442 switch (decl.analysis) {
3443 .in_progress => unreachable,
3444
3445 .file_failure => return error.AnalysisFail,
3446
3447 .sema_failure,
3448 .dependency_failure,
3449 .codegen_failure,
3450 => if (!was_outdated) return error.AnalysisFail,
3451
3452 .complete => if (!was_outdated) return,
3453
3454 .unreferenced => {},
3455 }
3456
3457 if (was_outdated) {
3458 // The exports this Decl performs will be re-discovered, so we remove them here
3459 // prior to re-analysis.
3460 if (build_options.only_c) unreachable;
3461 mod.deleteUnitExports(decl_as_depender);
3462 mod.deleteUnitReferences(decl_as_depender);
3463 }
3464
3465 const sema_result: SemaDeclResult = blk: {
3466 if (decl.zir_decl_index == .none and !mod.declIsRoot(decl_index)) {
3467 // Anonymous decl. We don't semantically analyze these.
3468 break :blk .{
3469 .invalidate_decl_val = false,
3470 .invalidate_decl_ref = false,
3471 };
3472 }
3473
3474 if (mod.declIsRoot(decl_index)) {
3475 const changed = try mod.semaFileUpdate(decl.getFileScopeIndex(mod), decl_was_outdated);
3476 break :blk .{
3477 .invalidate_decl_val = changed,
3478 .invalidate_decl_ref = changed,
3479 };
3480 }
3481
3482 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
3483 defer decl_prog_node.end();
3484
3485 break :blk mod.semaDecl(decl_index) catch |err| switch (err) {
3486 error.AnalysisFail => {
3487 if (decl.analysis == .in_progress) {
3488 // If this decl caused the compile error, the analysis field would
3489 // be changed to indicate it was this Decl's fault. Because this
3490 // did not happen, we infer here that it was a dependency failure.
3491 decl.analysis = .dependency_failure;
3492 }
3493 return error.AnalysisFail;
3494 },
3495 error.GenericPoison => unreachable,
3496 else => |e| {
3497 decl.analysis = .sema_failure;
3498 try mod.failed_analysis.ensureUnusedCapacity(mod.gpa, 1);
3499 try mod.retryable_failures.append(mod.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
3500 mod.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .decl = decl_index }), try ErrorMsg.create(
3501 mod.gpa,
3502 decl.navSrcLoc(mod),
3503 "unable to analyze: {s}",
3504 .{@errorName(e)},
3505 ));
3506 return error.AnalysisFail;
3507 },
3508 };
3509 };
3510
3511 // TODO: we do not yet have separate dependencies for decl values vs types.
3512 if (decl_was_outdated) {
3513 if (sema_result.invalidate_decl_val or sema_result.invalidate_decl_ref) {
3514 log.debug("Decl tv invalidated ('{d}')", .{@intFromEnum(decl_index)});
3515 // This dependency was marked as PO, meaning dependees were waiting
3516 // on its analysis result, and it has turned out to be outdated.
3517 // Update dependees accordingly.
3518 try mod.markDependeeOutdated(.{ .decl_val = decl_index });
3519 } else {
3520 log.debug("Decl tv up-to-date ('{d}')", .{@intFromEnum(decl_index)});
3521 // This dependency was previously PO, but turned out to be up-to-date.
3522 // We do not need to queue successive analysis.
3523 try mod.markPoDependeeUpToDate(.{ .decl_val = decl_index });
3524 }
3525 }
3526}
3527
3528pub fn ensureFuncBodyAnalyzed(zcu: *Zcu, maybe_coerced_func_index: InternPool.Index) SemaError!void {
3529 const tracy = trace(@src());
3530 defer tracy.end();
3531
3532 const gpa = zcu.gpa;
3533 const ip = &zcu.intern_pool;
3534
3535 // We only care about the uncoerced function.
3536 // We need to do this for the "orphaned function" check below to be valid.
3537 const func_index = ip.unwrapCoercedFunc(maybe_coerced_func_index);
3538
3539 const func = zcu.funcInfo(maybe_coerced_func_index);
3540 const decl_index = func.owner_decl;
3541 const decl = zcu.declPtr(decl_index);
3542
3543 log.debug("ensureFuncBodyAnalyzed '{d}' (instance of '{}')", .{
3544 @intFromEnum(func_index),
3545 decl.name.fmt(ip),
3546 });
3547
3548 // First, our owner decl must be up-to-date. This will always be the case
3549 // during the first update, but may not on successive updates if we happen
3550 // to get analyzed before our parent decl.
3551 try zcu.ensureDeclAnalyzed(decl_index);
3552
3553 // On an update, it's possible this function changed such that our owner
3554 // decl now refers to a different function, making this one orphaned. If
3555 // that's the case, we should remove this function from the binary.
3556 if (decl.val.ip_index != func_index) {
3557 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
3558 ip.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .func = func_index }));
3559 ip.remove(func_index);
3560 @panic("TODO: remove orphaned function from binary");
3561 }
3562
3563 // We'll want to remember what the IES used to be before the update for
3564 // dependency invalidation purposes.
3565 const old_resolved_ies = if (func.analysis(ip).inferred_error_set)
3566 func.resolvedErrorSet(ip).*
3567 else
3568 .none;
3569
3570 switch (decl.analysis) {
3571 .unreferenced => unreachable,
3572 .in_progress => unreachable,
3573
3574 .codegen_failure => unreachable, // functions do not perform constant value generation
3575
3576 .file_failure,
3577 .sema_failure,
3578 .dependency_failure,
3579 => return error.AnalysisFail,
3580
3581 .complete => {},
3582 }
3583
3584 const func_as_depender = AnalUnit.wrap(.{ .func = func_index });
3585 const was_outdated = zcu.outdated.swapRemove(func_as_depender) or
3586 zcu.potentially_outdated.swapRemove(func_as_depender);
3587
3588 if (was_outdated) {
3589 if (build_options.only_c) unreachable;
3590 _ = zcu.outdated_ready.swapRemove(func_as_depender);
3591 zcu.deleteUnitExports(func_as_depender);
3592 zcu.deleteUnitReferences(func_as_depender);
3593 }
3594
3595 switch (func.analysis(ip).state) {
3596 .success => if (!was_outdated) return,
3597 .sema_failure,
3598 .dependency_failure,
3599 .codegen_failure,
3600 => if (!was_outdated) return error.AnalysisFail,
3601 .none, .queued => {},
3602 .in_progress => unreachable,
3603 .inline_only => unreachable, // don't queue work for this
3604 }
3605
3606 log.debug("analyze and generate fn body '{d}'; reason='{s}'", .{
3607 @intFromEnum(func_index),
3608 if (was_outdated) "outdated" else "never analyzed",
3609 });
3610
3611 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
3612 defer tmp_arena.deinit();
3613 const sema_arena = tmp_arena.allocator();
3614
3615 var air = zcu.analyzeFnBody(func_index, sema_arena) catch |err| switch (err) {
3616 error.AnalysisFail => {
3617 if (func.analysis(ip).state == .in_progress) {
3618 // If this decl caused the compile error, the analysis field would
3619 // be changed to indicate it was this Decl's fault. Because this
3620 // did not happen, we infer here that it was a dependency failure.
3621 func.analysis(ip).state = .dependency_failure;
3622 }
3623 return error.AnalysisFail;
3624 },
3625 error.OutOfMemory => return error.OutOfMemory,
3626 };
3627 errdefer air.deinit(gpa);
3628
3629 const invalidate_ies_deps = i: {
3630 if (!was_outdated) break :i false;
3631 if (!func.analysis(ip).inferred_error_set) break :i true;
3632 const new_resolved_ies = func.resolvedErrorSet(ip).*;
3633 break :i new_resolved_ies != old_resolved_ies;
3634 };
3635 if (invalidate_ies_deps) {
3636 log.debug("func IES invalidated ('{d}')", .{@intFromEnum(func_index)});
3637 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
3638 } else if (was_outdated) {
3639 log.debug("func IES up-to-date ('{d}')", .{@intFromEnum(func_index)});
3640 try zcu.markPoDependeeUpToDate(.{ .func_ies = func_index });
3641 }
3642
3643 const comp = zcu.comp;
3644
3645 const dump_air = build_options.enable_debug_extensions and comp.verbose_air;
3646 const dump_llvm_ir = build_options.enable_debug_extensions and (comp.verbose_llvm_ir != null or comp.verbose_llvm_bc != null);
3647
3648 if (comp.bin_file == null and zcu.llvm_object == null and !dump_air and !dump_llvm_ir) {
3649 air.deinit(gpa);
3650 return;
3651 }
3652
3653 try comp.work_queue.writeItem(.{ .codegen_func = .{
3654 .func = func_index,
3655 .air = air,
3656 } });
3657}
3658
3659/// Takes ownership of `air`, even on error.
3660/// If any types referenced by `air` are unresolved, marks the codegen as failed.
3661pub fn linkerUpdateFunc(zcu: *Zcu, func_index: InternPool.Index, air: Air) Allocator.Error!void {
3662 const gpa = zcu.gpa;
3663 const ip = &zcu.intern_pool;
3664 const comp = zcu.comp;
3665
3666 defer {
3667 var air_mut = air;
3668 air_mut.deinit(gpa);
3669 }
3670
3671 const func = zcu.funcInfo(func_index);
3672 const decl_index = func.owner_decl;
3673 const decl = zcu.declPtr(decl_index);
3674
3675 var liveness = try Liveness.analyze(gpa, air, ip);
3676 defer liveness.deinit(gpa);
3677
3678 if (build_options.enable_debug_extensions and comp.verbose_air) {
3679 const fqn = try decl.fullyQualifiedName(zcu);
3680 std.debug.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)});
3681 @import("print_air.zig").dump(zcu, air, liveness);
3682 std.debug.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)});
3683 }
3684
3685 if (std.debug.runtime_safety) {
3686 var verify: Liveness.Verify = .{
3687 .gpa = gpa,
3688 .air = air,
3689 .liveness = liveness,
3690 .intern_pool = ip,
3691 };
3692 defer verify.deinit();
3693
3694 verify.verify() catch |err| switch (err) {
3695 error.OutOfMemory => return error.OutOfMemory,
3696 else => {
3697 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3698 zcu.failed_analysis.putAssumeCapacityNoClobber(
3699 AnalUnit.wrap(.{ .func = func_index }),
3700 try Module.ErrorMsg.create(
3701 gpa,
3702 decl.navSrcLoc(zcu),
3703 "invalid liveness: {s}",
3704 .{@errorName(err)},
3705 ),
3706 );
3707 func.analysis(ip).state = .codegen_failure;
3708 return;
3709 },
3710 };
3711 }
3712
3713 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(ip), 0);
3714 defer codegen_prog_node.end();
3715
3716 if (!air.typesFullyResolved(zcu)) {
3717 // A type we depend on failed to resolve. This is a transitive failure.
3718 // Correcting this failure will involve changing a type this function
3719 // depends on, hence triggering re-analysis of this function, so this
3720 // interacts correctly with incremental compilation.
3721 func.analysis(ip).state = .codegen_failure;
3722 } else if (comp.bin_file) |lf| {
3723 lf.updateFunc(zcu, func_index, air, liveness) catch |err| switch (err) {
3724 error.OutOfMemory => return error.OutOfMemory,
3725 error.AnalysisFail => {
3726 func.analysis(ip).state = .codegen_failure;
3727 },
3728 else => {
3729 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3730 zcu.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .func = func_index }), try Module.ErrorMsg.create(
3731 gpa,
3732 decl.navSrcLoc(zcu),
3733 "unable to codegen: {s}",
3734 .{@errorName(err)},
3735 ));
3736 func.analysis(ip).state = .codegen_failure;
3737 try zcu.retryable_failures.append(zcu.gpa, AnalUnit.wrap(.{ .func = func_index }));
3738 },
3739 };
3740 } else if (zcu.llvm_object) |llvm_object| {
3741 if (build_options.only_c) unreachable;
3742 llvm_object.updateFunc(zcu, func_index, air, liveness) catch |err| switch (err) {
3743 error.OutOfMemory => return error.OutOfMemory,
3744 };
3745 }
3746}
3747
37483398/// Ensure this function's body is or will be analyzed and emitted. This should
37493399/// be called whenever a potential runtime call of a function is seen.
37503400///
......@@ -3804,608 +3454,105 @@ pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index)
38043454 func.analysis(ip).state = .queued;
38053455}
38063456
3807pub fn semaPkg(zcu: *Zcu, pkg: *Package.Module) !void {
3808 const import_file_result = try zcu.importPkg(pkg);
3809 const root_decl_index = zcu.fileRootDecl(import_file_result.file_index);
3810 if (root_decl_index == .none) {
3811 return zcu.semaFile(import_file_result.file_index);
3812 }
3813}
3814
3815fn getFileRootStruct(
3816 zcu: *Zcu,
3817 decl_index: Decl.Index,
3818 namespace_index: Namespace.Index,
3819 file_index: File.Index,
3820) Allocator.Error!InternPool.Index {
3821 const gpa = zcu.gpa;
3822 const ip = &zcu.intern_pool;
3823 const file = zcu.fileByIndex(file_index);
3824 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
3825 assert(extended.opcode == .struct_decl);
3826 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
3827 assert(!small.has_captures_len);
3828 assert(!small.has_backing_int);
3829 assert(small.layout == .auto);
3830 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
3831 const fields_len = if (small.has_fields_len) blk: {
3832 const fields_len = file.zir.extra[extra_index];
3833 extra_index += 1;
3834 break :blk fields_len;
3835 } else 0;
3836 const decls_len = if (small.has_decls_len) blk: {
3837 const decls_len = file.zir.extra[extra_index];
3838 extra_index += 1;
3839 break :blk decls_len;
3840 } else 0;
3841 const decls = file.zir.bodySlice(extra_index, decls_len);
3842 extra_index += decls_len;
3843
3844 const tracked_inst = try ip.trackZir(gpa, file_index, .main_struct_inst);
3845 const wip_ty = switch (try ip.getStructType(gpa, .{
3846 .layout = .auto,
3847 .fields_len = fields_len,
3848 .known_non_opv = small.known_non_opv,
3849 .requires_comptime = if (small.known_comptime_only) .yes else .unknown,
3850 .is_tuple = small.is_tuple,
3851 .any_comptime_fields = small.any_comptime_fields,
3852 .any_default_inits = small.any_default_inits,
3853 .inits_resolved = false,
3854 .any_aligned_fields = small.any_aligned_fields,
3855 .has_namespace = true,
3856 .key = .{ .declared = .{
3857 .zir_index = tracked_inst,
3858 .captures = &.{},
3859 } },
3860 })) {
3861 .existing => unreachable, // we wouldn't be analysing the file root if this type existed
3862 .wip => |wip| wip,
3863 };
3864 errdefer wip_ty.cancel(ip);
3865
3866 if (zcu.comp.debug_incremental) {
3867 try ip.addDependency(
3868 gpa,
3869 AnalUnit.wrap(.{ .decl = decl_index }),
3870 .{ .src_hash = tracked_inst },
3871 );
3872 }
3457pub const SemaDeclResult = packed struct {
3458 /// Whether the value of a `decl_val` of this Decl changed.
3459 invalidate_decl_val: bool,
3460 /// Whether the type of a `decl_ref` of this Decl changed.
3461 invalidate_decl_ref: bool,
3462};
38733463
3464pub fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
38743465 const decl = zcu.declPtr(decl_index);
3875 decl.val = Value.fromInterned(wip_ty.index);
3876 decl.has_tv = true;
3877 decl.owns_tv = true;
3878 decl.analysis = .complete;
3879
3880 try zcu.scanNamespace(namespace_index, decls, decl);
3881 try zcu.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
3882 return wip_ty.finish(ip, decl_index, namespace_index.toOptional());
3883}
3884
3885/// Re-analyze the root Decl of a file on an incremental update.
3886/// If `type_outdated`, the struct type itself is considered outdated and is
3887/// reconstructed at a new InternPool index. Otherwise, the namespace is just
3888/// re-analyzed. Returns whether the decl's tyval was invalidated.
3889fn semaFileUpdate(zcu: *Zcu, file_index: File.Index, type_outdated: bool) SemaError!bool {
3890 const file = zcu.fileByIndex(file_index);
3891 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
3892
3893 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
3894 file.mod.fully_qualified_name,
3895 file.sub_file_path,
3896 type_outdated,
3897 });
3898
3899 if (file.status != .success_zir) {
3900 if (decl.analysis == .file_failure) {
3901 return false;
3902 } else {
3903 decl.analysis = .file_failure;
3904 return true;
3905 }
3906 }
3907
3908 if (decl.analysis == .file_failure) {
3909 // No struct type currently exists. Create one!
3910 const root_decl = zcu.fileRootDecl(file_index);
3911 _ = try zcu.getFileRootStruct(root_decl.unwrap().?, decl.src_namespace, file_index);
3912 return true;
3913 }
39143466
39153467 assert(decl.has_tv);
39163468 assert(decl.owns_tv);
39173469
3918 if (type_outdated) {
3919 // Invalidate the existing type, reusing the decl and namespace.
3920 const file_root_decl = zcu.fileRootDecl(file_index).unwrap().?;
3921 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{
3922 .decl = file_root_decl,
3923 }));
3924 zcu.intern_pool.remove(decl.val.toIntern());
3925 decl.val = undefined;
3926 _ = try zcu.getFileRootStruct(file_root_decl, decl.src_namespace, file_index);
3927 return true;
3928 }
3929
3930 // Only the struct's namespace is outdated.
3931 // Preserve the type - just scan the namespace again.
3932
3933 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
3934 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
3935
3936 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
3937 extra_index += @intFromBool(small.has_fields_len);
3938 const decls_len = if (small.has_decls_len) blk: {
3939 const decls_len = file.zir.extra[extra_index];
3940 extra_index += 1;
3941 break :blk decls_len;
3942 } else 0;
3943 const decls = file.zir.bodySlice(extra_index, decls_len);
3470 log.debug("semaAnonOwnerDecl '{d}'", .{@intFromEnum(decl_index)});
39443471
3945 if (!type_outdated) {
3946 try zcu.scanNamespace(decl.src_namespace, decls, decl);
3472 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
3473 .Fn => @panic("TODO: update fn instance"),
3474 .Type => {},
3475 else => unreachable,
39473476 }
39483477
3949 return false;
3478 // We are the owner Decl of a type, and we were marked as outdated. That means the *structure*
3479 // of this type changed; not just its namespace. Therefore, we need a new InternPool index.
3480 //
3481 // However, as soon as we make that, the context that created us will require re-analysis anyway
3482 // (as it depends on this Decl's value), meaning the `struct_decl` (or equivalent) instruction
3483 // will be analyzed again. Since Sema already needs to be able to reconstruct types like this,
3484 // why should we bother implementing it here too when the Sema logic will be hit right after?
3485 //
3486 // So instead, let's just mark this Decl as failed - so that any remaining Decls which genuinely
3487 // reference it (via `@This`) end up silently erroring too - and we'll let Sema make a new type
3488 // with a new Decl.
3489 //
3490 // Yes, this does mean that any type owner Decl has a constant value for its entire lifetime.
3491 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
3492 zcu.intern_pool.remove(decl.val.toIntern());
3493 decl.analysis = .dependency_failure;
3494 return .{
3495 .invalidate_decl_val = true,
3496 .invalidate_decl_ref = true,
3497 };
39503498}
39513499
3952/// Regardless of the file status, will create a `Decl` if none exists so that we can track
3953/// dependencies and re-analyze when the file becomes outdated.
3954fn semaFile(zcu: *Zcu, file_index: File.Index) SemaError!void {
3955 const tracy = trace(@src());
3956 defer tracy.end();
3957
3958 const file = zcu.fileByIndex(file_index);
3959 assert(zcu.fileRootDecl(file_index) == .none);
3500pub const ImportFileResult = struct {
3501 file: *File,
3502 file_index: File.Index,
3503 is_new: bool,
3504 is_pkg: bool,
3505};
39603506
3507pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
39613508 const gpa = zcu.gpa;
3962 log.debug("semaFile zcu={s} sub_file_path={s}", .{
3963 file.mod.fully_qualified_name, file.sub_file_path,
3964 });
39653509
3966 // Because these three things each reference each other, `undefined`
3967 // placeholders are used before being set after the struct type gains an
3968 // InternPool index.
3969 const new_namespace_index = try zcu.createNamespace(.{
3970 .parent = .none,
3971 .decl_index = undefined,
3972 .file_scope = file_index,
3510 // The resolved path is used as the key in the import table, to detect if
3511 // an import refers to the same as another, despite different relative paths
3512 // or differently mapped package names.
3513 const resolved_path = try std.fs.path.resolve(gpa, &.{
3514 mod.root.root_dir.path orelse ".",
3515 mod.root.sub_path,
3516 mod.root_src_path,
39733517 });
3974 errdefer zcu.destroyNamespace(new_namespace_index);
3518 var keep_resolved_path = false;
3519 defer if (!keep_resolved_path) gpa.free(resolved_path);
39753520
3976 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
3977 const new_decl = zcu.declPtr(new_decl_index);
3978 errdefer @panic("TODO error handling");
3521 const gop = try zcu.import_table.getOrPut(gpa, resolved_path);
3522 errdefer _ = zcu.import_table.pop();
3523 if (gop.found_existing) {
3524 try gop.value_ptr.*.addReference(zcu.*, .{ .root = mod });
3525 return .{
3526 .file = gop.value_ptr.*,
3527 .file_index = @enumFromInt(gop.index),
3528 .is_new = false,
3529 .is_pkg = true,
3530 };
3531 }
39793532
3980 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
3981 zcu.namespacePtr(new_namespace_index).decl_index = new_decl_index;
3533 const ip = &zcu.intern_pool;
39823534
3983 new_decl.name = try file.fullyQualifiedName(zcu);
3984 new_decl.name_fully_qualified = true;
3985 new_decl.is_pub = true;
3986 new_decl.is_exported = false;
3987 new_decl.alignment = .none;
3988 new_decl.@"linksection" = .none;
3989 new_decl.analysis = .in_progress;
3535 try ip.files.ensureUnusedCapacity(gpa, 1);
39903536
3991 if (file.status != .success_zir) {
3992 new_decl.analysis = .file_failure;
3993 return;
3537 if (mod.builtin_file) |builtin_file| {
3538 keep_resolved_path = true; // It's now owned by import_table.
3539 gop.value_ptr.* = builtin_file;
3540 try builtin_file.addReference(zcu.*, .{ .root = mod });
3541 const path_digest = computePathDigest(zcu, mod, builtin_file.sub_file_path);
3542 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
3543 return .{
3544 .file = builtin_file,
3545 .file_index = @enumFromInt(ip.files.entries.len - 1),
3546 .is_new = false,
3547 .is_pkg = true,
3548 };
39943549 }
3995 assert(file.zir_loaded);
39963550
3997 const struct_ty = try zcu.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
3998 errdefer zcu.intern_pool.remove(struct_ty);
3551 const sub_file_path = try gpa.dupe(u8, mod.root_src_path);
3552 errdefer gpa.free(sub_file_path);
39993553
4000 switch (zcu.comp.cache_use) {
4001 .whole => |whole| if (whole.cache_manifest) |man| {
4002 const source = file.getSource(gpa) catch |err| {
4003 try reportRetryableFileError(zcu, file_index, "unable to load source: {s}", .{@errorName(err)});
4004 return error.AnalysisFail;
4005 };
4006
4007 const resolved_path = std.fs.path.resolve(gpa, &.{
4008 file.mod.root.root_dir.path orelse ".",
4009 file.mod.root.sub_path,
4010 file.sub_file_path,
4011 }) catch |err| {
4012 try reportRetryableFileError(zcu, file_index, "unable to resolve path: {s}", .{@errorName(err)});
4013 return error.AnalysisFail;
4014 };
4015 errdefer gpa.free(resolved_path);
4016
4017 whole.cache_manifest_mutex.lock();
4018 defer whole.cache_manifest_mutex.unlock();
4019 try man.addFilePostContents(resolved_path, source.bytes, source.stat);
4020 },
4021 .incremental => {},
4022 }
4023}
4024
4025const SemaDeclResult = packed struct {
4026 /// Whether the value of a `decl_val` of this Decl changed.
4027 invalidate_decl_val: bool,
4028 /// Whether the type of a `decl_ref` of this Decl changed.
4029 invalidate_decl_ref: bool,
4030};
4031
4032fn semaDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
4033 const tracy = trace(@src());
4034 defer tracy.end();
4035
4036 const decl = zcu.declPtr(decl_index);
4037 const ip = &zcu.intern_pool;
4038
4039 if (decl.getFileScope(zcu).status != .success_zir) {
4040 return error.AnalysisFail;
4041 }
4042
4043 assert(!zcu.declIsRoot(decl_index));
4044
4045 if (decl.zir_decl_index == .none and decl.owns_tv) {
4046 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).
4047 return zcu.semaAnonOwnerDecl(decl_index);
4048 }
4049
4050 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
4051 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(zcu)).fmt(ip)});
4052 defer blk: {
4053 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(zcu) catch break :blk).fmt(ip)});
4054 }
4055
4056 const old_has_tv = decl.has_tv;
4057 // The following values are ignored if `!old_has_tv`
4058 const old_ty = if (old_has_tv) decl.typeOf(zcu) else undefined;
4059 const old_val = decl.val;
4060 const old_align = decl.alignment;
4061 const old_linksection = decl.@"linksection";
4062 const old_addrspace = decl.@"addrspace";
4063 const old_is_inline = if (decl.getOwnedFunction(zcu)) |prev_func|
4064 prev_func.analysis(ip).state == .inline_only
4065 else
4066 false;
4067
4068 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
4069
4070 const gpa = zcu.gpa;
4071 const zir = decl.getFileScope(zcu).zir;
4072
4073 const builtin_type_target_index: InternPool.Index = ip_index: {
4074 const std_mod = zcu.std_mod;
4075 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
4076 // We're in the std module.
4077 const std_file_imported = try zcu.importPkg(std_mod);
4078 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
4079 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
4080 const std_namespace = std_decl.getInnerNamespace(zcu).?;
4081 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
4082 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
4083 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
4084 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
4085 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
4086 for ([_][]const u8{
4087 "AtomicOrder",
4088 "AtomicRmwOp",
4089 "CallingConvention",
4090 "AddressSpace",
4091 "FloatMode",
4092 "ReduceOp",
4093 "CallModifier",
4094 "PrefetchOptions",
4095 "ExportOptions",
4096 "ExternOptions",
4097 "Type",
4098 }, [_]InternPool.Index{
4099 .atomic_order_type,
4100 .atomic_rmw_op_type,
4101 .calling_convention_type,
4102 .address_space_type,
4103 .float_mode_type,
4104 .reduce_op_type,
4105 .call_modifier_type,
4106 .prefetch_options_type,
4107 .export_options_type,
4108 .extern_options_type,
4109 .type_info_type,
4110 }) |type_name, type_ip| {
4111 if (decl.name.eqlSlice(type_name, ip)) break :ip_index type_ip;
4112 }
4113 break :ip_index .none;
4114 };
4115
4116 zcu.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));
4117
4118 decl.analysis = .in_progress;
4119
4120 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
4121 defer analysis_arena.deinit();
4122
4123 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
4124 defer comptime_err_ret_trace.deinit();
4125
4126 var sema: Sema = .{
4127 .mod = zcu,
4128 .gpa = gpa,
4129 .arena = analysis_arena.allocator(),
4130 .code = zir,
4131 .owner_decl = decl,
4132 .owner_decl_index = decl_index,
4133 .func_index = .none,
4134 .func_is_naked = false,
4135 .fn_ret_ty = Type.void,
4136 .fn_ret_ty_ies = null,
4137 .owner_func_index = .none,
4138 .comptime_err_ret_trace = &comptime_err_ret_trace,
4139 .builtin_type_target_index = builtin_type_target_index,
4140 };
4141 defer sema.deinit();
4142
4143 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
4144 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
4145 gpa,
4146 decl.getFileScopeIndex(zcu),
4147 decl_inst,
4148 ) });
4149
4150 var block_scope: Sema.Block = .{
4151 .parent = null,
4152 .sema = &sema,
4153 .namespace = decl.src_namespace,
4154 .instructions = .{},
4155 .inlining = null,
4156 .is_comptime = true,
4157 .src_base_inst = decl.zir_decl_index.unwrap().?,
4158 .type_name_ctx = decl.name,
4159 };
4160 defer block_scope.instructions.deinit(gpa);
4161
4162 const decl_bodies = decl.zirBodies(zcu);
4163
4164 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
4165 // We'll do some other bits with the Sema. Clear the type target index just
4166 // in case they analyze any type.
4167 sema.builtin_type_target_index = .none;
4168 const align_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_align = 0 });
4169 const section_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_section = 0 });
4170 const address_space_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_addrspace = 0 });
4171 const ty_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
4172 const init_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_init = 0 });
4173 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);
4174 const decl_ty = decl_val.typeOf(zcu);
4175
4176 // Note this resolves the type of the Decl, not the value; if this Decl
4177 // is a struct, for example, this resolves `type` (which needs no resolution),
4178 // not the struct itself.
4179 try decl_ty.resolveLayout(zcu);
4180
4181 if (decl.kind == .@"usingnamespace") {
4182 if (!decl_ty.eql(Type.type, zcu)) {
4183 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{
4184 decl_ty.fmt(zcu),
4185 });
4186 }
4187 const ty = decl_val.toType();
4188 if (ty.getNamespace(zcu) == null) {
4189 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(zcu)});
4190 }
4191
4192 decl.val = ty.toValue();
4193 decl.alignment = .none;
4194 decl.@"linksection" = .none;
4195 decl.has_tv = true;
4196 decl.owns_tv = false;
4197 decl.analysis = .complete;
4198
4199 // TODO: usingnamespace cannot currently participate in incremental compilation
4200 return .{
4201 .invalidate_decl_val = true,
4202 .invalidate_decl_ref = true,
4203 };
4204 }
4205
4206 var queue_linker_work = true;
4207 var is_func = false;
4208 var is_inline = false;
4209 switch (decl_val.toIntern()) {
4210 .generic_poison => unreachable,
4211 .unreachable_value => unreachable,
4212 else => switch (ip.indexToKey(decl_val.toIntern())) {
4213 .variable => |variable| {
4214 decl.owns_tv = variable.decl == decl_index;
4215 queue_linker_work = decl.owns_tv;
4216 },
4217
4218 .extern_func => |extern_func| {
4219 decl.owns_tv = extern_func.decl == decl_index;
4220 queue_linker_work = decl.owns_tv;
4221 is_func = decl.owns_tv;
4222 },
4223
4224 .func => |func| {
4225 decl.owns_tv = func.owner_decl == decl_index;
4226 queue_linker_work = false;
4227 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(zcu) == .Inline;
4228 is_func = decl.owns_tv;
4229 },
4230
4231 else => {},
4232 },
4233 }
4234
4235 decl.val = decl_val;
4236 // Function linksection, align, and addrspace were already set by Sema
4237 if (!is_func) {
4238 decl.alignment = blk: {
4239 const align_body = decl_bodies.align_body orelse break :blk .none;
4240 const align_ref = try sema.resolveInlineBody(&block_scope, align_body, decl_inst);
4241 break :blk try sema.analyzeAsAlign(&block_scope, align_src, align_ref);
4242 };
4243 decl.@"linksection" = blk: {
4244 const linksection_body = decl_bodies.linksection_body orelse break :blk .none;
4245 const linksection_ref = try sema.resolveInlineBody(&block_scope, linksection_body, decl_inst);
4246 const bytes = try sema.toConstString(&block_scope, section_src, linksection_ref, .{
4247 .needed_comptime_reason = "linksection must be comptime-known",
4248 });
4249 if (mem.indexOfScalar(u8, bytes, 0) != null) {
4250 return sema.fail(&block_scope, section_src, "linksection cannot contain null bytes", .{});
4251 } else if (bytes.len == 0) {
4252 return sema.fail(&block_scope, section_src, "linksection cannot be empty", .{});
4253 }
4254 break :blk try ip.getOrPutStringOpt(gpa, bytes, .no_embedded_nulls);
4255 };
4256 decl.@"addrspace" = blk: {
4257 const addrspace_ctx: Sema.AddressSpaceContext = switch (ip.indexToKey(decl_val.toIntern())) {
4258 .variable => .variable,
4259 .extern_func, .func => .function,
4260 else => .constant,
4261 };
4262
4263 const target = sema.mod.getTarget();
4264
4265 const addrspace_body = decl_bodies.addrspace_body orelse break :blk switch (addrspace_ctx) {
4266 .function => target_util.defaultAddressSpace(target, .function),
4267 .variable => target_util.defaultAddressSpace(target, .global_mutable),
4268 .constant => target_util.defaultAddressSpace(target, .global_constant),
4269 else => unreachable,
4270 };
4271 const addrspace_ref = try sema.resolveInlineBody(&block_scope, addrspace_body, decl_inst);
4272 break :blk try sema.analyzeAsAddressSpace(&block_scope, address_space_src, addrspace_ref, addrspace_ctx);
4273 };
4274 }
4275 decl.has_tv = true;
4276 decl.analysis = .complete;
4277
4278 const result: SemaDeclResult = if (old_has_tv) .{
4279 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
4280 !decl.val.eql(old_val, decl_ty, zcu) or
4281 is_inline != old_is_inline,
4282 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
4283 decl.alignment != old_align or
4284 decl.@"linksection" != old_linksection or
4285 decl.@"addrspace" != old_addrspace or
4286 is_inline != old_is_inline,
4287 } else .{
4288 .invalidate_decl_val = true,
4289 .invalidate_decl_ref = true,
4290 };
4291
4292 const has_runtime_bits = queue_linker_work and (is_func or try sema.typeHasRuntimeBits(decl_ty));
4293 if (has_runtime_bits) {
4294 // Needed for codegen_decl which will call updateDecl and then the
4295 // codegen backend wants full access to the Decl Type.
4296 try decl_ty.resolveFully(zcu);
4297
4298 try zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
4299
4300 if (result.invalidate_decl_ref and zcu.emit_h != null) {
4301 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
4302 }
4303 }
4304
4305 if (decl.is_exported) {
4306 const export_src: LazySrcLoc = block_scope.src(.{ .token_offset = @intFromBool(decl.is_pub) });
4307 if (is_inline) return sema.fail(&block_scope, export_src, "export of inline function", .{});
4308 // The scope needs to have the decl in it.
4309 try sema.analyzeExport(&block_scope, export_src, .{ .name = decl.name }, decl_index);
4310 }
4311
4312 try sema.flushExports();
4313
4314 return result;
4315}
4316
4317fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
4318 const decl = zcu.declPtr(decl_index);
4319
4320 assert(decl.has_tv);
4321 assert(decl.owns_tv);
4322
4323 log.debug("semaAnonOwnerDecl '{d}'", .{@intFromEnum(decl_index)});
4324
4325 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
4326 .Fn => @panic("TODO: update fn instance"),
4327 .Type => {},
4328 else => unreachable,
4329 }
4330
4331 // We are the owner Decl of a type, and we were marked as outdated. That means the *structure*
4332 // of this type changed; not just its namespace. Therefore, we need a new InternPool index.
4333 //
4334 // However, as soon as we make that, the context that created us will require re-analysis anyway
4335 // (as it depends on this Decl's value), meaning the `struct_decl` (or equivalent) instruction
4336 // will be analyzed again. Since Sema already needs to be able to reconstruct types like this,
4337 // why should we bother implementing it here too when the Sema logic will be hit right after?
4338 //
4339 // So instead, let's just mark this Decl as failed - so that any remaining Decls which genuinely
4340 // reference it (via `@This`) end up silently erroring too - and we'll let Sema make a new type
4341 // with a new Decl.
4342 //
4343 // Yes, this does mean that any type owner Decl has a constant value for its entire lifetime.
4344 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
4345 zcu.intern_pool.remove(decl.val.toIntern());
4346 decl.analysis = .dependency_failure;
4347 return .{
4348 .invalidate_decl_val = true,
4349 .invalidate_decl_ref = true,
4350 };
4351}
4352
4353pub const ImportFileResult = struct {
4354 file: *File,
4355 file_index: File.Index,
4356 is_new: bool,
4357 is_pkg: bool,
4358};
4359
4360pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
4361 const gpa = zcu.gpa;
4362
4363 // The resolved path is used as the key in the import table, to detect if
4364 // an import refers to the same as another, despite different relative paths
4365 // or differently mapped package names.
4366 const resolved_path = try std.fs.path.resolve(gpa, &.{
4367 mod.root.root_dir.path orelse ".",
4368 mod.root.sub_path,
4369 mod.root_src_path,
4370 });
4371 var keep_resolved_path = false;
4372 defer if (!keep_resolved_path) gpa.free(resolved_path);
4373
4374 const gop = try zcu.import_table.getOrPut(gpa, resolved_path);
4375 errdefer _ = zcu.import_table.pop();
4376 if (gop.found_existing) {
4377 try gop.value_ptr.*.addReference(zcu.*, .{ .root = mod });
4378 return .{
4379 .file = gop.value_ptr.*,
4380 .file_index = @enumFromInt(gop.index),
4381 .is_new = false,
4382 .is_pkg = true,
4383 };
4384 }
4385
4386 const ip = &zcu.intern_pool;
4387
4388 try ip.files.ensureUnusedCapacity(gpa, 1);
4389
4390 if (mod.builtin_file) |builtin_file| {
4391 keep_resolved_path = true; // It's now owned by import_table.
4392 gop.value_ptr.* = builtin_file;
4393 try builtin_file.addReference(zcu.*, .{ .root = mod });
4394 const path_digest = computePathDigest(zcu, mod, builtin_file.sub_file_path);
4395 ip.files.putAssumeCapacityNoClobber(path_digest, .none);
4396 return .{
4397 .file = builtin_file,
4398 .file_index = @enumFromInt(ip.files.entries.len - 1),
4399 .is_new = false,
4400 .is_pkg = true,
4401 };
4402 }
4403
4404 const sub_file_path = try gpa.dupe(u8, mod.root_src_path);
4405 errdefer gpa.free(sub_file_path);
4406
4407 const new_file = try gpa.create(File);
4408 errdefer gpa.destroy(new_file);
3554 const new_file = try gpa.create(File);
3555 errdefer gpa.destroy(new_file);
44093556
44103557 keep_resolved_path = true; // It's now owned by import_table.
44113558 gop.value_ptr.* = new_file;
......@@ -4533,78 +3680,6 @@ pub fn importFile(
45333680 };
45343681}
45353682
4536pub fn embedFile(
4537 mod: *Module,
4538 cur_file: *File,
4539 import_string: []const u8,
4540 src_loc: LazySrcLoc,
4541) !InternPool.Index {
4542 const gpa = mod.gpa;
4543
4544 if (cur_file.mod.deps.get(import_string)) |pkg| {
4545 const resolved_path = try std.fs.path.resolve(gpa, &.{
4546 pkg.root.root_dir.path orelse ".",
4547 pkg.root.sub_path,
4548 pkg.root_src_path,
4549 });
4550 var keep_resolved_path = false;
4551 defer if (!keep_resolved_path) gpa.free(resolved_path);
4552
4553 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
4554 errdefer {
4555 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
4556 keep_resolved_path = false;
4557 }
4558 if (gop.found_existing) return gop.value_ptr.*.val;
4559 keep_resolved_path = true;
4560
4561 const sub_file_path = try gpa.dupe(u8, pkg.root_src_path);
4562 errdefer gpa.free(sub_file_path);
4563
4564 return newEmbedFile(mod, pkg, sub_file_path, resolved_path, gop.value_ptr, src_loc);
4565 }
4566
4567 // The resolved path is used as the key in the table, to detect if a file
4568 // refers to the same as another, despite different relative paths.
4569 const resolved_path = try std.fs.path.resolve(gpa, &.{
4570 cur_file.mod.root.root_dir.path orelse ".",
4571 cur_file.mod.root.sub_path,
4572 cur_file.sub_file_path,
4573 "..",
4574 import_string,
4575 });
4576
4577 var keep_resolved_path = false;
4578 defer if (!keep_resolved_path) gpa.free(resolved_path);
4579
4580 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
4581 errdefer {
4582 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
4583 keep_resolved_path = false;
4584 }
4585 if (gop.found_existing) return gop.value_ptr.*.val;
4586 keep_resolved_path = true;
4587
4588 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
4589 cur_file.mod.root.root_dir.path orelse ".",
4590 cur_file.mod.root.sub_path,
4591 });
4592 defer gpa.free(resolved_root_path);
4593
4594 const sub_file_path = p: {
4595 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
4596 errdefer gpa.free(relative);
4597
4598 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
4599 break :p relative;
4600 }
4601 return error.ImportOutsideModulePath;
4602 };
4603 defer gpa.free(sub_file_path);
4604
4605 return newEmbedFile(mod, cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
4606}
4607
46083683fn computePathDigest(zcu: *Zcu, mod: *Package.Module, sub_file_path: []const u8) Cache.BinDigest {
46093684 const want_local_cache = mod == zcu.main_mod;
46103685 var path_hash: Cache.HashHelper = .{};
......@@ -4620,87 +3695,6 @@ fn computePathDigest(zcu: *Zcu, mod: *Package.Module, sub_file_path: []const u8)
46203695 return bin;
46213696}
46223697
4623/// https://github.com/ziglang/zig/issues/14307
4624fn newEmbedFile(
4625 mod: *Module,
4626 pkg: *Package.Module,
4627 sub_file_path: []const u8,
4628 resolved_path: []const u8,
4629 result: **EmbedFile,
4630 src_loc: LazySrcLoc,
4631) !InternPool.Index {
4632 const gpa = mod.gpa;
4633 const ip = &mod.intern_pool;
4634
4635 const new_file = try gpa.create(EmbedFile);
4636 errdefer gpa.destroy(new_file);
4637
4638 var file = try pkg.root.openFile(sub_file_path, .{});
4639 defer file.close();
4640
4641 const actual_stat = try file.stat();
4642 const stat: Cache.File.Stat = .{
4643 .size = actual_stat.size,
4644 .inode = actual_stat.inode,
4645 .mtime = actual_stat.mtime,
4646 };
4647 const size = std.math.cast(usize, actual_stat.size) orelse return error.Overflow;
4648
4649 const bytes = try ip.string_bytes.addManyAsSlice(gpa, try std.math.add(usize, size, 1));
4650 const actual_read = try file.readAll(bytes[0..size]);
4651 if (actual_read != size) return error.UnexpectedEndOfFile;
4652 bytes[size] = 0;
4653
4654 const comp = mod.comp;
4655 switch (comp.cache_use) {
4656 .whole => |whole| if (whole.cache_manifest) |man| {
4657 const copied_resolved_path = try gpa.dupe(u8, resolved_path);
4658 errdefer gpa.free(copied_resolved_path);
4659 whole.cache_manifest_mutex.lock();
4660 defer whole.cache_manifest_mutex.unlock();
4661 try man.addFilePostContents(copied_resolved_path, bytes[0..size], stat);
4662 },
4663 .incremental => {},
4664 }
4665
4666 const array_ty = try ip.get(gpa, .{ .array_type = .{
4667 .len = size,
4668 .sentinel = .zero_u8,
4669 .child = .u8_type,
4670 } });
4671 const array_val = try ip.get(gpa, .{ .aggregate = .{
4672 .ty = array_ty,
4673 .storage = .{ .bytes = try ip.getOrPutTrailingString(gpa, bytes.len, .maybe_embedded_nulls) },
4674 } });
4675
4676 const ptr_ty = (try mod.ptrType(.{
4677 .child = array_ty,
4678 .flags = .{
4679 .alignment = .none,
4680 .is_const = true,
4681 .address_space = .generic,
4682 },
4683 })).toIntern();
4684 const ptr_val = try ip.get(gpa, .{ .ptr = .{
4685 .ty = ptr_ty,
4686 .base_addr = .{ .anon_decl = .{
4687 .val = array_val,
4688 .orig_ty = ptr_ty,
4689 } },
4690 .byte_offset = 0,
4691 } });
4692
4693 result.* = new_file;
4694 new_file.* = .{
4695 .sub_file_path = try ip.getOrPutString(gpa, sub_file_path, .no_embedded_nulls),
4696 .owner = pkg,
4697 .stat = stat,
4698 .val = ptr_val,
4699 .src_loc = src_loc,
4700 };
4701 return ptr_val;
4702}
4703
47043698pub fn scanNamespace(
47053699 zcu: *Zcu,
47063700 namespace_index: Namespace.Index,
......@@ -4970,13 +3964,6 @@ pub fn abortAnonDecl(mod: *Module, decl_index: Decl.Index) void {
49703964 mod.destroyDecl(decl_index);
49713965}
49723966
4973/// Finalize the creation of an anon decl.
4974pub fn finalizeAnonDecl(mod: *Module, decl_index: Decl.Index) Allocator.Error!void {
4975 if (mod.declPtr(decl_index).typeOf(mod).isFnOrHasRuntimeBits(mod)) {
4976 try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
4977 }
4978}
4979
49803967/// Delete all the Export objects that are caused by this `AnalUnit`. Re-analysis of
49813968/// this `AnalUnit` will cause them to be re-created (or not).
49823969pub fn deleteUnitExports(zcu: *Zcu, anal_unit: AnalUnit) void {
......@@ -5019,7 +4006,7 @@ pub fn deleteUnitExports(zcu: *Zcu, anal_unit: AnalUnit) void {
50194006
50204007/// Delete all references in `reference_table` which are caused by this `AnalUnit`.
50214008/// Re-analysis of the `AnalUnit` will cause appropriate references to be recreated.
5022fn deleteUnitReferences(zcu: *Zcu, anal_unit: AnalUnit) void {
4009pub fn deleteUnitReferences(zcu: *Zcu, anal_unit: AnalUnit) void {
50234010 const gpa = zcu.gpa;
50244011
50254012 const kv = zcu.reference_table.fetchSwapRemove(anal_unit) orelse return;
......@@ -5058,258 +4045,13 @@ pub fn addUnitReference(zcu: *Zcu, src_unit: AnalUnit, referenced_unit: AnalUnit
50584045 gop.value_ptr.* = @intCast(ref_idx);
50594046}
50604047
5061pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocator) SemaError!Air {
5062 const tracy = trace(@src());
5063 defer tracy.end();
5064
5065 const gpa = mod.gpa;
5066 const ip = &mod.intern_pool;
5067 const func = mod.funcInfo(func_index);
5068 const decl_index = func.owner_decl;
5069 const decl = mod.declPtr(decl_index);
5070
5071 log.debug("func name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
5072 defer blk: {
5073 log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
5074 }
5075
5076 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
5077 defer decl_prog_node.end();
5078
5079 mod.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .func = func_index }));
5080
5081 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
5082 defer comptime_err_ret_trace.deinit();
4048pub fn createNamespace(mod: *Module, initialization: Namespace) !Namespace.Index {
4049 return mod.intern_pool.createNamespace(mod.gpa, initialization);
4050}
50834051
5084 // In the case of a generic function instance, this is the type of the
5085 // instance, which has comptime parameters elided. In other words, it is
5086 // the runtime-known parameters only, not to be confused with the
5087 // generic_owner function type, which potentially has more parameters,
5088 // including comptime parameters.
5089 const fn_ty = decl.typeOf(mod);
5090 const fn_ty_info = mod.typeToFunc(fn_ty).?;
5091
5092 var sema: Sema = .{
5093 .mod = mod,
5094 .gpa = gpa,
5095 .arena = arena,
5096 .code = decl.getFileScope(mod).zir,
5097 .owner_decl = decl,
5098 .owner_decl_index = decl_index,
5099 .func_index = func_index,
5100 .func_is_naked = fn_ty_info.cc == .Naked,
5101 .fn_ret_ty = Type.fromInterned(fn_ty_info.return_type),
5102 .fn_ret_ty_ies = null,
5103 .owner_func_index = func_index,
5104 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
5105 .comptime_err_ret_trace = &comptime_err_ret_trace,
5106 };
5107 defer sema.deinit();
5108
5109 // Every runtime function has a dependency on the source of the Decl it originates from.
5110 // It also depends on the value of its owner Decl.
5111 try sema.declareDependency(.{ .src_hash = decl.zir_decl_index.unwrap().? });
5112 try sema.declareDependency(.{ .decl_val = decl_index });
5113
5114 if (func.analysis(ip).inferred_error_set) {
5115 const ies = try arena.create(Sema.InferredErrorSet);
5116 ies.* = .{ .func = func_index };
5117 sema.fn_ret_ty_ies = ies;
5118 }
5119
5120 // reset in case calls to errorable functions are removed.
5121 func.analysis(ip).calls_or_awaits_errorable_fn = false;
5122
5123 // First few indexes of extra are reserved and set at the end.
5124 const reserved_count = @typeInfo(Air.ExtraIndex).Enum.fields.len;
5125 try sema.air_extra.ensureTotalCapacity(gpa, reserved_count);
5126 sema.air_extra.items.len += reserved_count;
5127
5128 var inner_block: Sema.Block = .{
5129 .parent = null,
5130 .sema = &sema,
5131 .namespace = decl.src_namespace,
5132 .instructions = .{},
5133 .inlining = null,
5134 .is_comptime = false,
5135 .src_base_inst = inst: {
5136 const owner_info = if (func.generic_owner == .none)
5137 func
5138 else
5139 mod.funcInfo(func.generic_owner);
5140 const orig_decl = mod.declPtr(owner_info.owner_decl);
5141 break :inst orig_decl.zir_decl_index.unwrap().?;
5142 },
5143 .type_name_ctx = decl.name,
5144 };
5145 defer inner_block.instructions.deinit(gpa);
5146
5147 const fn_info = sema.code.getFnInfo(func.zirBodyInst(ip).resolve(ip));
5148
5149 // Here we are performing "runtime semantic analysis" for a function body, which means
5150 // we must map the parameter ZIR instructions to `arg` AIR instructions.
5151 // AIR requires the `arg` parameters to be the first N instructions.
5152 // This could be a generic function instantiation, however, in which case we need to
5153 // map the comptime parameters to constant values and only emit arg AIR instructions
5154 // for the runtime ones.
5155 const runtime_params_len = fn_ty_info.param_types.len;
5156 try inner_block.instructions.ensureTotalCapacityPrecise(gpa, runtime_params_len);
5157 try sema.air_instructions.ensureUnusedCapacity(gpa, fn_info.total_params_len);
5158 try sema.inst_map.ensureSpaceForInstructions(gpa, fn_info.param_body);
5159
5160 // In the case of a generic function instance, pre-populate all the comptime args.
5161 if (func.comptime_args.len != 0) {
5162 for (
5163 fn_info.param_body[0..func.comptime_args.len],
5164 func.comptime_args.get(ip),
5165 ) |inst, comptime_arg| {
5166 if (comptime_arg == .none) continue;
5167 sema.inst_map.putAssumeCapacityNoClobber(inst, Air.internedToRef(comptime_arg));
5168 }
5169 }
5170
5171 const src_params_len = if (func.comptime_args.len != 0)
5172 func.comptime_args.len
5173 else
5174 runtime_params_len;
5175
5176 var runtime_param_index: usize = 0;
5177 for (fn_info.param_body[0..src_params_len], 0..) |inst, src_param_index| {
5178 const gop = sema.inst_map.getOrPutAssumeCapacity(inst);
5179 if (gop.found_existing) continue; // provided above by comptime arg
5180
5181 const param_ty = fn_ty_info.param_types.get(ip)[runtime_param_index];
5182 runtime_param_index += 1;
5183
5184 const opt_opv = sema.typeHasOnePossibleValue(Type.fromInterned(param_ty)) catch |err| switch (err) {
5185 error.GenericPoison => unreachable,
5186 error.ComptimeReturn => unreachable,
5187 error.ComptimeBreak => unreachable,
5188 else => |e| return e,
5189 };
5190 if (opt_opv) |opv| {
5191 gop.value_ptr.* = Air.internedToRef(opv.toIntern());
5192 continue;
5193 }
5194 const arg_index: Air.Inst.Index = @enumFromInt(sema.air_instructions.len);
5195 gop.value_ptr.* = arg_index.toRef();
5196 inner_block.instructions.appendAssumeCapacity(arg_index);
5197 sema.air_instructions.appendAssumeCapacity(.{
5198 .tag = .arg,
5199 .data = .{ .arg = .{
5200 .ty = Air.internedToRef(param_ty),
5201 .src_index = @intCast(src_param_index),
5202 } },
5203 });
5204 }
5205
5206 func.analysis(ip).state = .in_progress;
5207
5208 const last_arg_index = inner_block.instructions.items.len;
5209
5210 // Save the error trace as our first action in the function.
5211 // If this is unnecessary after all, Liveness will clean it up for us.
5212 const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&inner_block);
5213 sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
5214 inner_block.error_return_trace_index = error_return_trace_index;
5215
5216 sema.analyzeFnBody(&inner_block, fn_info.body) catch |err| switch (err) {
5217 // TODO make these unreachable instead of @panic
5218 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
5219 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
5220 else => |e| return e,
5221 };
5222
5223 for (sema.unresolved_inferred_allocs.keys()) |ptr_inst| {
5224 // The lack of a resolve_inferred_alloc means that this instruction
5225 // is unused so it just has to be a no-op.
5226 sema.air_instructions.set(@intFromEnum(ptr_inst), .{
5227 .tag = .alloc,
5228 .data = .{ .ty = Type.single_const_pointer_to_comptime_int },
5229 });
5230 }
5231
5232 // If we don't get an error return trace from a caller, create our own.
5233 if (func.analysis(ip).calls_or_awaits_errorable_fn and
5234 mod.comp.config.any_error_tracing and
5235 !sema.fn_ret_ty.isError(mod))
5236 {
5237 sema.setupErrorReturnTrace(&inner_block, last_arg_index) catch |err| switch (err) {
5238 // TODO make these unreachable instead of @panic
5239 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
5240 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
5241 error.ComptimeBreak => @panic("zig compiler bug: ComptimeBreak"),
5242 else => |e| return e,
5243 };
5244 }
5245
5246 // Copy the block into place and mark that as the main block.
5247 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
5248 inner_block.instructions.items.len);
5249 const main_block_index = sema.addExtraAssumeCapacity(Air.Block{
5250 .body_len = @intCast(inner_block.instructions.items.len),
5251 });
5252 sema.air_extra.appendSliceAssumeCapacity(@ptrCast(inner_block.instructions.items));
5253 sema.air_extra.items[@intFromEnum(Air.ExtraIndex.main_block)] = main_block_index;
5254
5255 // Resolving inferred error sets is done *before* setting the function
5256 // state to success, so that "unable to resolve inferred error set" errors
5257 // can be emitted here.
5258 if (sema.fn_ret_ty_ies) |ies| {
5259 sema.resolveInferredErrorSetPtr(&inner_block, .{
5260 .base_node_inst = inner_block.src_base_inst,
5261 .offset = LazySrcLoc.Offset.nodeOffset(0),
5262 }, ies) catch |err| switch (err) {
5263 error.GenericPoison => unreachable,
5264 error.ComptimeReturn => unreachable,
5265 error.ComptimeBreak => unreachable,
5266 error.AnalysisFail => {
5267 // In this case our function depends on a type that had a compile error.
5268 // We should not try to lower this function.
5269 decl.analysis = .dependency_failure;
5270 return error.AnalysisFail;
5271 },
5272 else => |e| return e,
5273 };
5274 assert(ies.resolved != .none);
5275 ip.funcIesResolved(func_index).* = ies.resolved;
5276 }
5277
5278 func.analysis(ip).state = .success;
5279
5280 // Finally we must resolve the return type and parameter types so that backends
5281 // have full access to type information.
5282 // Crucially, this happens *after* we set the function state to success above,
5283 // so that dependencies on the function body will now be satisfied rather than
5284 // result in circular dependency errors.
5285 sema.resolveFnTypes(fn_ty) catch |err| switch (err) {
5286 error.GenericPoison => unreachable,
5287 error.ComptimeReturn => unreachable,
5288 error.ComptimeBreak => unreachable,
5289 error.AnalysisFail => {
5290 // In this case our function depends on a type that had a compile error.
5291 // We should not try to lower this function.
5292 decl.analysis = .dependency_failure;
5293 return error.AnalysisFail;
5294 },
5295 else => |e| return e,
5296 };
5297
5298 try sema.flushExports();
5299
5300 return .{
5301 .instructions = sema.air_instructions.toOwnedSlice(),
5302 .extra = try sema.air_extra.toOwnedSlice(gpa),
5303 };
5304}
5305
5306pub fn createNamespace(mod: *Module, initialization: Namespace) !Namespace.Index {
5307 return mod.intern_pool.createNamespace(mod.gpa, initialization);
5308}
5309
5310pub fn destroyNamespace(mod: *Module, index: Namespace.Index) void {
5311 return mod.intern_pool.destroyNamespace(mod.gpa, index);
5312}
4052pub fn destroyNamespace(mod: *Module, index: Namespace.Index) void {
4053 return mod.intern_pool.destroyNamespace(mod.gpa, index);
4054}
53134055
53144056pub fn allocateNewDecl(zcu: *Zcu, namespace: Namespace.Index) !Decl.Index {
53154057 const gpa = zcu.gpa;
......@@ -5420,117 +4162,7 @@ fn lockAndClearFileCompileError(mod: *Module, file: *File) void {
54204162 }
54214163}
54224164
5423/// Called from `Compilation.update`, after everything is done, just before
5424/// reporting compile errors. In this function we emit exported symbol collision
5425/// errors and communicate exported symbols to the linker backend.
5426pub fn processExports(zcu: *Zcu) !void {
5427 const gpa = zcu.gpa;
5428
5429 // First, construct a mapping of every exported value and Decl to the indices of all its different exports.
5430 var decl_exports: std.AutoArrayHashMapUnmanaged(Decl.Index, ArrayListUnmanaged(u32)) = .{};
5431 var value_exports: std.AutoArrayHashMapUnmanaged(InternPool.Index, ArrayListUnmanaged(u32)) = .{};
5432 defer {
5433 for (decl_exports.values()) |*exports| {
5434 exports.deinit(gpa);
5435 }
5436 decl_exports.deinit(gpa);
5437 for (value_exports.values()) |*exports| {
5438 exports.deinit(gpa);
5439 }
5440 value_exports.deinit(gpa);
5441 }
5442
5443 // We note as a heuristic:
5444 // * It is rare to export a value.
5445 // * It is rare for one Decl to be exported multiple times.
5446 // So, this ensureTotalCapacity serves as a reasonable (albeit very approximate) optimization.
5447 try decl_exports.ensureTotalCapacity(gpa, zcu.single_exports.count() + zcu.multi_exports.count());
5448
5449 for (zcu.single_exports.values()) |export_idx| {
5450 const exp = zcu.all_exports.items[export_idx];
5451 const value_ptr, const found_existing = switch (exp.exported) {
5452 .decl_index => |i| gop: {
5453 const gop = try decl_exports.getOrPut(gpa, i);
5454 break :gop .{ gop.value_ptr, gop.found_existing };
5455 },
5456 .value => |i| gop: {
5457 const gop = try value_exports.getOrPut(gpa, i);
5458 break :gop .{ gop.value_ptr, gop.found_existing };
5459 },
5460 };
5461 if (!found_existing) value_ptr.* = .{};
5462 try value_ptr.append(gpa, export_idx);
5463 }
5464
5465 for (zcu.multi_exports.values()) |info| {
5466 for (zcu.all_exports.items[info.index..][0..info.len], info.index..) |exp, export_idx| {
5467 const value_ptr, const found_existing = switch (exp.exported) {
5468 .decl_index => |i| gop: {
5469 const gop = try decl_exports.getOrPut(gpa, i);
5470 break :gop .{ gop.value_ptr, gop.found_existing };
5471 },
5472 .value => |i| gop: {
5473 const gop = try value_exports.getOrPut(gpa, i);
5474 break :gop .{ gop.value_ptr, gop.found_existing };
5475 },
5476 };
5477 if (!found_existing) value_ptr.* = .{};
5478 try value_ptr.append(gpa, @intCast(export_idx));
5479 }
5480 }
5481
5482 // Map symbol names to `Export` for name collision detection.
5483 var symbol_exports: SymbolExports = .{};
5484 defer symbol_exports.deinit(gpa);
5485
5486 for (decl_exports.keys(), decl_exports.values()) |exported_decl, exports_list| {
5487 const exported: Exported = .{ .decl_index = exported_decl };
5488 try processExportsInner(zcu, &symbol_exports, exported, exports_list.items);
5489 }
5490
5491 for (value_exports.keys(), value_exports.values()) |exported_value, exports_list| {
5492 const exported: Exported = .{ .value = exported_value };
5493 try processExportsInner(zcu, &symbol_exports, exported, exports_list.items);
5494 }
5495}
5496
5497const SymbolExports = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, u32);
5498
5499fn processExportsInner(
5500 zcu: *Zcu,
5501 symbol_exports: *SymbolExports,
5502 exported: Exported,
5503 export_indices: []const u32,
5504) error{OutOfMemory}!void {
5505 const gpa = zcu.gpa;
5506
5507 for (export_indices) |export_idx| {
5508 const new_export = &zcu.all_exports.items[export_idx];
5509 const gop = try symbol_exports.getOrPut(gpa, new_export.opts.name);
5510 if (gop.found_existing) {
5511 new_export.status = .failed_retryable;
5512 try zcu.failed_exports.ensureUnusedCapacity(gpa, 1);
5513 const msg = try ErrorMsg.create(gpa, new_export.src, "exported symbol collision: {}", .{
5514 new_export.opts.name.fmt(&zcu.intern_pool),
5515 });
5516 errdefer msg.destroy(gpa);
5517 const other_export = zcu.all_exports.items[gop.value_ptr.*];
5518 try zcu.errNote(other_export.src, msg, "other symbol here", .{});
5519 zcu.failed_exports.putAssumeCapacityNoClobber(export_idx, msg);
5520 new_export.status = .failed;
5521 } else {
5522 gop.value_ptr.* = export_idx;
5523 }
5524 }
5525 if (zcu.comp.bin_file) |lf| {
5526 try handleUpdateExports(zcu, export_indices, lf.updateExports(zcu, exported, export_indices));
5527 } else if (zcu.llvm_object) |llvm_object| {
5528 if (build_options.only_c) unreachable;
5529 try handleUpdateExports(zcu, export_indices, llvm_object.updateExports(zcu, exported, export_indices));
5530 }
5531}
5532
5533fn handleUpdateExports(
4165pub fn handleUpdateExports(
55344166 zcu: *Zcu,
55354167 export_indices: []const u32,
55364168 result: link.File.UpdateExportsError!void,
......@@ -5551,180 +4183,7 @@ fn handleUpdateExports(
55514183 };
55524184}
55534185
5554pub fn populateTestFunctions(
5555 zcu: *Zcu,
5556 main_progress_node: std.Progress.Node,
5557) !void {
5558 const gpa = zcu.gpa;
5559 const ip = &zcu.intern_pool;
5560 const builtin_mod = zcu.root_mod.getBuiltinDependency();
5561 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
5562 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
5563 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
5564 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
5565 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);
5566 const decl_index = builtin_namespace.decls.getKeyAdapted(
5567 test_functions_str,
5568 DeclAdapter{ .zcu = zcu },
5569 ).?;
5570 {
5571 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
5572 // was not referenced by start code.
5573 zcu.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
5574 defer {
5575 zcu.sema_prog_node.end();
5576 zcu.sema_prog_node = undefined;
5577 }
5578 try zcu.ensureDeclAnalyzed(decl_index);
5579 }
5580
5581 const decl = zcu.declPtr(decl_index);
5582 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
5583
5584 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
5585 // Add zcu.test_functions to an array decl then make the test_functions
5586 // decl reference it as a slice.
5587 const test_fn_vals = try gpa.alloc(InternPool.Index, zcu.test_functions.count());
5588 defer gpa.free(test_fn_vals);
5589
5590 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
5591 const test_decl = zcu.declPtr(test_decl_index);
5592 const test_decl_name = try test_decl.fullyQualifiedName(zcu);
5593 const test_decl_name_len = test_decl_name.length(ip);
5594 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
5595 const test_name_ty = try zcu.arrayType(.{
5596 .len = test_decl_name_len,
5597 .child = .u8_type,
5598 });
5599 const test_name_val = try zcu.intern(.{ .aggregate = .{
5600 .ty = test_name_ty.toIntern(),
5601 .storage = .{ .bytes = test_decl_name.toString() },
5602 } });
5603 break :n .{
5604 .orig_ty = (try zcu.singleConstPtrType(test_name_ty)).toIntern(),
5605 .val = test_name_val,
5606 };
5607 };
5608
5609 const test_fn_fields = .{
5610 // name
5611 try zcu.intern(.{ .slice = .{
5612 .ty = .slice_const_u8_type,
5613 .ptr = try zcu.intern(.{ .ptr = .{
5614 .ty = .manyptr_const_u8_type,
5615 .base_addr = .{ .anon_decl = test_name_anon_decl },
5616 .byte_offset = 0,
5617 } }),
5618 .len = try zcu.intern(.{ .int = .{
5619 .ty = .usize_type,
5620 .storage = .{ .u64 = test_decl_name_len },
5621 } }),
5622 } }),
5623 // func
5624 try zcu.intern(.{ .ptr = .{
5625 .ty = try zcu.intern(.{ .ptr_type = .{
5626 .child = test_decl.typeOf(zcu).toIntern(),
5627 .flags = .{
5628 .is_const = true,
5629 },
5630 } }),
5631 .base_addr = .{ .decl = test_decl_index },
5632 .byte_offset = 0,
5633 } }),
5634 };
5635 test_fn_val.* = try zcu.intern(.{ .aggregate = .{
5636 .ty = test_fn_ty.toIntern(),
5637 .storage = .{ .elems = &test_fn_fields },
5638 } });
5639 }
5640
5641 const array_ty = try zcu.arrayType(.{
5642 .len = test_fn_vals.len,
5643 .child = test_fn_ty.toIntern(),
5644 .sentinel = .none,
5645 });
5646 const array_val = try zcu.intern(.{ .aggregate = .{
5647 .ty = array_ty.toIntern(),
5648 .storage = .{ .elems = test_fn_vals },
5649 } });
5650 break :array .{
5651 .orig_ty = (try zcu.singleConstPtrType(array_ty)).toIntern(),
5652 .val = array_val,
5653 };
5654 };
5655
5656 {
5657 const new_ty = try zcu.ptrType(.{
5658 .child = test_fn_ty.toIntern(),
5659 .flags = .{
5660 .is_const = true,
5661 .size = .Slice,
5662 },
5663 });
5664 const new_val = decl.val;
5665 const new_init = try zcu.intern(.{ .slice = .{
5666 .ty = new_ty.toIntern(),
5667 .ptr = try zcu.intern(.{ .ptr = .{
5668 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
5669 .base_addr = .{ .anon_decl = array_anon_decl },
5670 .byte_offset = 0,
5671 } }),
5672 .len = (try zcu.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
5673 } });
5674 ip.mutateVarInit(decl.val.toIntern(), new_init);
5675
5676 // Since we are replacing the Decl's value we must perform cleanup on the
5677 // previous value.
5678 decl.val = new_val;
5679 decl.has_tv = true;
5680 }
5681 {
5682 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
5683 defer {
5684 zcu.codegen_prog_node.end();
5685 zcu.codegen_prog_node = undefined;
5686 }
5687
5688 try zcu.linkerUpdateDecl(decl_index);
5689 }
5690}
5691
5692pub fn linkerUpdateDecl(zcu: *Zcu, decl_index: Decl.Index) !void {
5693 const comp = zcu.comp;
5694
5695 const decl = zcu.declPtr(decl_index);
5696
5697 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool), 0);
5698 defer codegen_prog_node.end();
5699
5700 if (comp.bin_file) |lf| {
5701 lf.updateDecl(zcu, decl_index) catch |err| switch (err) {
5702 error.OutOfMemory => return error.OutOfMemory,
5703 error.AnalysisFail => {
5704 decl.analysis = .codegen_failure;
5705 },
5706 else => {
5707 const gpa = zcu.gpa;
5708 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
5709 zcu.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .decl = decl_index }), try ErrorMsg.create(
5710 gpa,
5711 decl.navSrcLoc(zcu),
5712 "unable to codegen: {s}",
5713 .{@errorName(err)},
5714 ));
5715 decl.analysis = .codegen_failure;
5716 try zcu.retryable_failures.append(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
5717 },
5718 };
5719 } else if (zcu.llvm_object) |llvm_object| {
5720 if (build_options.only_c) unreachable;
5721 llvm_object.updateDecl(zcu, decl_index) catch |err| switch (err) {
5722 error.OutOfMemory => return error.OutOfMemory,
5723 };
5724 }
5725}
5726
5727fn reportRetryableFileError(
4186pub fn reportRetryableFileError(
57284187 zcu: *Zcu,
57294188 file_index: File.Index,
57304189 comptime format: []const u8,
......@@ -5795,344 +4254,6 @@ pub fn backendSupportsFeature(zcu: Module, feature: Feature) bool {
57954254 return target_util.backendSupportsFeature(cpu_arch, ofmt, use_llvm, feature);
57964255}
57974256
5798/// Shortcut for calling `intern_pool.get`.
5799pub fn intern(mod: *Module, key: InternPool.Key) Allocator.Error!InternPool.Index {
5800 return mod.intern_pool.get(mod.gpa, key);
5801}
5802
5803/// Shortcut for calling `intern_pool.getCoerced`.
5804pub fn getCoerced(mod: *Module, val: Value, new_ty: Type) Allocator.Error!Value {
5805 return Value.fromInterned((try mod.intern_pool.getCoerced(mod.gpa, val.toIntern(), new_ty.toIntern())));
5806}
5807
5808pub fn intType(mod: *Module, signedness: std.builtin.Signedness, bits: u16) Allocator.Error!Type {
5809 return Type.fromInterned((try intern(mod, .{ .int_type = .{
5810 .signedness = signedness,
5811 .bits = bits,
5812 } })));
5813}
5814
5815pub fn errorIntType(mod: *Module) std.mem.Allocator.Error!Type {
5816 return mod.intType(.unsigned, mod.errorSetBits());
5817}
5818
5819pub fn arrayType(mod: *Module, info: InternPool.Key.ArrayType) Allocator.Error!Type {
5820 const i = try intern(mod, .{ .array_type = info });
5821 return Type.fromInterned(i);
5822}
5823
5824pub fn vectorType(mod: *Module, info: InternPool.Key.VectorType) Allocator.Error!Type {
5825 const i = try intern(mod, .{ .vector_type = info });
5826 return Type.fromInterned(i);
5827}
5828
5829pub fn optionalType(mod: *Module, child_type: InternPool.Index) Allocator.Error!Type {
5830 const i = try intern(mod, .{ .opt_type = child_type });
5831 return Type.fromInterned(i);
5832}
5833
5834pub fn ptrType(mod: *Module, info: InternPool.Key.PtrType) Allocator.Error!Type {
5835 var canon_info = info;
5836
5837 if (info.flags.size == .C) canon_info.flags.is_allowzero = true;
5838
5839 // Canonicalize non-zero alignment. If it matches the ABI alignment of the pointee
5840 // type, we change it to 0 here. If this causes an assertion trip because the
5841 // pointee type needs to be resolved more, that needs to be done before calling
5842 // this ptr() function.
5843 if (info.flags.alignment != .none and
5844 info.flags.alignment == Type.fromInterned(info.child).abiAlignment(mod))
5845 {
5846 canon_info.flags.alignment = .none;
5847 }
5848
5849 switch (info.flags.vector_index) {
5850 // Canonicalize host_size. If it matches the bit size of the pointee type,
5851 // we change it to 0 here. If this causes an assertion trip, the pointee type
5852 // needs to be resolved before calling this ptr() function.
5853 .none => if (info.packed_offset.host_size != 0) {
5854 const elem_bit_size = Type.fromInterned(info.child).bitSize(mod);
5855 assert(info.packed_offset.bit_offset + elem_bit_size <= info.packed_offset.host_size * 8);
5856 if (info.packed_offset.host_size * 8 == elem_bit_size) {
5857 canon_info.packed_offset.host_size = 0;
5858 }
5859 },
5860 .runtime => {},
5861 _ => assert(@intFromEnum(info.flags.vector_index) < info.packed_offset.host_size),
5862 }
5863
5864 return Type.fromInterned((try intern(mod, .{ .ptr_type = canon_info })));
5865}
5866
5867/// Like `ptrType`, but if `info` specifies an `alignment`, first ensures the pointer
5868/// child type's alignment is resolved so that an invalid alignment is not used.
5869/// In general, prefer this function during semantic analysis.
5870pub fn ptrTypeSema(zcu: *Zcu, info: InternPool.Key.PtrType) SemaError!Type {
5871 if (info.flags.alignment != .none) {
5872 _ = try Type.fromInterned(info.child).abiAlignmentAdvanced(zcu, .sema);
5873 }
5874 return zcu.ptrType(info);
5875}
5876
5877pub fn singleMutPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5878 return ptrType(mod, .{ .child = child_type.toIntern() });
5879}
5880
5881pub fn singleConstPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5882 return ptrType(mod, .{
5883 .child = child_type.toIntern(),
5884 .flags = .{
5885 .is_const = true,
5886 },
5887 });
5888}
5889
5890pub fn manyConstPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5891 return ptrType(mod, .{
5892 .child = child_type.toIntern(),
5893 .flags = .{
5894 .size = .Many,
5895 .is_const = true,
5896 },
5897 });
5898}
5899
5900pub fn adjustPtrTypeChild(mod: *Module, ptr_ty: Type, new_child: Type) Allocator.Error!Type {
5901 var info = ptr_ty.ptrInfo(mod);
5902 info.child = new_child.toIntern();
5903 return mod.ptrType(info);
5904}
5905
5906pub fn funcType(mod: *Module, key: InternPool.GetFuncTypeKey) Allocator.Error!Type {
5907 return Type.fromInterned((try mod.intern_pool.getFuncType(mod.gpa, key)));
5908}
5909
5910/// Use this for `anyframe->T` only.
5911/// For `anyframe`, use the `InternPool.Index.anyframe` tag directly.
5912pub fn anyframeType(mod: *Module, payload_ty: Type) Allocator.Error!Type {
5913 return Type.fromInterned((try intern(mod, .{ .anyframe_type = payload_ty.toIntern() })));
5914}
5915
5916pub fn errorUnionType(mod: *Module, error_set_ty: Type, payload_ty: Type) Allocator.Error!Type {
5917 return Type.fromInterned((try intern(mod, .{ .error_union_type = .{
5918 .error_set_type = error_set_ty.toIntern(),
5919 .payload_type = payload_ty.toIntern(),
5920 } })));
5921}
5922
5923pub fn singleErrorSetType(mod: *Module, name: InternPool.NullTerminatedString) Allocator.Error!Type {
5924 const names: *const [1]InternPool.NullTerminatedString = &name;
5925 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
5926 return Type.fromInterned(new_ty);
5927}
5928
5929/// Sorts `names` in place.
5930pub fn errorSetFromUnsortedNames(
5931 mod: *Module,
5932 names: []InternPool.NullTerminatedString,
5933) Allocator.Error!Type {
5934 std.mem.sort(
5935 InternPool.NullTerminatedString,
5936 names,
5937 {},
5938 InternPool.NullTerminatedString.indexLessThan,
5939 );
5940 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
5941 return Type.fromInterned(new_ty);
5942}
5943
5944/// Supports only pointers, not pointer-like optionals.
5945pub fn ptrIntValue(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
5946 assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
5947 assert(x != 0 or ty.isAllowzeroPtr(mod));
5948 const i = try intern(mod, .{ .ptr = .{
5949 .ty = ty.toIntern(),
5950 .base_addr = .int,
5951 .byte_offset = x,
5952 } });
5953 return Value.fromInterned(i);
5954}
5955
5956/// Creates an enum tag value based on the integer tag value.
5957pub fn enumValue(mod: *Module, ty: Type, tag_int: InternPool.Index) Allocator.Error!Value {
5958 if (std.debug.runtime_safety) {
5959 const tag = ty.zigTypeTag(mod);
5960 assert(tag == .Enum);
5961 }
5962 const i = try intern(mod, .{ .enum_tag = .{
5963 .ty = ty.toIntern(),
5964 .int = tag_int,
5965 } });
5966 return Value.fromInterned(i);
5967}
5968
5969/// Creates an enum tag value based on the field index according to source code
5970/// declaration order.
5971pub fn enumValueFieldIndex(mod: *Module, ty: Type, field_index: u32) Allocator.Error!Value {
5972 const ip = &mod.intern_pool;
5973 const gpa = mod.gpa;
5974 const enum_type = ip.loadEnumType(ty.toIntern());
5975
5976 if (enum_type.values.len == 0) {
5977 // Auto-numbered fields.
5978 return Value.fromInterned((try ip.get(gpa, .{ .enum_tag = .{
5979 .ty = ty.toIntern(),
5980 .int = try ip.get(gpa, .{ .int = .{
5981 .ty = enum_type.tag_ty,
5982 .storage = .{ .u64 = field_index },
5983 } }),
5984 } })));
5985 }
5986
5987 return Value.fromInterned((try ip.get(gpa, .{ .enum_tag = .{
5988 .ty = ty.toIntern(),
5989 .int = enum_type.values.get(ip)[field_index],
5990 } })));
5991}
5992
5993pub fn undefValue(mod: *Module, ty: Type) Allocator.Error!Value {
5994 return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
5995}
5996
5997pub fn undefRef(mod: *Module, ty: Type) Allocator.Error!Air.Inst.Ref {
5998 return Air.internedToRef((try mod.undefValue(ty)).toIntern());
5999}
6000
6001pub fn intValue(mod: *Module, ty: Type, x: anytype) Allocator.Error!Value {
6002 if (std.math.cast(u64, x)) |casted| return intValue_u64(mod, ty, casted);
6003 if (std.math.cast(i64, x)) |casted| return intValue_i64(mod, ty, casted);
6004 var limbs_buffer: [4]usize = undefined;
6005 var big_int = BigIntMutable.init(&limbs_buffer, x);
6006 return intValue_big(mod, ty, big_int.toConst());
6007}
6008
6009pub fn intRef(mod: *Module, ty: Type, x: anytype) Allocator.Error!Air.Inst.Ref {
6010 return Air.internedToRef((try mod.intValue(ty, x)).toIntern());
6011}
6012
6013pub fn intValue_big(mod: *Module, ty: Type, x: BigIntConst) Allocator.Error!Value {
6014 const i = try intern(mod, .{ .int = .{
6015 .ty = ty.toIntern(),
6016 .storage = .{ .big_int = x },
6017 } });
6018 return Value.fromInterned(i);
6019}
6020
6021pub fn intValue_u64(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
6022 const i = try intern(mod, .{ .int = .{
6023 .ty = ty.toIntern(),
6024 .storage = .{ .u64 = x },
6025 } });
6026 return Value.fromInterned(i);
6027}
6028
6029pub fn intValue_i64(mod: *Module, ty: Type, x: i64) Allocator.Error!Value {
6030 const i = try intern(mod, .{ .int = .{
6031 .ty = ty.toIntern(),
6032 .storage = .{ .i64 = x },
6033 } });
6034 return Value.fromInterned(i);
6035}
6036
6037pub fn unionValue(mod: *Module, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
6038 const i = try intern(mod, .{ .un = .{
6039 .ty = union_ty.toIntern(),
6040 .tag = tag.toIntern(),
6041 .val = val.toIntern(),
6042 } });
6043 return Value.fromInterned(i);
6044}
6045
6046/// This function casts the float representation down to the representation of the type, potentially
6047/// losing data if the representation wasn't correct.
6048pub fn floatValue(mod: *Module, ty: Type, x: anytype) Allocator.Error!Value {
6049 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(mod.getTarget())) {
6050 16 => .{ .f16 = @as(f16, @floatCast(x)) },
6051 32 => .{ .f32 = @as(f32, @floatCast(x)) },
6052 64 => .{ .f64 = @as(f64, @floatCast(x)) },
6053 80 => .{ .f80 = @as(f80, @floatCast(x)) },
6054 128 => .{ .f128 = @as(f128, @floatCast(x)) },
6055 else => unreachable,
6056 };
6057 const i = try intern(mod, .{ .float = .{
6058 .ty = ty.toIntern(),
6059 .storage = storage,
6060 } });
6061 return Value.fromInterned(i);
6062}
6063
6064pub fn nullValue(mod: *Module, opt_ty: Type) Allocator.Error!Value {
6065 const ip = &mod.intern_pool;
6066 assert(ip.isOptionalType(opt_ty.toIntern()));
6067 const result = try ip.get(mod.gpa, .{ .opt = .{
6068 .ty = opt_ty.toIntern(),
6069 .val = .none,
6070 } });
6071 return Value.fromInterned(result);
6072}
6073
6074pub fn smallestUnsignedInt(mod: *Module, max: u64) Allocator.Error!Type {
6075 return intType(mod, .unsigned, Type.smallestUnsignedBits(max));
6076}
6077
6078/// Returns the smallest possible integer type containing both `min` and
6079/// `max`. Asserts that neither value is undef.
6080/// TODO: if #3806 is implemented, this becomes trivial
6081pub fn intFittingRange(mod: *Module, min: Value, max: Value) !Type {
6082 assert(!min.isUndef(mod));
6083 assert(!max.isUndef(mod));
6084
6085 if (std.debug.runtime_safety) {
6086 assert(Value.order(min, max, mod).compare(.lte));
6087 }
6088
6089 const sign = min.orderAgainstZero(mod) == .lt;
6090
6091 const min_val_bits = intBitsForValue(mod, min, sign);
6092 const max_val_bits = intBitsForValue(mod, max, sign);
6093
6094 return mod.intType(
6095 if (sign) .signed else .unsigned,
6096 @max(min_val_bits, max_val_bits),
6097 );
6098}
6099
6100/// Given a value representing an integer, returns the number of bits necessary to represent
6101/// this value in an integer. If `sign` is true, returns the number of bits necessary in a
6102/// twos-complement integer; otherwise in an unsigned integer.
6103/// Asserts that `val` is not undef. If `val` is negative, asserts that `sign` is true.
6104pub fn intBitsForValue(mod: *Module, val: Value, sign: bool) u16 {
6105 assert(!val.isUndef(mod));
6106
6107 const key = mod.intern_pool.indexToKey(val.toIntern());
6108 switch (key.int.storage) {
6109 .i64 => |x| {
6110 if (std.math.cast(u64, x)) |casted| return Type.smallestUnsignedBits(casted) + @intFromBool(sign);
6111 assert(sign);
6112 // Protect against overflow in the following negation.
6113 if (x == std.math.minInt(i64)) return 64;
6114 return Type.smallestUnsignedBits(@as(u64, @intCast(-(x + 1)))) + 1;
6115 },
6116 .u64 => |x| {
6117 return Type.smallestUnsignedBits(x) + @intFromBool(sign);
6118 },
6119 .big_int => |big| {
6120 if (big.positive) return @as(u16, @intCast(big.bitCountAbs() + @intFromBool(sign)));
6121
6122 // Zero is still a possibility, in which case unsigned is fine
6123 if (big.eqlZero()) return 0;
6124
6125 return @as(u16, @intCast(big.bitCountTwosComp()));
6126 },
6127 .lazy_align => |lazy_ty| {
6128 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiAlignment(mod).toByteUnits() orelse 0) + @intFromBool(sign);
6129 },
6130 .lazy_size => |lazy_ty| {
6131 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiSize(mod)) + @intFromBool(sign);
6132 },
6133 }
6134}
6135
61364257pub const AtomicPtrAlignmentError = error{
61374258 FloatTooBig,
61384259 IntTooBig,
......@@ -6371,101 +4492,6 @@ pub const UnionLayout = struct {
63714492 padding: u32,
63724493};
63734494
6374pub fn getUnionLayout(mod: *Module, loaded_union: InternPool.LoadedUnionType) UnionLayout {
6375 const ip = &mod.intern_pool;
6376 assert(loaded_union.haveLayout(ip));
6377 var most_aligned_field: u32 = undefined;
6378 var most_aligned_field_size: u64 = undefined;
6379 var biggest_field: u32 = undefined;
6380 var payload_size: u64 = 0;
6381 var payload_align: Alignment = .@"1";
6382 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
6383 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
6384
6385 const explicit_align = loaded_union.fieldAlign(ip, field_index);
6386 const field_align = if (explicit_align != .none)
6387 explicit_align
6388 else
6389 Type.fromInterned(field_ty).abiAlignment(mod);
6390 const field_size = Type.fromInterned(field_ty).abiSize(mod);
6391 if (field_size > payload_size) {
6392 payload_size = field_size;
6393 biggest_field = @intCast(field_index);
6394 }
6395 if (field_align.compare(.gte, payload_align)) {
6396 payload_align = field_align;
6397 most_aligned_field = @intCast(field_index);
6398 most_aligned_field_size = field_size;
6399 }
6400 }
6401 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
6402 if (!have_tag or !Type.fromInterned(loaded_union.enum_tag_ty).hasRuntimeBits(mod)) {
6403 return .{
6404 .abi_size = payload_align.forward(payload_size),
6405 .abi_align = payload_align,
6406 .most_aligned_field = most_aligned_field,
6407 .most_aligned_field_size = most_aligned_field_size,
6408 .biggest_field = biggest_field,
6409 .payload_size = payload_size,
6410 .payload_align = payload_align,
6411 .tag_align = .none,
6412 .tag_size = 0,
6413 .padding = 0,
6414 };
6415 }
6416
6417 const tag_size = Type.fromInterned(loaded_union.enum_tag_ty).abiSize(mod);
6418 const tag_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(mod).max(.@"1");
6419 return .{
6420 .abi_size = loaded_union.size(ip).*,
6421 .abi_align = tag_align.max(payload_align),
6422 .most_aligned_field = most_aligned_field,
6423 .most_aligned_field_size = most_aligned_field_size,
6424 .biggest_field = biggest_field,
6425 .payload_size = payload_size,
6426 .payload_align = payload_align,
6427 .tag_align = tag_align,
6428 .tag_size = tag_size,
6429 .padding = loaded_union.padding(ip).*,
6430 };
6431}
6432
6433pub fn unionAbiSize(mod: *Module, loaded_union: InternPool.LoadedUnionType) u64 {
6434 return mod.getUnionLayout(loaded_union).abi_size;
6435}
6436
6437/// Returns 0 if the union is represented with 0 bits at runtime.
6438pub fn unionAbiAlignment(mod: *Module, loaded_union: InternPool.LoadedUnionType) Alignment {
6439 const ip = &mod.intern_pool;
6440 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
6441 var max_align: Alignment = .none;
6442 if (have_tag) max_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(mod);
6443 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
6444 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
6445
6446 const field_align = mod.unionFieldNormalAlignment(loaded_union, @intCast(field_index));
6447 max_align = max_align.max(field_align);
6448 }
6449 return max_align;
6450}
6451
6452/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
6453pub fn unionFieldNormalAlignment(zcu: *Zcu, loaded_union: InternPool.LoadedUnionType, field_index: u32) Alignment {
6454 return zcu.unionFieldNormalAlignmentAdvanced(loaded_union, field_index, .normal) catch unreachable;
6455}
6456
6457/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
6458/// If `strat` is `.sema`, may perform type resolution.
6459pub fn unionFieldNormalAlignmentAdvanced(zcu: *Zcu, loaded_union: InternPool.LoadedUnionType, field_index: u32, strat: Type.ResolveStrat) SemaError!Alignment {
6460 const ip = &zcu.intern_pool;
6461 assert(loaded_union.flagsPtr(ip).layout != .@"packed");
6462 const field_align = loaded_union.fieldAlign(ip, field_index);
6463 if (field_align != .none) return field_align;
6464 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
6465 if (field_ty.isNoReturn(zcu)) return .none;
6466 return (try field_ty.abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
6467}
6468
64694495/// Returns the index of the active field, given the current tag value
64704496pub fn unionTagFieldIndex(mod: *Module, loaded_union: InternPool.LoadedUnionType, enum_tag: Value) ?u32 {
64714497 const ip = &mod.intern_pool;
......@@ -6474,63 +4500,6 @@ pub fn unionTagFieldIndex(mod: *Module, loaded_union: InternPool.LoadedUnionType
64744500 return loaded_union.loadTagType(ip).tagValueIndex(ip, enum_tag.toIntern());
64754501}
64764502
6477/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
6478pub fn structFieldAlignment(
6479 zcu: *Zcu,
6480 explicit_alignment: InternPool.Alignment,
6481 field_ty: Type,
6482 layout: std.builtin.Type.ContainerLayout,
6483) Alignment {
6484 return zcu.structFieldAlignmentAdvanced(explicit_alignment, field_ty, layout, .normal) catch unreachable;
6485}
6486
6487/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
6488/// If `strat` is `.sema`, may perform type resolution.
6489pub fn structFieldAlignmentAdvanced(
6490 zcu: *Zcu,
6491 explicit_alignment: InternPool.Alignment,
6492 field_ty: Type,
6493 layout: std.builtin.Type.ContainerLayout,
6494 strat: Type.ResolveStrat,
6495) SemaError!Alignment {
6496 assert(layout != .@"packed");
6497 if (explicit_alignment != .none) return explicit_alignment;
6498 const ty_abi_align = (try field_ty.abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
6499 switch (layout) {
6500 .@"packed" => unreachable,
6501 .auto => if (zcu.getTarget().ofmt != .c) return ty_abi_align,
6502 .@"extern" => {},
6503 }
6504 // extern
6505 if (field_ty.isAbiInt(zcu) and field_ty.intInfo(zcu).bits >= 128) {
6506 return ty_abi_align.maxStrict(.@"16");
6507 }
6508 return ty_abi_align;
6509}
6510
6511/// https://github.com/ziglang/zig/issues/17178 explored storing these bit offsets
6512/// into the packed struct InternPool data rather than computing this on the
6513/// fly, however it was found to perform worse when measured on real world
6514/// projects.
6515pub fn structPackedFieldBitOffset(
6516 mod: *Module,
6517 struct_type: InternPool.LoadedStructType,
6518 field_index: u32,
6519) u16 {
6520 const ip = &mod.intern_pool;
6521 assert(struct_type.layout == .@"packed");
6522 assert(struct_type.haveLayout(ip));
6523 var bit_sum: u64 = 0;
6524 for (0..struct_type.field_types.len) |i| {
6525 if (i == field_index) {
6526 return @intCast(bit_sum);
6527 }
6528 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
6529 bit_sum += field_ty.bitSize(mod);
6530 }
6531 unreachable; // index out of bounds
6532}
6533
65344503pub const ResolvedReference = struct {
65354504 referencer: AnalUnit,
65364505 src: LazySrcLoc,
......@@ -6564,33 +4533,6 @@ pub fn resolveReferences(zcu: *Zcu) !std.AutoHashMapUnmanaged(AnalUnit, Resolved
65644533 return result;
65654534}
65664535
6567pub fn getBuiltin(zcu: *Zcu, name: []const u8) Allocator.Error!Air.Inst.Ref {
6568 const decl_index = try zcu.getBuiltinDecl(name);
6569 zcu.ensureDeclAnalyzed(decl_index) catch @panic("std.builtin is corrupt");
6570 return Air.internedToRef(zcu.declPtr(decl_index).val.toIntern());
6571}
6572
6573pub fn getBuiltinDecl(zcu: *Zcu, name: []const u8) Allocator.Error!InternPool.DeclIndex {
6574 const gpa = zcu.gpa;
6575 const ip = &zcu.intern_pool;
6576 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
6577 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index).unwrap().?;
6578 const std_namespace = zcu.declPtr(std_file_root_decl).getOwnedInnerNamespace(zcu).?;
6579 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
6580 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
6581 zcu.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");
6582 const builtin_namespace = zcu.declPtr(builtin_decl).getInnerNamespace(zcu) orelse @panic("std.builtin is corrupt");
6583 const name_str = try ip.getOrPutString(gpa, name, .no_embedded_nulls);
6584 return builtin_namespace.decls.getKeyAdapted(name_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std/builtin.zig is corrupt");
6585}
6586
6587pub fn getBuiltinType(zcu: *Zcu, name: []const u8) Allocator.Error!Type {
6588 const ty_inst = try zcu.getBuiltin(name);
6589 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
6590 ty.resolveFully(zcu) catch @panic("std.builtin is corrupt");
6591 return ty;
6592}
6593
65944536pub fn fileByIndex(zcu: *const Zcu, i: File.Index) *File {
65954537 return zcu.import_table.values()[@intFromEnum(i)];
65964538}
src/Zcu/PerThread.zig created+2102
......@@ -0,0 +1,2102 @@
1zcu: *Zcu,
2
3/// Dense, per-thread unique index.
4tid: Id,
5
6pub const Id = if (builtin.single_threaded) enum { main } else enum(usize) { main, _ };
7
8/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
9pub fn ensureFileAnalyzed(pt: Zcu.PerThread, file_index: Zcu.File.Index) Zcu.SemaError!void {
10 if (pt.zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
11 return pt.ensureDeclAnalyzed(existing_root);
12 } else {
13 return pt.semaFile(file_index);
14 }
15}
16
17/// This ensures that the Decl will have an up-to-date Type and Value populated.
18/// However the resolution status of the Type may not be fully resolved.
19/// For example an inferred error set is not resolved until after `analyzeFnBody`.
20/// is called.
21pub fn ensureDeclAnalyzed(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) Zcu.SemaError!void {
22 const tracy = trace(@src());
23 defer tracy.end();
24
25 const mod = pt.zcu;
26 const ip = &mod.intern_pool;
27 const decl = mod.declPtr(decl_index);
28
29 log.debug("ensureDeclAnalyzed '{d}' (name '{}')", .{
30 @intFromEnum(decl_index),
31 decl.name.fmt(ip),
32 });
33
34 // Determine whether or not this Decl is outdated, i.e. requires re-analysis
35 // even if `complete`. If a Decl is PO, we pessismistically assume that it
36 // *does* require re-analysis, to ensure that the Decl is definitely
37 // up-to-date when this function returns.
38
39 // If analysis occurs in a poor order, this could result in over-analysis.
40 // We do our best to avoid this by the other dependency logic in this file
41 // which tries to limit re-analysis to Decls whose previously listed
42 // dependencies are all up-to-date.
43
44 const decl_as_depender = InternPool.AnalUnit.wrap(.{ .decl = decl_index });
45 const decl_was_outdated = mod.outdated.swapRemove(decl_as_depender) or
46 mod.potentially_outdated.swapRemove(decl_as_depender);
47
48 if (decl_was_outdated) {
49 _ = mod.outdated_ready.swapRemove(decl_as_depender);
50 }
51
52 const was_outdated = mod.outdated_file_root.swapRemove(decl_index) or decl_was_outdated;
53
54 switch (decl.analysis) {
55 .in_progress => unreachable,
56
57 .file_failure => return error.AnalysisFail,
58
59 .sema_failure,
60 .dependency_failure,
61 .codegen_failure,
62 => if (!was_outdated) return error.AnalysisFail,
63
64 .complete => if (!was_outdated) return,
65
66 .unreferenced => {},
67 }
68
69 if (was_outdated) {
70 // The exports this Decl performs will be re-discovered, so we remove them here
71 // prior to re-analysis.
72 if (build_options.only_c) unreachable;
73 mod.deleteUnitExports(decl_as_depender);
74 mod.deleteUnitReferences(decl_as_depender);
75 }
76
77 const sema_result: Zcu.SemaDeclResult = blk: {
78 if (decl.zir_decl_index == .none and !mod.declIsRoot(decl_index)) {
79 // Anonymous decl. We don't semantically analyze these.
80 break :blk .{
81 .invalidate_decl_val = false,
82 .invalidate_decl_ref = false,
83 };
84 }
85
86 if (mod.declIsRoot(decl_index)) {
87 const changed = try pt.semaFileUpdate(decl.getFileScopeIndex(mod), decl_was_outdated);
88 break :blk .{
89 .invalidate_decl_val = changed,
90 .invalidate_decl_ref = changed,
91 };
92 }
93
94 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
95 defer decl_prog_node.end();
96
97 break :blk pt.semaDecl(decl_index) catch |err| switch (err) {
98 error.AnalysisFail => {
99 if (decl.analysis == .in_progress) {
100 // If this decl caused the compile error, the analysis field would
101 // be changed to indicate it was this Decl's fault. Because this
102 // did not happen, we infer here that it was a dependency failure.
103 decl.analysis = .dependency_failure;
104 }
105 return error.AnalysisFail;
106 },
107 error.GenericPoison => unreachable,
108 else => |e| {
109 decl.analysis = .sema_failure;
110 try mod.failed_analysis.ensureUnusedCapacity(mod.gpa, 1);
111 try mod.retryable_failures.append(mod.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
112 mod.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .decl = decl_index }), try Zcu.ErrorMsg.create(
113 mod.gpa,
114 decl.navSrcLoc(mod),
115 "unable to analyze: {s}",
116 .{@errorName(e)},
117 ));
118 return error.AnalysisFail;
119 },
120 };
121 };
122
123 // TODO: we do not yet have separate dependencies for decl values vs types.
124 if (decl_was_outdated) {
125 if (sema_result.invalidate_decl_val or sema_result.invalidate_decl_ref) {
126 log.debug("Decl tv invalidated ('{d}')", .{@intFromEnum(decl_index)});
127 // This dependency was marked as PO, meaning dependees were waiting
128 // on its analysis result, and it has turned out to be outdated.
129 // Update dependees accordingly.
130 try mod.markDependeeOutdated(.{ .decl_val = decl_index });
131 } else {
132 log.debug("Decl tv up-to-date ('{d}')", .{@intFromEnum(decl_index)});
133 // This dependency was previously PO, but turned out to be up-to-date.
134 // We do not need to queue successive analysis.
135 try mod.markPoDependeeUpToDate(.{ .decl_val = decl_index });
136 }
137 }
138}
139
140pub fn ensureFuncBodyAnalyzed(pt: Zcu.PerThread, maybe_coerced_func_index: InternPool.Index) Zcu.SemaError!void {
141 const tracy = trace(@src());
142 defer tracy.end();
143
144 const zcu = pt.zcu;
145 const gpa = zcu.gpa;
146 const ip = &zcu.intern_pool;
147
148 // We only care about the uncoerced function.
149 // We need to do this for the "orphaned function" check below to be valid.
150 const func_index = ip.unwrapCoercedFunc(maybe_coerced_func_index);
151
152 const func = zcu.funcInfo(maybe_coerced_func_index);
153 const decl_index = func.owner_decl;
154 const decl = zcu.declPtr(decl_index);
155
156 log.debug("ensureFuncBodyAnalyzed '{d}' (instance of '{}')", .{
157 @intFromEnum(func_index),
158 decl.name.fmt(ip),
159 });
160
161 // First, our owner decl must be up-to-date. This will always be the case
162 // during the first update, but may not on successive updates if we happen
163 // to get analyzed before our parent decl.
164 try pt.ensureDeclAnalyzed(decl_index);
165
166 // On an update, it's possible this function changed such that our owner
167 // decl now refers to a different function, making this one orphaned. If
168 // that's the case, we should remove this function from the binary.
169 if (decl.val.ip_index != func_index) {
170 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
171 ip.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
172 ip.remove(func_index);
173 @panic("TODO: remove orphaned function from binary");
174 }
175
176 // We'll want to remember what the IES used to be before the update for
177 // dependency invalidation purposes.
178 const old_resolved_ies = if (func.analysis(ip).inferred_error_set)
179 func.resolvedErrorSet(ip).*
180 else
181 .none;
182
183 switch (decl.analysis) {
184 .unreferenced => unreachable,
185 .in_progress => unreachable,
186
187 .codegen_failure => unreachable, // functions do not perform constant value generation
188
189 .file_failure,
190 .sema_failure,
191 .dependency_failure,
192 => return error.AnalysisFail,
193
194 .complete => {},
195 }
196
197 const func_as_depender = InternPool.AnalUnit.wrap(.{ .func = func_index });
198 const was_outdated = zcu.outdated.swapRemove(func_as_depender) or
199 zcu.potentially_outdated.swapRemove(func_as_depender);
200
201 if (was_outdated) {
202 if (build_options.only_c) unreachable;
203 _ = zcu.outdated_ready.swapRemove(func_as_depender);
204 zcu.deleteUnitExports(func_as_depender);
205 zcu.deleteUnitReferences(func_as_depender);
206 }
207
208 switch (func.analysis(ip).state) {
209 .success => if (!was_outdated) return,
210 .sema_failure,
211 .dependency_failure,
212 .codegen_failure,
213 => if (!was_outdated) return error.AnalysisFail,
214 .none, .queued => {},
215 .in_progress => unreachable,
216 .inline_only => unreachable, // don't queue work for this
217 }
218
219 log.debug("analyze and generate fn body '{d}'; reason='{s}'", .{
220 @intFromEnum(func_index),
221 if (was_outdated) "outdated" else "never analyzed",
222 });
223
224 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
225 defer tmp_arena.deinit();
226 const sema_arena = tmp_arena.allocator();
227
228 var air = pt.analyzeFnBody(func_index, sema_arena) catch |err| switch (err) {
229 error.AnalysisFail => {
230 if (func.analysis(ip).state == .in_progress) {
231 // If this decl caused the compile error, the analysis field would
232 // be changed to indicate it was this Decl's fault. Because this
233 // did not happen, we infer here that it was a dependency failure.
234 func.analysis(ip).state = .dependency_failure;
235 }
236 return error.AnalysisFail;
237 },
238 error.OutOfMemory => return error.OutOfMemory,
239 };
240 errdefer air.deinit(gpa);
241
242 const invalidate_ies_deps = i: {
243 if (!was_outdated) break :i false;
244 if (!func.analysis(ip).inferred_error_set) break :i true;
245 const new_resolved_ies = func.resolvedErrorSet(ip).*;
246 break :i new_resolved_ies != old_resolved_ies;
247 };
248 if (invalidate_ies_deps) {
249 log.debug("func IES invalidated ('{d}')", .{@intFromEnum(func_index)});
250 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
251 } else if (was_outdated) {
252 log.debug("func IES up-to-date ('{d}')", .{@intFromEnum(func_index)});
253 try zcu.markPoDependeeUpToDate(.{ .func_ies = func_index });
254 }
255
256 const comp = zcu.comp;
257
258 const dump_air = build_options.enable_debug_extensions and comp.verbose_air;
259 const dump_llvm_ir = build_options.enable_debug_extensions and (comp.verbose_llvm_ir != null or comp.verbose_llvm_bc != null);
260
261 if (comp.bin_file == null and zcu.llvm_object == null and !dump_air and !dump_llvm_ir) {
262 air.deinit(gpa);
263 return;
264 }
265
266 try comp.work_queue.writeItem(.{ .codegen_func = .{
267 .func = func_index,
268 .air = air,
269 } });
270}
271
272/// Takes ownership of `air`, even on error.
273/// If any types referenced by `air` are unresolved, marks the codegen as failed.
274pub fn linkerUpdateFunc(pt: Zcu.PerThread, func_index: InternPool.Index, air: Air) Allocator.Error!void {
275 const zcu = pt.zcu;
276 const gpa = zcu.gpa;
277 const ip = &zcu.intern_pool;
278 const comp = zcu.comp;
279
280 defer {
281 var air_mut = air;
282 air_mut.deinit(gpa);
283 }
284
285 const func = zcu.funcInfo(func_index);
286 const decl_index = func.owner_decl;
287 const decl = zcu.declPtr(decl_index);
288
289 var liveness = try Liveness.analyze(gpa, air, ip);
290 defer liveness.deinit(gpa);
291
292 if (build_options.enable_debug_extensions and comp.verbose_air) {
293 const fqn = try decl.fullyQualifiedName(zcu);
294 std.debug.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)});
295 @import("../print_air.zig").dump(pt, air, liveness);
296 std.debug.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)});
297 }
298
299 if (std.debug.runtime_safety) {
300 var verify: Liveness.Verify = .{
301 .gpa = gpa,
302 .air = air,
303 .liveness = liveness,
304 .intern_pool = ip,
305 };
306 defer verify.deinit();
307
308 verify.verify() catch |err| switch (err) {
309 error.OutOfMemory => return error.OutOfMemory,
310 else => {
311 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
312 zcu.failed_analysis.putAssumeCapacityNoClobber(
313 InternPool.AnalUnit.wrap(.{ .func = func_index }),
314 try Zcu.ErrorMsg.create(
315 gpa,
316 decl.navSrcLoc(zcu),
317 "invalid liveness: {s}",
318 .{@errorName(err)},
319 ),
320 );
321 func.analysis(ip).state = .codegen_failure;
322 return;
323 },
324 };
325 }
326
327 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(ip), 0);
328 defer codegen_prog_node.end();
329
330 if (!air.typesFullyResolved(zcu)) {
331 // A type we depend on failed to resolve. This is a transitive failure.
332 // Correcting this failure will involve changing a type this function
333 // depends on, hence triggering re-analysis of this function, so this
334 // interacts correctly with incremental compilation.
335 func.analysis(ip).state = .codegen_failure;
336 } else if (comp.bin_file) |lf| {
337 lf.updateFunc(pt, func_index, air, liveness) catch |err| switch (err) {
338 error.OutOfMemory => return error.OutOfMemory,
339 error.AnalysisFail => {
340 func.analysis(ip).state = .codegen_failure;
341 },
342 else => {
343 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
344 zcu.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .func = func_index }), try Zcu.ErrorMsg.create(
345 gpa,
346 decl.navSrcLoc(zcu),
347 "unable to codegen: {s}",
348 .{@errorName(err)},
349 ));
350 func.analysis(ip).state = .codegen_failure;
351 try zcu.retryable_failures.append(zcu.gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
352 },
353 };
354 } else if (zcu.llvm_object) |llvm_object| {
355 if (build_options.only_c) unreachable;
356 llvm_object.updateFunc(pt, func_index, air, liveness) catch |err| switch (err) {
357 error.OutOfMemory => return error.OutOfMemory,
358 };
359 }
360}
361
362/// https://github.com/ziglang/zig/issues/14307
363pub fn semaPkg(pt: Zcu.PerThread, pkg: *Module) !void {
364 const import_file_result = try pt.zcu.importPkg(pkg);
365 const root_decl_index = pt.zcu.fileRootDecl(import_file_result.file_index);
366 if (root_decl_index == .none) {
367 return pt.semaFile(import_file_result.file_index);
368 }
369}
370
371fn getFileRootStruct(
372 pt: Zcu.PerThread,
373 decl_index: Zcu.Decl.Index,
374 namespace_index: Zcu.Namespace.Index,
375 file_index: Zcu.File.Index,
376) Allocator.Error!InternPool.Index {
377 const zcu = pt.zcu;
378 const gpa = zcu.gpa;
379 const ip = &zcu.intern_pool;
380 const file = zcu.fileByIndex(file_index);
381 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
382 assert(extended.opcode == .struct_decl);
383 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
384 assert(!small.has_captures_len);
385 assert(!small.has_backing_int);
386 assert(small.layout == .auto);
387 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
388 const fields_len = if (small.has_fields_len) blk: {
389 const fields_len = file.zir.extra[extra_index];
390 extra_index += 1;
391 break :blk fields_len;
392 } else 0;
393 const decls_len = if (small.has_decls_len) blk: {
394 const decls_len = file.zir.extra[extra_index];
395 extra_index += 1;
396 break :blk decls_len;
397 } else 0;
398 const decls = file.zir.bodySlice(extra_index, decls_len);
399 extra_index += decls_len;
400
401 const tracked_inst = try ip.trackZir(gpa, file_index, .main_struct_inst);
402 const wip_ty = switch (try ip.getStructType(gpa, pt.tid, .{
403 .layout = .auto,
404 .fields_len = fields_len,
405 .known_non_opv = small.known_non_opv,
406 .requires_comptime = if (small.known_comptime_only) .yes else .unknown,
407 .is_tuple = small.is_tuple,
408 .any_comptime_fields = small.any_comptime_fields,
409 .any_default_inits = small.any_default_inits,
410 .inits_resolved = false,
411 .any_aligned_fields = small.any_aligned_fields,
412 .has_namespace = true,
413 .key = .{ .declared = .{
414 .zir_index = tracked_inst,
415 .captures = &.{},
416 } },
417 })) {
418 .existing => unreachable, // we wouldn't be analysing the file root if this type existed
419 .wip => |wip| wip,
420 };
421 errdefer wip_ty.cancel(ip);
422
423 if (zcu.comp.debug_incremental) {
424 try ip.addDependency(
425 gpa,
426 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),
427 .{ .src_hash = tracked_inst },
428 );
429 }
430
431 const decl = zcu.declPtr(decl_index);
432 decl.val = Value.fromInterned(wip_ty.index);
433 decl.has_tv = true;
434 decl.owns_tv = true;
435 decl.analysis = .complete;
436
437 try zcu.scanNamespace(namespace_index, decls, decl);
438 try zcu.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
439 return wip_ty.finish(ip, decl_index, namespace_index.toOptional());
440}
441
442/// Re-analyze the root Decl of a file on an incremental update.
443/// If `type_outdated`, the struct type itself is considered outdated and is
444/// reconstructed at a new InternPool index. Otherwise, the namespace is just
445/// re-analyzed. Returns whether the decl's tyval was invalidated.
446fn semaFileUpdate(pt: Zcu.PerThread, file_index: Zcu.File.Index, type_outdated: bool) Zcu.SemaError!bool {
447 const zcu = pt.zcu;
448 const ip = &zcu.intern_pool;
449 const file = zcu.fileByIndex(file_index);
450 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
451
452 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
453 file.mod.fully_qualified_name,
454 file.sub_file_path,
455 type_outdated,
456 });
457
458 if (file.status != .success_zir) {
459 if (decl.analysis == .file_failure) {
460 return false;
461 } else {
462 decl.analysis = .file_failure;
463 return true;
464 }
465 }
466
467 if (decl.analysis == .file_failure) {
468 // No struct type currently exists. Create one!
469 const root_decl = zcu.fileRootDecl(file_index);
470 _ = try pt.getFileRootStruct(root_decl.unwrap().?, decl.src_namespace, file_index);
471 return true;
472 }
473
474 assert(decl.has_tv);
475 assert(decl.owns_tv);
476
477 if (type_outdated) {
478 // Invalidate the existing type, reusing the decl and namespace.
479 const file_root_decl = zcu.fileRootDecl(file_index).unwrap().?;
480 ip.removeDependenciesForDepender(zcu.gpa, InternPool.AnalUnit.wrap(.{
481 .decl = file_root_decl,
482 }));
483 ip.remove(decl.val.toIntern());
484 decl.val = undefined;
485 _ = try pt.getFileRootStruct(file_root_decl, decl.src_namespace, file_index);
486 return true;
487 }
488
489 // Only the struct's namespace is outdated.
490 // Preserve the type - just scan the namespace again.
491
492 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
493 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
494
495 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
496 extra_index += @intFromBool(small.has_fields_len);
497 const decls_len = if (small.has_decls_len) blk: {
498 const decls_len = file.zir.extra[extra_index];
499 extra_index += 1;
500 break :blk decls_len;
501 } else 0;
502 const decls = file.zir.bodySlice(extra_index, decls_len);
503
504 if (!type_outdated) {
505 try zcu.scanNamespace(decl.src_namespace, decls, decl);
506 }
507
508 return false;
509}
510
511/// Regardless of the file status, will create a `Decl` if none exists so that we can track
512/// dependencies and re-analyze when the file becomes outdated.
513fn semaFile(pt: Zcu.PerThread, file_index: Zcu.File.Index) Zcu.SemaError!void {
514 const tracy = trace(@src());
515 defer tracy.end();
516
517 const zcu = pt.zcu;
518 const gpa = zcu.gpa;
519 const file = zcu.fileByIndex(file_index);
520 assert(zcu.fileRootDecl(file_index) == .none);
521 log.debug("semaFile zcu={s} sub_file_path={s}", .{
522 file.mod.fully_qualified_name, file.sub_file_path,
523 });
524
525 // Because these three things each reference each other, `undefined`
526 // placeholders are used before being set after the struct type gains an
527 // InternPool index.
528 const new_namespace_index = try zcu.createNamespace(.{
529 .parent = .none,
530 .decl_index = undefined,
531 .file_scope = file_index,
532 });
533 errdefer zcu.destroyNamespace(new_namespace_index);
534
535 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
536 const new_decl = zcu.declPtr(new_decl_index);
537 errdefer @panic("TODO error handling");
538
539 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
540 zcu.namespacePtr(new_namespace_index).decl_index = new_decl_index;
541
542 new_decl.name = try file.fullyQualifiedName(zcu);
543 new_decl.name_fully_qualified = true;
544 new_decl.is_pub = true;
545 new_decl.is_exported = false;
546 new_decl.alignment = .none;
547 new_decl.@"linksection" = .none;
548 new_decl.analysis = .in_progress;
549
550 if (file.status != .success_zir) {
551 new_decl.analysis = .file_failure;
552 return;
553 }
554 assert(file.zir_loaded);
555
556 const struct_ty = try pt.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
557 errdefer zcu.intern_pool.remove(struct_ty);
558
559 switch (zcu.comp.cache_use) {
560 .whole => |whole| if (whole.cache_manifest) |man| {
561 const source = file.getSource(gpa) catch |err| {
562 try Zcu.reportRetryableFileError(zcu, file_index, "unable to load source: {s}", .{@errorName(err)});
563 return error.AnalysisFail;
564 };
565
566 const resolved_path = std.fs.path.resolve(gpa, &.{
567 file.mod.root.root_dir.path orelse ".",
568 file.mod.root.sub_path,
569 file.sub_file_path,
570 }) catch |err| {
571 try Zcu.reportRetryableFileError(zcu, file_index, "unable to resolve path: {s}", .{@errorName(err)});
572 return error.AnalysisFail;
573 };
574 errdefer gpa.free(resolved_path);
575
576 whole.cache_manifest_mutex.lock();
577 defer whole.cache_manifest_mutex.unlock();
578 try man.addFilePostContents(resolved_path, source.bytes, source.stat);
579 },
580 .incremental => {},
581 }
582}
583
584fn semaDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) !Zcu.SemaDeclResult {
585 const tracy = trace(@src());
586 defer tracy.end();
587
588 const zcu = pt.zcu;
589 const decl = zcu.declPtr(decl_index);
590 const ip = &zcu.intern_pool;
591
592 if (decl.getFileScope(zcu).status != .success_zir) {
593 return error.AnalysisFail;
594 }
595
596 assert(!zcu.declIsRoot(decl_index));
597
598 if (decl.zir_decl_index == .none and decl.owns_tv) {
599 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).
600 return zcu.semaAnonOwnerDecl(decl_index);
601 }
602
603 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
604 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(zcu)).fmt(ip)});
605 defer blk: {
606 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(zcu) catch break :blk).fmt(ip)});
607 }
608
609 const old_has_tv = decl.has_tv;
610 // The following values are ignored if `!old_has_tv`
611 const old_ty = if (old_has_tv) decl.typeOf(zcu) else undefined;
612 const old_val = decl.val;
613 const old_align = decl.alignment;
614 const old_linksection = decl.@"linksection";
615 const old_addrspace = decl.@"addrspace";
616 const old_is_inline = if (decl.getOwnedFunction(zcu)) |prev_func|
617 prev_func.analysis(ip).state == .inline_only
618 else
619 false;
620
621 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
622
623 const gpa = zcu.gpa;
624 const zir = decl.getFileScope(zcu).zir;
625
626 const builtin_type_target_index: InternPool.Index = ip_index: {
627 const std_mod = zcu.std_mod;
628 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
629 // We're in the std module.
630 const std_file_imported = try zcu.importPkg(std_mod);
631 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
632 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
633 const std_namespace = std_decl.getInnerNamespace(zcu).?;
634 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
635 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
636 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
637 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
638 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
639 for ([_][]const u8{
640 "AtomicOrder",
641 "AtomicRmwOp",
642 "CallingConvention",
643 "AddressSpace",
644 "FloatMode",
645 "ReduceOp",
646 "CallModifier",
647 "PrefetchOptions",
648 "ExportOptions",
649 "ExternOptions",
650 "Type",
651 }, [_]InternPool.Index{
652 .atomic_order_type,
653 .atomic_rmw_op_type,
654 .calling_convention_type,
655 .address_space_type,
656 .float_mode_type,
657 .reduce_op_type,
658 .call_modifier_type,
659 .prefetch_options_type,
660 .export_options_type,
661 .extern_options_type,
662 .type_info_type,
663 }) |type_name, type_ip| {
664 if (decl.name.eqlSlice(type_name, ip)) break :ip_index type_ip;
665 }
666 break :ip_index .none;
667 };
668
669 zcu.intern_pool.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
670
671 decl.analysis = .in_progress;
672
673 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
674 defer analysis_arena.deinit();
675
676 var comptime_err_ret_trace = std.ArrayList(Zcu.LazySrcLoc).init(gpa);
677 defer comptime_err_ret_trace.deinit();
678
679 var sema: Sema = .{
680 .pt = pt,
681 .gpa = gpa,
682 .arena = analysis_arena.allocator(),
683 .code = zir,
684 .owner_decl = decl,
685 .owner_decl_index = decl_index,
686 .func_index = .none,
687 .func_is_naked = false,
688 .fn_ret_ty = Type.void,
689 .fn_ret_ty_ies = null,
690 .owner_func_index = .none,
691 .comptime_err_ret_trace = &comptime_err_ret_trace,
692 .builtin_type_target_index = builtin_type_target_index,
693 };
694 defer sema.deinit();
695
696 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
697 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
698 gpa,
699 decl.getFileScopeIndex(zcu),
700 decl_inst,
701 ) });
702
703 var block_scope: Sema.Block = .{
704 .parent = null,
705 .sema = &sema,
706 .namespace = decl.src_namespace,
707 .instructions = .{},
708 .inlining = null,
709 .is_comptime = true,
710 .src_base_inst = decl.zir_decl_index.unwrap().?,
711 .type_name_ctx = decl.name,
712 };
713 defer block_scope.instructions.deinit(gpa);
714
715 const decl_bodies = decl.zirBodies(zcu);
716
717 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
718 // We'll do some other bits with the Sema. Clear the type target index just
719 // in case they analyze any type.
720 sema.builtin_type_target_index = .none;
721 const align_src = block_scope.src(.{ .node_offset_var_decl_align = 0 });
722 const section_src = block_scope.src(.{ .node_offset_var_decl_section = 0 });
723 const address_space_src = block_scope.src(.{ .node_offset_var_decl_addrspace = 0 });
724 const ty_src = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
725 const init_src = block_scope.src(.{ .node_offset_var_decl_init = 0 });
726 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);
727 const decl_ty = decl_val.typeOf(zcu);
728
729 // Note this resolves the type of the Decl, not the value; if this Decl
730 // is a struct, for example, this resolves `type` (which needs no resolution),
731 // not the struct itself.
732 try decl_ty.resolveLayout(pt);
733
734 if (decl.kind == .@"usingnamespace") {
735 if (!decl_ty.eql(Type.type, zcu)) {
736 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{decl_ty.fmt(pt)});
737 }
738 const ty = decl_val.toType();
739 if (ty.getNamespace(zcu) == null) {
740 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(pt)});
741 }
742
743 decl.val = ty.toValue();
744 decl.alignment = .none;
745 decl.@"linksection" = .none;
746 decl.has_tv = true;
747 decl.owns_tv = false;
748 decl.analysis = .complete;
749
750 // TODO: usingnamespace cannot currently participate in incremental compilation
751 return .{
752 .invalidate_decl_val = true,
753 .invalidate_decl_ref = true,
754 };
755 }
756
757 var queue_linker_work = true;
758 var is_func = false;
759 var is_inline = false;
760 switch (decl_val.toIntern()) {
761 .generic_poison => unreachable,
762 .unreachable_value => unreachable,
763 else => switch (ip.indexToKey(decl_val.toIntern())) {
764 .variable => |variable| {
765 decl.owns_tv = variable.decl == decl_index;
766 queue_linker_work = decl.owns_tv;
767 },
768
769 .extern_func => |extern_func| {
770 decl.owns_tv = extern_func.decl == decl_index;
771 queue_linker_work = decl.owns_tv;
772 is_func = decl.owns_tv;
773 },
774
775 .func => |func| {
776 decl.owns_tv = func.owner_decl == decl_index;
777 queue_linker_work = false;
778 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(zcu) == .Inline;
779 is_func = decl.owns_tv;
780 },
781
782 else => {},
783 },
784 }
785
786 decl.val = decl_val;
787 // Function linksection, align, and addrspace were already set by Sema
788 if (!is_func) {
789 decl.alignment = blk: {
790 const align_body = decl_bodies.align_body orelse break :blk .none;
791 const align_ref = try sema.resolveInlineBody(&block_scope, align_body, decl_inst);
792 break :blk try sema.analyzeAsAlign(&block_scope, align_src, align_ref);
793 };
794 decl.@"linksection" = blk: {
795 const linksection_body = decl_bodies.linksection_body orelse break :blk .none;
796 const linksection_ref = try sema.resolveInlineBody(&block_scope, linksection_body, decl_inst);
797 const bytes = try sema.toConstString(&block_scope, section_src, linksection_ref, .{
798 .needed_comptime_reason = "linksection must be comptime-known",
799 });
800 if (std.mem.indexOfScalar(u8, bytes, 0) != null) {
801 return sema.fail(&block_scope, section_src, "linksection cannot contain null bytes", .{});
802 } else if (bytes.len == 0) {
803 return sema.fail(&block_scope, section_src, "linksection cannot be empty", .{});
804 }
805 break :blk try ip.getOrPutStringOpt(gpa, bytes, .no_embedded_nulls);
806 };
807 decl.@"addrspace" = blk: {
808 const addrspace_ctx: Sema.AddressSpaceContext = switch (ip.indexToKey(decl_val.toIntern())) {
809 .variable => .variable,
810 .extern_func, .func => .function,
811 else => .constant,
812 };
813
814 const target = zcu.getTarget();
815
816 const addrspace_body = decl_bodies.addrspace_body orelse break :blk switch (addrspace_ctx) {
817 .function => target_util.defaultAddressSpace(target, .function),
818 .variable => target_util.defaultAddressSpace(target, .global_mutable),
819 .constant => target_util.defaultAddressSpace(target, .global_constant),
820 else => unreachable,
821 };
822 const addrspace_ref = try sema.resolveInlineBody(&block_scope, addrspace_body, decl_inst);
823 break :blk try sema.analyzeAsAddressSpace(&block_scope, address_space_src, addrspace_ref, addrspace_ctx);
824 };
825 }
826 decl.has_tv = true;
827 decl.analysis = .complete;
828
829 const result: Zcu.SemaDeclResult = if (old_has_tv) .{
830 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
831 !decl.val.eql(old_val, decl_ty, zcu) or
832 is_inline != old_is_inline,
833 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
834 decl.alignment != old_align or
835 decl.@"linksection" != old_linksection or
836 decl.@"addrspace" != old_addrspace or
837 is_inline != old_is_inline,
838 } else .{
839 .invalidate_decl_val = true,
840 .invalidate_decl_ref = true,
841 };
842
843 const has_runtime_bits = queue_linker_work and (is_func or try sema.typeHasRuntimeBits(decl_ty));
844 if (has_runtime_bits) {
845 // Needed for codegen_decl which will call updateDecl and then the
846 // codegen backend wants full access to the Decl Type.
847 try decl_ty.resolveFully(pt);
848
849 try zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
850
851 if (result.invalidate_decl_ref and zcu.emit_h != null) {
852 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
853 }
854 }
855
856 if (decl.is_exported) {
857 const export_src = block_scope.src(.{ .token_offset = @intFromBool(decl.is_pub) });
858 if (is_inline) return sema.fail(&block_scope, export_src, "export of inline function", .{});
859 // The scope needs to have the decl in it.
860 try sema.analyzeExport(&block_scope, export_src, .{ .name = decl.name }, decl_index);
861 }
862
863 try sema.flushExports();
864
865 return result;
866}
867
868pub fn embedFile(
869 pt: Zcu.PerThread,
870 cur_file: *Zcu.File,
871 import_string: []const u8,
872 src_loc: Zcu.LazySrcLoc,
873) !InternPool.Index {
874 const mod = pt.zcu;
875 const gpa = mod.gpa;
876
877 if (cur_file.mod.deps.get(import_string)) |pkg| {
878 const resolved_path = try std.fs.path.resolve(gpa, &.{
879 pkg.root.root_dir.path orelse ".",
880 pkg.root.sub_path,
881 pkg.root_src_path,
882 });
883 var keep_resolved_path = false;
884 defer if (!keep_resolved_path) gpa.free(resolved_path);
885
886 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
887 errdefer {
888 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
889 keep_resolved_path = false;
890 }
891 if (gop.found_existing) return gop.value_ptr.*.val;
892 keep_resolved_path = true;
893
894 const sub_file_path = try gpa.dupe(u8, pkg.root_src_path);
895 errdefer gpa.free(sub_file_path);
896
897 return pt.newEmbedFile(pkg, sub_file_path, resolved_path, gop.value_ptr, src_loc);
898 }
899
900 // The resolved path is used as the key in the table, to detect if a file
901 // refers to the same as another, despite different relative paths.
902 const resolved_path = try std.fs.path.resolve(gpa, &.{
903 cur_file.mod.root.root_dir.path orelse ".",
904 cur_file.mod.root.sub_path,
905 cur_file.sub_file_path,
906 "..",
907 import_string,
908 });
909
910 var keep_resolved_path = false;
911 defer if (!keep_resolved_path) gpa.free(resolved_path);
912
913 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
914 errdefer {
915 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
916 keep_resolved_path = false;
917 }
918 if (gop.found_existing) return gop.value_ptr.*.val;
919 keep_resolved_path = true;
920
921 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
922 cur_file.mod.root.root_dir.path orelse ".",
923 cur_file.mod.root.sub_path,
924 });
925 defer gpa.free(resolved_root_path);
926
927 const sub_file_path = p: {
928 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
929 errdefer gpa.free(relative);
930
931 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
932 break :p relative;
933 }
934 return error.ImportOutsideModulePath;
935 };
936 defer gpa.free(sub_file_path);
937
938 return pt.newEmbedFile(cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
939}
940
941/// Finalize the creation of an anon decl.
942pub fn finalizeAnonDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) Allocator.Error!void {
943 if (pt.zcu.declPtr(decl_index).typeOf(pt.zcu).isFnOrHasRuntimeBits(pt)) {
944 try pt.zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
945 }
946}
947
948/// https://github.com/ziglang/zig/issues/14307
949fn newEmbedFile(
950 pt: Zcu.PerThread,
951 pkg: *Module,
952 sub_file_path: []const u8,
953 resolved_path: []const u8,
954 result: **Zcu.EmbedFile,
955 src_loc: Zcu.LazySrcLoc,
956) !InternPool.Index {
957 const mod = pt.zcu;
958 const gpa = mod.gpa;
959 const ip = &mod.intern_pool;
960
961 const new_file = try gpa.create(Zcu.EmbedFile);
962 errdefer gpa.destroy(new_file);
963
964 var file = try pkg.root.openFile(sub_file_path, .{});
965 defer file.close();
966
967 const actual_stat = try file.stat();
968 const stat: Cache.File.Stat = .{
969 .size = actual_stat.size,
970 .inode = actual_stat.inode,
971 .mtime = actual_stat.mtime,
972 };
973 const size = std.math.cast(usize, actual_stat.size) orelse return error.Overflow;
974
975 const bytes = try ip.string_bytes.addManyAsSlice(gpa, try std.math.add(usize, size, 1));
976 const actual_read = try file.readAll(bytes[0..size]);
977 if (actual_read != size) return error.UnexpectedEndOfFile;
978 bytes[size] = 0;
979
980 const comp = mod.comp;
981 switch (comp.cache_use) {
982 .whole => |whole| if (whole.cache_manifest) |man| {
983 const copied_resolved_path = try gpa.dupe(u8, resolved_path);
984 errdefer gpa.free(copied_resolved_path);
985 whole.cache_manifest_mutex.lock();
986 defer whole.cache_manifest_mutex.unlock();
987 try man.addFilePostContents(copied_resolved_path, bytes[0..size], stat);
988 },
989 .incremental => {},
990 }
991
992 const array_ty = try pt.intern(.{ .array_type = .{
993 .len = size,
994 .sentinel = .zero_u8,
995 .child = .u8_type,
996 } });
997 const array_val = try pt.intern(.{ .aggregate = .{
998 .ty = array_ty,
999 .storage = .{ .bytes = try ip.getOrPutTrailingString(gpa, bytes.len, .maybe_embedded_nulls) },
1000 } });
1001
1002 const ptr_ty = (try pt.ptrType(.{
1003 .child = array_ty,
1004 .flags = .{
1005 .alignment = .none,
1006 .is_const = true,
1007 .address_space = .generic,
1008 },
1009 })).toIntern();
1010 const ptr_val = try pt.intern(.{ .ptr = .{
1011 .ty = ptr_ty,
1012 .base_addr = .{ .anon_decl = .{
1013 .val = array_val,
1014 .orig_ty = ptr_ty,
1015 } },
1016 .byte_offset = 0,
1017 } });
1018
1019 result.* = new_file;
1020 new_file.* = .{
1021 .sub_file_path = try ip.getOrPutString(gpa, sub_file_path, .no_embedded_nulls),
1022 .owner = pkg,
1023 .stat = stat,
1024 .val = ptr_val,
1025 .src_loc = src_loc,
1026 };
1027 return ptr_val;
1028}
1029
1030pub fn analyzeFnBody(pt: Zcu.PerThread, func_index: InternPool.Index, arena: Allocator) Zcu.SemaError!Air {
1031 const tracy = trace(@src());
1032 defer tracy.end();
1033
1034 const mod = pt.zcu;
1035 const gpa = mod.gpa;
1036 const ip = &mod.intern_pool;
1037 const func = mod.funcInfo(func_index);
1038 const decl_index = func.owner_decl;
1039 const decl = mod.declPtr(decl_index);
1040
1041 log.debug("func name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
1042 defer blk: {
1043 log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
1044 }
1045
1046 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
1047 defer decl_prog_node.end();
1048
1049 mod.intern_pool.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
1050
1051 var comptime_err_ret_trace = std.ArrayList(Zcu.LazySrcLoc).init(gpa);
1052 defer comptime_err_ret_trace.deinit();
1053
1054 // In the case of a generic function instance, this is the type of the
1055 // instance, which has comptime parameters elided. In other words, it is
1056 // the runtime-known parameters only, not to be confused with the
1057 // generic_owner function type, which potentially has more parameters,
1058 // including comptime parameters.
1059 const fn_ty = decl.typeOf(mod);
1060 const fn_ty_info = mod.typeToFunc(fn_ty).?;
1061
1062 var sema: Sema = .{
1063 .pt = pt,
1064 .gpa = gpa,
1065 .arena = arena,
1066 .code = decl.getFileScope(mod).zir,
1067 .owner_decl = decl,
1068 .owner_decl_index = decl_index,
1069 .func_index = func_index,
1070 .func_is_naked = fn_ty_info.cc == .Naked,
1071 .fn_ret_ty = Type.fromInterned(fn_ty_info.return_type),
1072 .fn_ret_ty_ies = null,
1073 .owner_func_index = func_index,
1074 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
1075 .comptime_err_ret_trace = &comptime_err_ret_trace,
1076 };
1077 defer sema.deinit();
1078
1079 // Every runtime function has a dependency on the source of the Decl it originates from.
1080 // It also depends on the value of its owner Decl.
1081 try sema.declareDependency(.{ .src_hash = decl.zir_decl_index.unwrap().? });
1082 try sema.declareDependency(.{ .decl_val = decl_index });
1083
1084 if (func.analysis(ip).inferred_error_set) {
1085 const ies = try arena.create(Sema.InferredErrorSet);
1086 ies.* = .{ .func = func_index };
1087 sema.fn_ret_ty_ies = ies;
1088 }
1089
1090 // reset in case calls to errorable functions are removed.
1091 func.analysis(ip).calls_or_awaits_errorable_fn = false;
1092
1093 // First few indexes of extra are reserved and set at the end.
1094 const reserved_count = @typeInfo(Air.ExtraIndex).Enum.fields.len;
1095 try sema.air_extra.ensureTotalCapacity(gpa, reserved_count);
1096 sema.air_extra.items.len += reserved_count;
1097
1098 var inner_block: Sema.Block = .{
1099 .parent = null,
1100 .sema = &sema,
1101 .namespace = decl.src_namespace,
1102 .instructions = .{},
1103 .inlining = null,
1104 .is_comptime = false,
1105 .src_base_inst = inst: {
1106 const owner_info = if (func.generic_owner == .none)
1107 func
1108 else
1109 mod.funcInfo(func.generic_owner);
1110 const orig_decl = mod.declPtr(owner_info.owner_decl);
1111 break :inst orig_decl.zir_decl_index.unwrap().?;
1112 },
1113 .type_name_ctx = decl.name,
1114 };
1115 defer inner_block.instructions.deinit(gpa);
1116
1117 const fn_info = sema.code.getFnInfo(func.zirBodyInst(ip).resolve(ip));
1118
1119 // Here we are performing "runtime semantic analysis" for a function body, which means
1120 // we must map the parameter ZIR instructions to `arg` AIR instructions.
1121 // AIR requires the `arg` parameters to be the first N instructions.
1122 // This could be a generic function instantiation, however, in which case we need to
1123 // map the comptime parameters to constant values and only emit arg AIR instructions
1124 // for the runtime ones.
1125 const runtime_params_len = fn_ty_info.param_types.len;
1126 try inner_block.instructions.ensureTotalCapacityPrecise(gpa, runtime_params_len);
1127 try sema.air_instructions.ensureUnusedCapacity(gpa, fn_info.total_params_len);
1128 try sema.inst_map.ensureSpaceForInstructions(gpa, fn_info.param_body);
1129
1130 // In the case of a generic function instance, pre-populate all the comptime args.
1131 if (func.comptime_args.len != 0) {
1132 for (
1133 fn_info.param_body[0..func.comptime_args.len],
1134 func.comptime_args.get(ip),
1135 ) |inst, comptime_arg| {
1136 if (comptime_arg == .none) continue;
1137 sema.inst_map.putAssumeCapacityNoClobber(inst, Air.internedToRef(comptime_arg));
1138 }
1139 }
1140
1141 const src_params_len = if (func.comptime_args.len != 0)
1142 func.comptime_args.len
1143 else
1144 runtime_params_len;
1145
1146 var runtime_param_index: usize = 0;
1147 for (fn_info.param_body[0..src_params_len], 0..) |inst, src_param_index| {
1148 const gop = sema.inst_map.getOrPutAssumeCapacity(inst);
1149 if (gop.found_existing) continue; // provided above by comptime arg
1150
1151 const param_ty = fn_ty_info.param_types.get(ip)[runtime_param_index];
1152 runtime_param_index += 1;
1153
1154 const opt_opv = sema.typeHasOnePossibleValue(Type.fromInterned(param_ty)) catch |err| switch (err) {
1155 error.GenericPoison => unreachable,
1156 error.ComptimeReturn => unreachable,
1157 error.ComptimeBreak => unreachable,
1158 else => |e| return e,
1159 };
1160 if (opt_opv) |opv| {
1161 gop.value_ptr.* = Air.internedToRef(opv.toIntern());
1162 continue;
1163 }
1164 const arg_index: Air.Inst.Index = @enumFromInt(sema.air_instructions.len);
1165 gop.value_ptr.* = arg_index.toRef();
1166 inner_block.instructions.appendAssumeCapacity(arg_index);
1167 sema.air_instructions.appendAssumeCapacity(.{
1168 .tag = .arg,
1169 .data = .{ .arg = .{
1170 .ty = Air.internedToRef(param_ty),
1171 .src_index = @intCast(src_param_index),
1172 } },
1173 });
1174 }
1175
1176 func.analysis(ip).state = .in_progress;
1177
1178 const last_arg_index = inner_block.instructions.items.len;
1179
1180 // Save the error trace as our first action in the function.
1181 // If this is unnecessary after all, Liveness will clean it up for us.
1182 const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&inner_block);
1183 sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
1184 inner_block.error_return_trace_index = error_return_trace_index;
1185
1186 sema.analyzeFnBody(&inner_block, fn_info.body) catch |err| switch (err) {
1187 // TODO make these unreachable instead of @panic
1188 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
1189 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
1190 else => |e| return e,
1191 };
1192
1193 for (sema.unresolved_inferred_allocs.keys()) |ptr_inst| {
1194 // The lack of a resolve_inferred_alloc means that this instruction
1195 // is unused so it just has to be a no-op.
1196 sema.air_instructions.set(@intFromEnum(ptr_inst), .{
1197 .tag = .alloc,
1198 .data = .{ .ty = Type.single_const_pointer_to_comptime_int },
1199 });
1200 }
1201
1202 // If we don't get an error return trace from a caller, create our own.
1203 if (func.analysis(ip).calls_or_awaits_errorable_fn and
1204 mod.comp.config.any_error_tracing and
1205 !sema.fn_ret_ty.isError(mod))
1206 {
1207 sema.setupErrorReturnTrace(&inner_block, last_arg_index) catch |err| switch (err) {
1208 // TODO make these unreachable instead of @panic
1209 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
1210 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
1211 error.ComptimeBreak => @panic("zig compiler bug: ComptimeBreak"),
1212 else => |e| return e,
1213 };
1214 }
1215
1216 // Copy the block into place and mark that as the main block.
1217 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
1218 inner_block.instructions.items.len);
1219 const main_block_index = sema.addExtraAssumeCapacity(Air.Block{
1220 .body_len = @intCast(inner_block.instructions.items.len),
1221 });
1222 sema.air_extra.appendSliceAssumeCapacity(@ptrCast(inner_block.instructions.items));
1223 sema.air_extra.items[@intFromEnum(Air.ExtraIndex.main_block)] = main_block_index;
1224
1225 // Resolving inferred error sets is done *before* setting the function
1226 // state to success, so that "unable to resolve inferred error set" errors
1227 // can be emitted here.
1228 if (sema.fn_ret_ty_ies) |ies| {
1229 sema.resolveInferredErrorSetPtr(&inner_block, .{
1230 .base_node_inst = inner_block.src_base_inst,
1231 .offset = Zcu.LazySrcLoc.Offset.nodeOffset(0),
1232 }, ies) catch |err| switch (err) {
1233 error.GenericPoison => unreachable,
1234 error.ComptimeReturn => unreachable,
1235 error.ComptimeBreak => unreachable,
1236 error.AnalysisFail => {
1237 // In this case our function depends on a type that had a compile error.
1238 // We should not try to lower this function.
1239 decl.analysis = .dependency_failure;
1240 return error.AnalysisFail;
1241 },
1242 else => |e| return e,
1243 };
1244 assert(ies.resolved != .none);
1245 ip.funcIesResolved(func_index).* = ies.resolved;
1246 }
1247
1248 func.analysis(ip).state = .success;
1249
1250 // Finally we must resolve the return type and parameter types so that backends
1251 // have full access to type information.
1252 // Crucially, this happens *after* we set the function state to success above,
1253 // so that dependencies on the function body will now be satisfied rather than
1254 // result in circular dependency errors.
1255 sema.resolveFnTypes(fn_ty) catch |err| switch (err) {
1256 error.GenericPoison => unreachable,
1257 error.ComptimeReturn => unreachable,
1258 error.ComptimeBreak => unreachable,
1259 error.AnalysisFail => {
1260 // In this case our function depends on a type that had a compile error.
1261 // We should not try to lower this function.
1262 decl.analysis = .dependency_failure;
1263 return error.AnalysisFail;
1264 },
1265 else => |e| return e,
1266 };
1267
1268 try sema.flushExports();
1269
1270 return .{
1271 .instructions = sema.air_instructions.toOwnedSlice(),
1272 .extra = try sema.air_extra.toOwnedSlice(gpa),
1273 };
1274}
1275
1276/// Called from `Compilation.update`, after everything is done, just before
1277/// reporting compile errors. In this function we emit exported symbol collision
1278/// errors and communicate exported symbols to the linker backend.
1279pub fn processExports(pt: Zcu.PerThread) !void {
1280 const zcu = pt.zcu;
1281 const gpa = zcu.gpa;
1282
1283 // First, construct a mapping of every exported value and Decl to the indices of all its different exports.
1284 var decl_exports: std.AutoArrayHashMapUnmanaged(Zcu.Decl.Index, std.ArrayListUnmanaged(u32)) = .{};
1285 var value_exports: std.AutoArrayHashMapUnmanaged(InternPool.Index, std.ArrayListUnmanaged(u32)) = .{};
1286 defer {
1287 for (decl_exports.values()) |*exports| {
1288 exports.deinit(gpa);
1289 }
1290 decl_exports.deinit(gpa);
1291 for (value_exports.values()) |*exports| {
1292 exports.deinit(gpa);
1293 }
1294 value_exports.deinit(gpa);
1295 }
1296
1297 // We note as a heuristic:
1298 // * It is rare to export a value.
1299 // * It is rare for one Decl to be exported multiple times.
1300 // So, this ensureTotalCapacity serves as a reasonable (albeit very approximate) optimization.
1301 try decl_exports.ensureTotalCapacity(gpa, zcu.single_exports.count() + zcu.multi_exports.count());
1302
1303 for (zcu.single_exports.values()) |export_idx| {
1304 const exp = zcu.all_exports.items[export_idx];
1305 const value_ptr, const found_existing = switch (exp.exported) {
1306 .decl_index => |i| gop: {
1307 const gop = try decl_exports.getOrPut(gpa, i);
1308 break :gop .{ gop.value_ptr, gop.found_existing };
1309 },
1310 .value => |i| gop: {
1311 const gop = try value_exports.getOrPut(gpa, i);
1312 break :gop .{ gop.value_ptr, gop.found_existing };
1313 },
1314 };
1315 if (!found_existing) value_ptr.* = .{};
1316 try value_ptr.append(gpa, export_idx);
1317 }
1318
1319 for (zcu.multi_exports.values()) |info| {
1320 for (zcu.all_exports.items[info.index..][0..info.len], info.index..) |exp, export_idx| {
1321 const value_ptr, const found_existing = switch (exp.exported) {
1322 .decl_index => |i| gop: {
1323 const gop = try decl_exports.getOrPut(gpa, i);
1324 break :gop .{ gop.value_ptr, gop.found_existing };
1325 },
1326 .value => |i| gop: {
1327 const gop = try value_exports.getOrPut(gpa, i);
1328 break :gop .{ gop.value_ptr, gop.found_existing };
1329 },
1330 };
1331 if (!found_existing) value_ptr.* = .{};
1332 try value_ptr.append(gpa, @intCast(export_idx));
1333 }
1334 }
1335
1336 // Map symbol names to `Export` for name collision detection.
1337 var symbol_exports: SymbolExports = .{};
1338 defer symbol_exports.deinit(gpa);
1339
1340 for (decl_exports.keys(), decl_exports.values()) |exported_decl, exports_list| {
1341 const exported: Zcu.Exported = .{ .decl_index = exported_decl };
1342 try pt.processExportsInner(&symbol_exports, exported, exports_list.items);
1343 }
1344
1345 for (value_exports.keys(), value_exports.values()) |exported_value, exports_list| {
1346 const exported: Zcu.Exported = .{ .value = exported_value };
1347 try pt.processExportsInner(&symbol_exports, exported, exports_list.items);
1348 }
1349}
1350
1351const SymbolExports = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, u32);
1352
1353fn processExportsInner(
1354 pt: Zcu.PerThread,
1355 symbol_exports: *SymbolExports,
1356 exported: Zcu.Exported,
1357 export_indices: []const u32,
1358) error{OutOfMemory}!void {
1359 const zcu = pt.zcu;
1360 const gpa = zcu.gpa;
1361
1362 for (export_indices) |export_idx| {
1363 const new_export = &zcu.all_exports.items[export_idx];
1364 const gop = try symbol_exports.getOrPut(gpa, new_export.opts.name);
1365 if (gop.found_existing) {
1366 new_export.status = .failed_retryable;
1367 try zcu.failed_exports.ensureUnusedCapacity(gpa, 1);
1368 const msg = try Zcu.ErrorMsg.create(gpa, new_export.src, "exported symbol collision: {}", .{
1369 new_export.opts.name.fmt(&zcu.intern_pool),
1370 });
1371 errdefer msg.destroy(gpa);
1372 const other_export = zcu.all_exports.items[gop.value_ptr.*];
1373 try zcu.errNote(other_export.src, msg, "other symbol here", .{});
1374 zcu.failed_exports.putAssumeCapacityNoClobber(export_idx, msg);
1375 new_export.status = .failed;
1376 } else {
1377 gop.value_ptr.* = export_idx;
1378 }
1379 }
1380 if (zcu.comp.bin_file) |lf| {
1381 try zcu.handleUpdateExports(export_indices, lf.updateExports(pt, exported, export_indices));
1382 } else if (zcu.llvm_object) |llvm_object| {
1383 if (build_options.only_c) unreachable;
1384 try zcu.handleUpdateExports(export_indices, llvm_object.updateExports(pt, exported, export_indices));
1385 }
1386}
1387
1388pub fn populateTestFunctions(
1389 pt: Zcu.PerThread,
1390 main_progress_node: std.Progress.Node,
1391) !void {
1392 const zcu = pt.zcu;
1393 const gpa = zcu.gpa;
1394 const ip = &zcu.intern_pool;
1395 const builtin_mod = zcu.root_mod.getBuiltinDependency();
1396 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
1397 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
1398 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
1399 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
1400 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);
1401 const decl_index = builtin_namespace.decls.getKeyAdapted(
1402 test_functions_str,
1403 Zcu.DeclAdapter{ .zcu = zcu },
1404 ).?;
1405 {
1406 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
1407 // was not referenced by start code.
1408 zcu.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
1409 defer {
1410 zcu.sema_prog_node.end();
1411 zcu.sema_prog_node = undefined;
1412 }
1413 try pt.ensureDeclAnalyzed(decl_index);
1414 }
1415
1416 const decl = zcu.declPtr(decl_index);
1417 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
1418
1419 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
1420 // Add zcu.test_functions to an array decl then make the test_functions
1421 // decl reference it as a slice.
1422 const test_fn_vals = try gpa.alloc(InternPool.Index, zcu.test_functions.count());
1423 defer gpa.free(test_fn_vals);
1424
1425 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
1426 const test_decl = zcu.declPtr(test_decl_index);
1427 const test_decl_name = try test_decl.fullyQualifiedName(zcu);
1428 const test_decl_name_len = test_decl_name.length(ip);
1429 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
1430 const test_name_ty = try pt.arrayType(.{
1431 .len = test_decl_name_len,
1432 .child = .u8_type,
1433 });
1434 const test_name_val = try pt.intern(.{ .aggregate = .{
1435 .ty = test_name_ty.toIntern(),
1436 .storage = .{ .bytes = test_decl_name.toString() },
1437 } });
1438 break :n .{
1439 .orig_ty = (try pt.singleConstPtrType(test_name_ty)).toIntern(),
1440 .val = test_name_val,
1441 };
1442 };
1443
1444 const test_fn_fields = .{
1445 // name
1446 try pt.intern(.{ .slice = .{
1447 .ty = .slice_const_u8_type,
1448 .ptr = try pt.intern(.{ .ptr = .{
1449 .ty = .manyptr_const_u8_type,
1450 .base_addr = .{ .anon_decl = test_name_anon_decl },
1451 .byte_offset = 0,
1452 } }),
1453 .len = try pt.intern(.{ .int = .{
1454 .ty = .usize_type,
1455 .storage = .{ .u64 = test_decl_name_len },
1456 } }),
1457 } }),
1458 // func
1459 try pt.intern(.{ .ptr = .{
1460 .ty = try pt.intern(.{ .ptr_type = .{
1461 .child = test_decl.typeOf(zcu).toIntern(),
1462 .flags = .{
1463 .is_const = true,
1464 },
1465 } }),
1466 .base_addr = .{ .decl = test_decl_index },
1467 .byte_offset = 0,
1468 } }),
1469 };
1470 test_fn_val.* = try pt.intern(.{ .aggregate = .{
1471 .ty = test_fn_ty.toIntern(),
1472 .storage = .{ .elems = &test_fn_fields },
1473 } });
1474 }
1475
1476 const array_ty = try pt.arrayType(.{
1477 .len = test_fn_vals.len,
1478 .child = test_fn_ty.toIntern(),
1479 .sentinel = .none,
1480 });
1481 const array_val = try pt.intern(.{ .aggregate = .{
1482 .ty = array_ty.toIntern(),
1483 .storage = .{ .elems = test_fn_vals },
1484 } });
1485 break :array .{
1486 .orig_ty = (try pt.singleConstPtrType(array_ty)).toIntern(),
1487 .val = array_val,
1488 };
1489 };
1490
1491 {
1492 const new_ty = try pt.ptrType(.{
1493 .child = test_fn_ty.toIntern(),
1494 .flags = .{
1495 .is_const = true,
1496 .size = .Slice,
1497 },
1498 });
1499 const new_val = decl.val;
1500 const new_init = try pt.intern(.{ .slice = .{
1501 .ty = new_ty.toIntern(),
1502 .ptr = try pt.intern(.{ .ptr = .{
1503 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
1504 .base_addr = .{ .anon_decl = array_anon_decl },
1505 .byte_offset = 0,
1506 } }),
1507 .len = (try pt.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
1508 } });
1509 ip.mutateVarInit(decl.val.toIntern(), new_init);
1510
1511 // Since we are replacing the Decl's value we must perform cleanup on the
1512 // previous value.
1513 decl.val = new_val;
1514 decl.has_tv = true;
1515 }
1516 {
1517 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
1518 defer {
1519 zcu.codegen_prog_node.end();
1520 zcu.codegen_prog_node = undefined;
1521 }
1522
1523 try pt.linkerUpdateDecl(decl_index);
1524 }
1525}
1526
1527pub fn linkerUpdateDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) !void {
1528 const zcu = pt.zcu;
1529 const comp = zcu.comp;
1530
1531 const decl = zcu.declPtr(decl_index);
1532
1533 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool), 0);
1534 defer codegen_prog_node.end();
1535
1536 if (comp.bin_file) |lf| {
1537 lf.updateDecl(pt, decl_index) catch |err| switch (err) {
1538 error.OutOfMemory => return error.OutOfMemory,
1539 error.AnalysisFail => {
1540 decl.analysis = .codegen_failure;
1541 },
1542 else => {
1543 const gpa = zcu.gpa;
1544 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
1545 zcu.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .decl = decl_index }), try Zcu.ErrorMsg.create(
1546 gpa,
1547 decl.navSrcLoc(zcu),
1548 "unable to codegen: {s}",
1549 .{@errorName(err)},
1550 ));
1551 decl.analysis = .codegen_failure;
1552 try zcu.retryable_failures.append(zcu.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
1553 },
1554 };
1555 } else if (zcu.llvm_object) |llvm_object| {
1556 if (build_options.only_c) unreachable;
1557 llvm_object.updateDecl(pt, decl_index) catch |err| switch (err) {
1558 error.OutOfMemory => return error.OutOfMemory,
1559 };
1560 }
1561}
1562
1563/// Shortcut for calling `intern_pool.get`.
1564pub fn intern(pt: Zcu.PerThread, key: InternPool.Key) Allocator.Error!InternPool.Index {
1565 return pt.zcu.intern_pool.get(pt.zcu.gpa, pt.tid, key);
1566}
1567
1568/// Shortcut for calling `intern_pool.getCoerced`.
1569pub fn getCoerced(pt: Zcu.PerThread, val: Value, new_ty: Type) Allocator.Error!Value {
1570 return Value.fromInterned(try pt.zcu.intern_pool.getCoerced(pt.zcu.gpa, pt.tid, val.toIntern(), new_ty.toIntern()));
1571}
1572
1573pub fn intType(pt: Zcu.PerThread, signedness: std.builtin.Signedness, bits: u16) Allocator.Error!Type {
1574 return Type.fromInterned(try pt.intern(.{ .int_type = .{
1575 .signedness = signedness,
1576 .bits = bits,
1577 } }));
1578}
1579
1580pub fn errorIntType(pt: Zcu.PerThread) std.mem.Allocator.Error!Type {
1581 return pt.intType(.unsigned, pt.zcu.errorSetBits());
1582}
1583
1584pub fn arrayType(pt: Zcu.PerThread, info: InternPool.Key.ArrayType) Allocator.Error!Type {
1585 return Type.fromInterned(try pt.intern(.{ .array_type = info }));
1586}
1587
1588pub fn vectorType(pt: Zcu.PerThread, info: InternPool.Key.VectorType) Allocator.Error!Type {
1589 return Type.fromInterned(try pt.intern(.{ .vector_type = info }));
1590}
1591
1592pub fn optionalType(pt: Zcu.PerThread, child_type: InternPool.Index) Allocator.Error!Type {
1593 return Type.fromInterned(try pt.intern(.{ .opt_type = child_type }));
1594}
1595
1596pub fn ptrType(pt: Zcu.PerThread, info: InternPool.Key.PtrType) Allocator.Error!Type {
1597 var canon_info = info;
1598
1599 if (info.flags.size == .C) canon_info.flags.is_allowzero = true;
1600
1601 // Canonicalize non-zero alignment. If it matches the ABI alignment of the pointee
1602 // type, we change it to 0 here. If this causes an assertion trip because the
1603 // pointee type needs to be resolved more, that needs to be done before calling
1604 // this ptr() function.
1605 if (info.flags.alignment != .none and
1606 info.flags.alignment == Type.fromInterned(info.child).abiAlignment(pt))
1607 {
1608 canon_info.flags.alignment = .none;
1609 }
1610
1611 switch (info.flags.vector_index) {
1612 // Canonicalize host_size. If it matches the bit size of the pointee type,
1613 // we change it to 0 here. If this causes an assertion trip, the pointee type
1614 // needs to be resolved before calling this ptr() function.
1615 .none => if (info.packed_offset.host_size != 0) {
1616 const elem_bit_size = Type.fromInterned(info.child).bitSize(pt);
1617 assert(info.packed_offset.bit_offset + elem_bit_size <= info.packed_offset.host_size * 8);
1618 if (info.packed_offset.host_size * 8 == elem_bit_size) {
1619 canon_info.packed_offset.host_size = 0;
1620 }
1621 },
1622 .runtime => {},
1623 _ => assert(@intFromEnum(info.flags.vector_index) < info.packed_offset.host_size),
1624 }
1625
1626 return Type.fromInterned(try pt.intern(.{ .ptr_type = canon_info }));
1627}
1628
1629/// Like `ptrType`, but if `info` specifies an `alignment`, first ensures the pointer
1630/// child type's alignment is resolved so that an invalid alignment is not used.
1631/// In general, prefer this function during semantic analysis.
1632pub fn ptrTypeSema(pt: Zcu.PerThread, info: InternPool.Key.PtrType) Zcu.SemaError!Type {
1633 if (info.flags.alignment != .none) {
1634 _ = try Type.fromInterned(info.child).abiAlignmentAdvanced(pt, .sema);
1635 }
1636 return pt.ptrType(info);
1637}
1638
1639pub fn singleMutPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
1640 return pt.ptrType(.{ .child = child_type.toIntern() });
1641}
1642
1643pub fn singleConstPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
1644 return pt.ptrType(.{
1645 .child = child_type.toIntern(),
1646 .flags = .{
1647 .is_const = true,
1648 },
1649 });
1650}
1651
1652pub fn manyConstPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
1653 return pt.ptrType(.{
1654 .child = child_type.toIntern(),
1655 .flags = .{
1656 .size = .Many,
1657 .is_const = true,
1658 },
1659 });
1660}
1661
1662pub fn adjustPtrTypeChild(pt: Zcu.PerThread, ptr_ty: Type, new_child: Type) Allocator.Error!Type {
1663 var info = ptr_ty.ptrInfo(pt.zcu);
1664 info.child = new_child.toIntern();
1665 return pt.ptrType(info);
1666}
1667
1668pub fn funcType(pt: Zcu.PerThread, key: InternPool.GetFuncTypeKey) Allocator.Error!Type {
1669 return Type.fromInterned(try pt.zcu.intern_pool.getFuncType(pt.zcu.gpa, pt.tid, key));
1670}
1671
1672/// Use this for `anyframe->T` only.
1673/// For `anyframe`, use the `InternPool.Index.anyframe` tag directly.
1674pub fn anyframeType(pt: Zcu.PerThread, payload_ty: Type) Allocator.Error!Type {
1675 return Type.fromInterned(try pt.intern(.{ .anyframe_type = payload_ty.toIntern() }));
1676}
1677
1678pub fn errorUnionType(pt: Zcu.PerThread, error_set_ty: Type, payload_ty: Type) Allocator.Error!Type {
1679 return Type.fromInterned(try pt.intern(.{ .error_union_type = .{
1680 .error_set_type = error_set_ty.toIntern(),
1681 .payload_type = payload_ty.toIntern(),
1682 } }));
1683}
1684
1685pub fn singleErrorSetType(pt: Zcu.PerThread, name: InternPool.NullTerminatedString) Allocator.Error!Type {
1686 const names: *const [1]InternPool.NullTerminatedString = &name;
1687 return Type.fromInterned(try pt.zcu.intern_pool.getErrorSetType(pt.zcu.gpa, pt.tid, names));
1688}
1689
1690/// Sorts `names` in place.
1691pub fn errorSetFromUnsortedNames(
1692 pt: Zcu.PerThread,
1693 names: []InternPool.NullTerminatedString,
1694) Allocator.Error!Type {
1695 std.mem.sort(
1696 InternPool.NullTerminatedString,
1697 names,
1698 {},
1699 InternPool.NullTerminatedString.indexLessThan,
1700 );
1701 const new_ty = try pt.zcu.intern_pool.getErrorSetType(pt.zcu.gpa, pt.tid, names);
1702 return Type.fromInterned(new_ty);
1703}
1704
1705/// Supports only pointers, not pointer-like optionals.
1706pub fn ptrIntValue(pt: Zcu.PerThread, ty: Type, x: u64) Allocator.Error!Value {
1707 const mod = pt.zcu;
1708 assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
1709 assert(x != 0 or ty.isAllowzeroPtr(mod));
1710 return Value.fromInterned(try pt.intern(.{ .ptr = .{
1711 .ty = ty.toIntern(),
1712 .base_addr = .int,
1713 .byte_offset = x,
1714 } }));
1715}
1716
1717/// Creates an enum tag value based on the integer tag value.
1718pub fn enumValue(pt: Zcu.PerThread, ty: Type, tag_int: InternPool.Index) Allocator.Error!Value {
1719 if (std.debug.runtime_safety) {
1720 const tag = ty.zigTypeTag(pt.zcu);
1721 assert(tag == .Enum);
1722 }
1723 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
1724 .ty = ty.toIntern(),
1725 .int = tag_int,
1726 } }));
1727}
1728
1729/// Creates an enum tag value based on the field index according to source code
1730/// declaration order.
1731pub fn enumValueFieldIndex(pt: Zcu.PerThread, ty: Type, field_index: u32) Allocator.Error!Value {
1732 const ip = &pt.zcu.intern_pool;
1733 const enum_type = ip.loadEnumType(ty.toIntern());
1734
1735 if (enum_type.values.len == 0) {
1736 // Auto-numbered fields.
1737 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
1738 .ty = ty.toIntern(),
1739 .int = try pt.intern(.{ .int = .{
1740 .ty = enum_type.tag_ty,
1741 .storage = .{ .u64 = field_index },
1742 } }),
1743 } }));
1744 }
1745
1746 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
1747 .ty = ty.toIntern(),
1748 .int = enum_type.values.get(ip)[field_index],
1749 } }));
1750}
1751
1752pub fn undefValue(pt: Zcu.PerThread, ty: Type) Allocator.Error!Value {
1753 return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
1754}
1755
1756pub fn undefRef(pt: Zcu.PerThread, ty: Type) Allocator.Error!Air.Inst.Ref {
1757 return Air.internedToRef((try pt.undefValue(ty)).toIntern());
1758}
1759
1760pub fn intValue(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Value {
1761 if (std.math.cast(u64, x)) |casted| return pt.intValue_u64(ty, casted);
1762 if (std.math.cast(i64, x)) |casted| return pt.intValue_i64(ty, casted);
1763 var limbs_buffer: [4]usize = undefined;
1764 var big_int = BigIntMutable.init(&limbs_buffer, x);
1765 return pt.intValue_big(ty, big_int.toConst());
1766}
1767
1768pub fn intRef(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Air.Inst.Ref {
1769 return Air.internedToRef((try pt.intValue(ty, x)).toIntern());
1770}
1771
1772pub fn intValue_big(pt: Zcu.PerThread, ty: Type, x: BigIntConst) Allocator.Error!Value {
1773 return Value.fromInterned(try pt.intern(.{ .int = .{
1774 .ty = ty.toIntern(),
1775 .storage = .{ .big_int = x },
1776 } }));
1777}
1778
1779pub fn intValue_u64(pt: Zcu.PerThread, ty: Type, x: u64) Allocator.Error!Value {
1780 return Value.fromInterned(try pt.intern(.{ .int = .{
1781 .ty = ty.toIntern(),
1782 .storage = .{ .u64 = x },
1783 } }));
1784}
1785
1786pub fn intValue_i64(pt: Zcu.PerThread, ty: Type, x: i64) Allocator.Error!Value {
1787 return Value.fromInterned(try pt.intern(.{ .int = .{
1788 .ty = ty.toIntern(),
1789 .storage = .{ .i64 = x },
1790 } }));
1791}
1792
1793pub fn unionValue(pt: Zcu.PerThread, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
1794 return Value.fromInterned(try pt.intern(.{ .un = .{
1795 .ty = union_ty.toIntern(),
1796 .tag = tag.toIntern(),
1797 .val = val.toIntern(),
1798 } }));
1799}
1800
1801/// This function casts the float representation down to the representation of the type, potentially
1802/// losing data if the representation wasn't correct.
1803pub fn floatValue(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Value {
1804 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(pt.zcu.getTarget())) {
1805 16 => .{ .f16 = @as(f16, @floatCast(x)) },
1806 32 => .{ .f32 = @as(f32, @floatCast(x)) },
1807 64 => .{ .f64 = @as(f64, @floatCast(x)) },
1808 80 => .{ .f80 = @as(f80, @floatCast(x)) },
1809 128 => .{ .f128 = @as(f128, @floatCast(x)) },
1810 else => unreachable,
1811 };
1812 return Value.fromInterned(try pt.intern(.{ .float = .{
1813 .ty = ty.toIntern(),
1814 .storage = storage,
1815 } }));
1816}
1817
1818pub fn nullValue(pt: Zcu.PerThread, opt_ty: Type) Allocator.Error!Value {
1819 assert(pt.zcu.intern_pool.isOptionalType(opt_ty.toIntern()));
1820 return Value.fromInterned(try pt.intern(.{ .opt = .{
1821 .ty = opt_ty.toIntern(),
1822 .val = .none,
1823 } }));
1824}
1825
1826pub fn smallestUnsignedInt(pt: Zcu.PerThread, max: u64) Allocator.Error!Type {
1827 return pt.intType(.unsigned, Type.smallestUnsignedBits(max));
1828}
1829
1830/// Returns the smallest possible integer type containing both `min` and
1831/// `max`. Asserts that neither value is undef.
1832/// TODO: if #3806 is implemented, this becomes trivial
1833pub fn intFittingRange(pt: Zcu.PerThread, min: Value, max: Value) !Type {
1834 const mod = pt.zcu;
1835 assert(!min.isUndef(mod));
1836 assert(!max.isUndef(mod));
1837
1838 if (std.debug.runtime_safety) {
1839 assert(Value.order(min, max, pt).compare(.lte));
1840 }
1841
1842 const sign = min.orderAgainstZero(pt) == .lt;
1843
1844 const min_val_bits = pt.intBitsForValue(min, sign);
1845 const max_val_bits = pt.intBitsForValue(max, sign);
1846
1847 return pt.intType(
1848 if (sign) .signed else .unsigned,
1849 @max(min_val_bits, max_val_bits),
1850 );
1851}
1852
1853/// Given a value representing an integer, returns the number of bits necessary to represent
1854/// this value in an integer. If `sign` is true, returns the number of bits necessary in a
1855/// twos-complement integer; otherwise in an unsigned integer.
1856/// Asserts that `val` is not undef. If `val` is negative, asserts that `sign` is true.
1857pub fn intBitsForValue(pt: Zcu.PerThread, val: Value, sign: bool) u16 {
1858 const mod = pt.zcu;
1859 assert(!val.isUndef(mod));
1860
1861 const key = mod.intern_pool.indexToKey(val.toIntern());
1862 switch (key.int.storage) {
1863 .i64 => |x| {
1864 if (std.math.cast(u64, x)) |casted| return Type.smallestUnsignedBits(casted) + @intFromBool(sign);
1865 assert(sign);
1866 // Protect against overflow in the following negation.
1867 if (x == std.math.minInt(i64)) return 64;
1868 return Type.smallestUnsignedBits(@as(u64, @intCast(-(x + 1)))) + 1;
1869 },
1870 .u64 => |x| {
1871 return Type.smallestUnsignedBits(x) + @intFromBool(sign);
1872 },
1873 .big_int => |big| {
1874 if (big.positive) return @as(u16, @intCast(big.bitCountAbs() + @intFromBool(sign)));
1875
1876 // Zero is still a possibility, in which case unsigned is fine
1877 if (big.eqlZero()) return 0;
1878
1879 return @as(u16, @intCast(big.bitCountTwosComp()));
1880 },
1881 .lazy_align => |lazy_ty| {
1882 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiAlignment(pt).toByteUnits() orelse 0) + @intFromBool(sign);
1883 },
1884 .lazy_size => |lazy_ty| {
1885 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiSize(pt)) + @intFromBool(sign);
1886 },
1887 }
1888}
1889
1890pub fn getUnionLayout(pt: Zcu.PerThread, loaded_union: InternPool.LoadedUnionType) Zcu.UnionLayout {
1891 const mod = pt.zcu;
1892 const ip = &mod.intern_pool;
1893 assert(loaded_union.haveLayout(ip));
1894 var most_aligned_field: u32 = undefined;
1895 var most_aligned_field_size: u64 = undefined;
1896 var biggest_field: u32 = undefined;
1897 var payload_size: u64 = 0;
1898 var payload_align: InternPool.Alignment = .@"1";
1899 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
1900 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
1901
1902 const explicit_align = loaded_union.fieldAlign(ip, field_index);
1903 const field_align = if (explicit_align != .none)
1904 explicit_align
1905 else
1906 Type.fromInterned(field_ty).abiAlignment(pt);
1907 const field_size = Type.fromInterned(field_ty).abiSize(pt);
1908 if (field_size > payload_size) {
1909 payload_size = field_size;
1910 biggest_field = @intCast(field_index);
1911 }
1912 if (field_align.compare(.gte, payload_align)) {
1913 payload_align = field_align;
1914 most_aligned_field = @intCast(field_index);
1915 most_aligned_field_size = field_size;
1916 }
1917 }
1918 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
1919 if (!have_tag or !Type.fromInterned(loaded_union.enum_tag_ty).hasRuntimeBits(pt)) {
1920 return .{
1921 .abi_size = payload_align.forward(payload_size),
1922 .abi_align = payload_align,
1923 .most_aligned_field = most_aligned_field,
1924 .most_aligned_field_size = most_aligned_field_size,
1925 .biggest_field = biggest_field,
1926 .payload_size = payload_size,
1927 .payload_align = payload_align,
1928 .tag_align = .none,
1929 .tag_size = 0,
1930 .padding = 0,
1931 };
1932 }
1933
1934 const tag_size = Type.fromInterned(loaded_union.enum_tag_ty).abiSize(pt);
1935 const tag_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(pt).max(.@"1");
1936 return .{
1937 .abi_size = loaded_union.size(ip).*,
1938 .abi_align = tag_align.max(payload_align),
1939 .most_aligned_field = most_aligned_field,
1940 .most_aligned_field_size = most_aligned_field_size,
1941 .biggest_field = biggest_field,
1942 .payload_size = payload_size,
1943 .payload_align = payload_align,
1944 .tag_align = tag_align,
1945 .tag_size = tag_size,
1946 .padding = loaded_union.padding(ip).*,
1947 };
1948}
1949
1950pub fn unionAbiSize(mod: *Module, loaded_union: InternPool.LoadedUnionType) u64 {
1951 return mod.getUnionLayout(loaded_union).abi_size;
1952}
1953
1954/// Returns 0 if the union is represented with 0 bits at runtime.
1955pub fn unionAbiAlignment(pt: Zcu.PerThread, loaded_union: InternPool.LoadedUnionType) InternPool.Alignment {
1956 const mod = pt.zcu;
1957 const ip = &mod.intern_pool;
1958 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
1959 var max_align: InternPool.Alignment = .none;
1960 if (have_tag) max_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(pt);
1961 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
1962 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
1963
1964 const field_align = mod.unionFieldNormalAlignment(loaded_union, @intCast(field_index));
1965 max_align = max_align.max(field_align);
1966 }
1967 return max_align;
1968}
1969
1970/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
1971pub fn unionFieldNormalAlignment(
1972 pt: Zcu.PerThread,
1973 loaded_union: InternPool.LoadedUnionType,
1974 field_index: u32,
1975) InternPool.Alignment {
1976 return pt.unionFieldNormalAlignmentAdvanced(loaded_union, field_index, .normal) catch unreachable;
1977}
1978
1979/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
1980/// If `strat` is `.sema`, may perform type resolution.
1981pub fn unionFieldNormalAlignmentAdvanced(
1982 pt: Zcu.PerThread,
1983 loaded_union: InternPool.LoadedUnionType,
1984 field_index: u32,
1985 strat: Type.ResolveStrat,
1986) Zcu.SemaError!InternPool.Alignment {
1987 const ip = &pt.zcu.intern_pool;
1988 assert(loaded_union.flagsPtr(ip).layout != .@"packed");
1989 const field_align = loaded_union.fieldAlign(ip, field_index);
1990 if (field_align != .none) return field_align;
1991 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
1992 if (field_ty.isNoReturn(pt.zcu)) return .none;
1993 return (try field_ty.abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
1994}
1995
1996/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
1997pub fn structFieldAlignment(
1998 pt: Zcu.PerThread,
1999 explicit_alignment: InternPool.Alignment,
2000 field_ty: Type,
2001 layout: std.builtin.Type.ContainerLayout,
2002) InternPool.Alignment {
2003 return pt.structFieldAlignmentAdvanced(explicit_alignment, field_ty, layout, .normal) catch unreachable;
2004}
2005
2006/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
2007/// If `strat` is `.sema`, may perform type resolution.
2008pub fn structFieldAlignmentAdvanced(
2009 pt: Zcu.PerThread,
2010 explicit_alignment: InternPool.Alignment,
2011 field_ty: Type,
2012 layout: std.builtin.Type.ContainerLayout,
2013 strat: Type.ResolveStrat,
2014) Zcu.SemaError!InternPool.Alignment {
2015 assert(layout != .@"packed");
2016 if (explicit_alignment != .none) return explicit_alignment;
2017 const ty_abi_align = (try field_ty.abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
2018 switch (layout) {
2019 .@"packed" => unreachable,
2020 .auto => if (pt.zcu.getTarget().ofmt != .c) return ty_abi_align,
2021 .@"extern" => {},
2022 }
2023 // extern
2024 if (field_ty.isAbiInt(pt.zcu) and field_ty.intInfo(pt.zcu).bits >= 128) {
2025 return ty_abi_align.maxStrict(.@"16");
2026 }
2027 return ty_abi_align;
2028}
2029
2030/// https://github.com/ziglang/zig/issues/17178 explored storing these bit offsets
2031/// into the packed struct InternPool data rather than computing this on the
2032/// fly, however it was found to perform worse when measured on real world
2033/// projects.
2034pub fn structPackedFieldBitOffset(
2035 pt: Zcu.PerThread,
2036 struct_type: InternPool.LoadedStructType,
2037 field_index: u32,
2038) u16 {
2039 const mod = pt.zcu;
2040 const ip = &mod.intern_pool;
2041 assert(struct_type.layout == .@"packed");
2042 assert(struct_type.haveLayout(ip));
2043 var bit_sum: u64 = 0;
2044 for (0..struct_type.field_types.len) |i| {
2045 if (i == field_index) {
2046 return @intCast(bit_sum);
2047 }
2048 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
2049 bit_sum += field_ty.bitSize(pt);
2050 }
2051 unreachable; // index out of bounds
2052}
2053
2054pub fn getBuiltin(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Air.Inst.Ref {
2055 const decl_index = try pt.getBuiltinDecl(name);
2056 pt.ensureDeclAnalyzed(decl_index) catch @panic("std.builtin is corrupt");
2057 return Air.internedToRef(pt.zcu.declPtr(decl_index).val.toIntern());
2058}
2059
2060pub fn getBuiltinDecl(pt: Zcu.PerThread, name: []const u8) Allocator.Error!InternPool.DeclIndex {
2061 const zcu = pt.zcu;
2062 const gpa = zcu.gpa;
2063 const ip = &zcu.intern_pool;
2064 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
2065 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index).unwrap().?;
2066 const std_namespace = zcu.declPtr(std_file_root_decl).getOwnedInnerNamespace(zcu).?;
2067 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
2068 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
2069 pt.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");
2070 const builtin_namespace = zcu.declPtr(builtin_decl).getInnerNamespace(zcu) orelse @panic("std.builtin is corrupt");
2071 const name_str = try ip.getOrPutString(gpa, name, .no_embedded_nulls);
2072 return builtin_namespace.decls.getKeyAdapted(name_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std/builtin.zig is corrupt");
2073}
2074
2075pub fn getBuiltinType(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Type {
2076 const ty_inst = try pt.getBuiltin(name);
2077 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
2078 ty.resolveFully(pt) catch @panic("std.builtin is corrupt");
2079 return ty;
2080}
2081
2082const Air = @import("../Air.zig");
2083const Allocator = std.mem.Allocator;
2084const assert = std.debug.assert;
2085const BigIntConst = std.math.big.int.Const;
2086const BigIntMutable = std.math.big.int.Mutable;
2087const build_options = @import("build_options");
2088const builtin = @import("builtin");
2089const Cache = std.Build.Cache;
2090const InternPool = @import("../InternPool.zig");
2091const isUpDir = @import("../introspect.zig").isUpDir;
2092const Liveness = @import("../Liveness.zig");
2093const log = std.log.scoped(.zcu);
2094const Module = @import("../Package.zig").Module;
2095const Sema = @import("../Sema.zig");
2096const std = @import("std");
2097const target_util = @import("../target.zig");
2098const trace = @import("../tracy.zig").trace;
2099const Type = @import("../Type.zig");
2100const Value = @import("../Value.zig");
2101const Zcu = @import("../Zcu.zig");
2102const Zir = std.zig.Zir;
src/arch/aarch64/CodeGen.zig+220-163
......@@ -12,11 +12,9 @@ const Type = @import("../../Type.zig");
1212const Value = @import("../../Value.zig");
1313const link = @import("../../link.zig");
1414const Zcu = @import("../../Zcu.zig");
15/// Deprecated.
16const Module = Zcu;
1715const InternPool = @import("../../InternPool.zig");
1816const Compilation = @import("../../Compilation.zig");
19const ErrorMsg = Module.ErrorMsg;
17const ErrorMsg = Zcu.ErrorMsg;
2018const Target = std.Target;
2119const Allocator = mem.Allocator;
2220const trace = @import("../../tracy.zig").trace;
......@@ -47,6 +45,7 @@ const gp = abi.RegisterClass.gp;
4745const InnerError = CodeGenError || error{OutOfRegisters};
4846
4947gpa: Allocator,
48pt: Zcu.PerThread,
5049air: Air,
5150liveness: Liveness,
5251bin_file: *link.File,
......@@ -59,7 +58,7 @@ args: []MCValue,
5958ret_mcv: MCValue,
6059fn_type: Type,
6160arg_index: u32,
62src_loc: Module.LazySrcLoc,
61src_loc: Zcu.LazySrcLoc,
6362stack_align: u32,
6463
6564/// MIR Instructions
......@@ -331,15 +330,16 @@ const Self = @This();
331330
332331pub fn generate(
333332 lf: *link.File,
334 src_loc: Module.LazySrcLoc,
333 pt: Zcu.PerThread,
334 src_loc: Zcu.LazySrcLoc,
335335 func_index: InternPool.Index,
336336 air: Air,
337337 liveness: Liveness,
338338 code: *std.ArrayList(u8),
339339 debug_output: DebugInfoOutput,
340340) CodeGenError!Result {
341 const gpa = lf.comp.gpa;
342 const zcu = lf.comp.module.?;
341 const zcu = pt.zcu;
342 const gpa = zcu.gpa;
343343 const func = zcu.funcInfo(func_index);
344344 const fn_owner_decl = zcu.declPtr(func.owner_decl);
345345 assert(fn_owner_decl.has_tv);
......@@ -355,8 +355,9 @@ pub fn generate(
355355 }
356356 try branch_stack.append(.{});
357357
358 var function = Self{
358 var function: Self = .{
359359 .gpa = gpa,
360 .pt = pt,
360361 .air = air,
361362 .liveness = liveness,
362363 .debug_output = debug_output,
......@@ -476,7 +477,8 @@ pub fn addExtraAssumeCapacity(self: *Self, extra: anytype) u32 {
476477}
477478
478479fn gen(self: *Self) !void {
479 const mod = self.bin_file.comp.module.?;
480 const pt = self.pt;
481 const mod = pt.zcu;
480482 const cc = self.fn_type.fnCallingConvention(mod);
481483 if (cc != .Naked) {
482484 // stp fp, lr, [sp, #-16]!
......@@ -526,8 +528,8 @@ fn gen(self: *Self) !void {
526528
527529 const ty = self.typeOfIndex(inst);
528530
529 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
530 const abi_align = ty.abiAlignment(mod);
531 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
532 const abi_align = ty.abiAlignment(pt);
531533 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
532534 try self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
533535
......@@ -656,7 +658,8 @@ fn gen(self: *Self) !void {
656658}
657659
658660fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
659 const mod = self.bin_file.comp.module.?;
661 const pt = self.pt;
662 const mod = pt.zcu;
660663 const ip = &mod.intern_pool;
661664 const air_tags = self.air.instructions.items(.tag);
662665
......@@ -1022,31 +1025,32 @@ fn allocMem(
10221025
10231026/// Use a pointer instruction as the basis for allocating stack memory.
10241027fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
1025 const mod = self.bin_file.comp.module.?;
1028 const pt = self.pt;
1029 const mod = pt.zcu;
10261030 const elem_ty = self.typeOfIndex(inst).childType(mod);
10271031
1028 if (!elem_ty.hasRuntimeBits(mod)) {
1032 if (!elem_ty.hasRuntimeBits(pt)) {
10291033 // return the stack offset 0. Stack offset 0 will be where all
10301034 // zero-sized stack allocations live as non-zero-sized
10311035 // allocations will always have an offset > 0.
10321036 return @as(u32, 0);
10331037 }
10341038
1035 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1036 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1039 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1040 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10371041 };
10381042 // TODO swap this for inst.ty.ptrAlign
1039 const abi_align = elem_ty.abiAlignment(mod);
1043 const abi_align = elem_ty.abiAlignment(pt);
10401044
10411045 return self.allocMem(abi_size, abi_align, inst);
10421046}
10431047
10441048fn allocRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool, maybe_inst: ?Air.Inst.Index) !MCValue {
1045 const mod = self.bin_file.comp.module.?;
1046 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1047 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1049 const pt = self.pt;
1050 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1051 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10481052 };
1049 const abi_align = elem_ty.abiAlignment(mod);
1053 const abi_align = elem_ty.abiAlignment(pt);
10501054
10511055 if (reg_ok) {
10521056 // Make sure the type can fit in a register before we try to allocate one.
......@@ -1133,14 +1137,15 @@ fn airAlloc(self: *Self, inst: Air.Inst.Index) !void {
11331137}
11341138
11351139fn airRetPtr(self: *Self, inst: Air.Inst.Index) !void {
1136 const mod = self.bin_file.comp.module.?;
1140 const pt = self.pt;
1141 const mod = pt.zcu;
11371142 const result: MCValue = switch (self.ret_mcv) {
11381143 .none, .register => .{ .ptr_stack_offset = try self.allocMemPtr(inst) },
11391144 .stack_offset => blk: {
11401145 // self.ret_mcv is an address to where this function
11411146 // should store its result into
11421147 const ret_ty = self.fn_type.fnReturnType(mod);
1143 const ptr_ty = try mod.singleMutPtrType(ret_ty);
1148 const ptr_ty = try pt.singleMutPtrType(ret_ty);
11441149
11451150 // addr_reg will contain the address of where to store the
11461151 // result into
......@@ -1170,7 +1175,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
11701175 if (self.liveness.isUnused(inst))
11711176 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
11721177
1173 const mod = self.bin_file.comp.module.?;
1178 const pt = self.pt;
1179 const mod = pt.zcu;
11741180 const operand = ty_op.operand;
11751181 const operand_mcv = try self.resolveInst(operand);
11761182 const operand_ty = self.typeOf(operand);
......@@ -1251,7 +1257,8 @@ fn trunc(
12511257 operand_ty: Type,
12521258 dest_ty: Type,
12531259) !MCValue {
1254 const mod = self.bin_file.comp.module.?;
1260 const pt = self.pt;
1261 const mod = pt.zcu;
12551262 const info_a = operand_ty.intInfo(mod);
12561263 const info_b = dest_ty.intInfo(mod);
12571264
......@@ -1314,7 +1321,8 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
13141321
13151322fn airNot(self: *Self, inst: Air.Inst.Index) !void {
13161323 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1317 const mod = self.bin_file.comp.module.?;
1324 const pt = self.pt;
1325 const mod = pt.zcu;
13181326 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
13191327 const operand = try self.resolveInst(ty_op.operand);
13201328 const operand_ty = self.typeOf(ty_op.operand);
......@@ -1409,7 +1417,8 @@ fn minMax(
14091417 rhs_ty: Type,
14101418 maybe_inst: ?Air.Inst.Index,
14111419) !MCValue {
1412 const mod = self.bin_file.comp.module.?;
1420 const pt = self.pt;
1421 const mod = pt.zcu;
14131422 switch (lhs_ty.zigTypeTag(mod)) {
14141423 .Float => return self.fail("TODO ARM min/max on floats", .{}),
14151424 .Vector => return self.fail("TODO ARM min/max on vectors", .{}),
......@@ -1899,7 +1908,8 @@ fn addSub(
18991908 rhs_ty: Type,
19001909 maybe_inst: ?Air.Inst.Index,
19011910) InnerError!MCValue {
1902 const mod = self.bin_file.comp.module.?;
1911 const pt = self.pt;
1912 const mod = pt.zcu;
19031913 switch (lhs_ty.zigTypeTag(mod)) {
19041914 .Float => return self.fail("TODO binary operations on floats", .{}),
19051915 .Vector => return self.fail("TODO binary operations on vectors", .{}),
......@@ -1960,7 +1970,8 @@ fn mul(
19601970 rhs_ty: Type,
19611971 maybe_inst: ?Air.Inst.Index,
19621972) InnerError!MCValue {
1963 const mod = self.bin_file.comp.module.?;
1973 const pt = self.pt;
1974 const mod = pt.zcu;
19641975 switch (lhs_ty.zigTypeTag(mod)) {
19651976 .Vector => return self.fail("TODO binary operations on vectors", .{}),
19661977 .Int => {
......@@ -1992,7 +2003,8 @@ fn divFloat(
19922003 _ = rhs_ty;
19932004 _ = maybe_inst;
19942005
1995 const mod = self.bin_file.comp.module.?;
2006 const pt = self.pt;
2007 const mod = pt.zcu;
19962008 switch (lhs_ty.zigTypeTag(mod)) {
19972009 .Float => return self.fail("TODO div_float", .{}),
19982010 .Vector => return self.fail("TODO div_float on vectors", .{}),
......@@ -2008,7 +2020,8 @@ fn divTrunc(
20082020 rhs_ty: Type,
20092021 maybe_inst: ?Air.Inst.Index,
20102022) InnerError!MCValue {
2011 const mod = self.bin_file.comp.module.?;
2023 const pt = self.pt;
2024 const mod = pt.zcu;
20122025 switch (lhs_ty.zigTypeTag(mod)) {
20132026 .Float => return self.fail("TODO div on floats", .{}),
20142027 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2042,7 +2055,8 @@ fn divFloor(
20422055 rhs_ty: Type,
20432056 maybe_inst: ?Air.Inst.Index,
20442057) InnerError!MCValue {
2045 const mod = self.bin_file.comp.module.?;
2058 const pt = self.pt;
2059 const mod = pt.zcu;
20462060 switch (lhs_ty.zigTypeTag(mod)) {
20472061 .Float => return self.fail("TODO div on floats", .{}),
20482062 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2075,7 +2089,8 @@ fn divExact(
20752089 rhs_ty: Type,
20762090 maybe_inst: ?Air.Inst.Index,
20772091) InnerError!MCValue {
2078 const mod = self.bin_file.comp.module.?;
2092 const pt = self.pt;
2093 const mod = pt.zcu;
20792094 switch (lhs_ty.zigTypeTag(mod)) {
20802095 .Float => return self.fail("TODO div on floats", .{}),
20812096 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2111,7 +2126,8 @@ fn rem(
21112126) InnerError!MCValue {
21122127 _ = maybe_inst;
21132128
2114 const mod = self.bin_file.comp.module.?;
2129 const pt = self.pt;
2130 const mod = pt.zcu;
21152131 switch (lhs_ty.zigTypeTag(mod)) {
21162132 .Float => return self.fail("TODO rem/mod on floats", .{}),
21172133 .Vector => return self.fail("TODO rem/mod on vectors", .{}),
......@@ -2182,7 +2198,8 @@ fn modulo(
21822198 _ = rhs_ty;
21832199 _ = maybe_inst;
21842200
2185 const mod = self.bin_file.comp.module.?;
2201 const pt = self.pt;
2202 const mod = pt.zcu;
21862203 switch (lhs_ty.zigTypeTag(mod)) {
21872204 .Float => return self.fail("TODO mod on floats", .{}),
21882205 .Vector => return self.fail("TODO mod on vectors", .{}),
......@@ -2200,7 +2217,8 @@ fn wrappingArithmetic(
22002217 rhs_ty: Type,
22012218 maybe_inst: ?Air.Inst.Index,
22022219) InnerError!MCValue {
2203 const mod = self.bin_file.comp.module.?;
2220 const pt = self.pt;
2221 const mod = pt.zcu;
22042222 switch (lhs_ty.zigTypeTag(mod)) {
22052223 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22062224 .Int => {
......@@ -2235,7 +2253,8 @@ fn bitwise(
22352253 rhs_ty: Type,
22362254 maybe_inst: ?Air.Inst.Index,
22372255) InnerError!MCValue {
2238 const mod = self.bin_file.comp.module.?;
2256 const pt = self.pt;
2257 const mod = pt.zcu;
22392258 switch (lhs_ty.zigTypeTag(mod)) {
22402259 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22412260 .Int => {
......@@ -2270,7 +2289,8 @@ fn shiftExact(
22702289) InnerError!MCValue {
22712290 _ = rhs_ty;
22722291
2273 const mod = self.bin_file.comp.module.?;
2292 const pt = self.pt;
2293 const mod = pt.zcu;
22742294 switch (lhs_ty.zigTypeTag(mod)) {
22752295 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22762296 .Int => {
......@@ -2320,7 +2340,8 @@ fn shiftNormal(
23202340 rhs_ty: Type,
23212341 maybe_inst: ?Air.Inst.Index,
23222342) InnerError!MCValue {
2323 const mod = self.bin_file.comp.module.?;
2343 const pt = self.pt;
2344 const mod = pt.zcu;
23242345 switch (lhs_ty.zigTypeTag(mod)) {
23252346 .Vector => return self.fail("TODO binary operations on vectors", .{}),
23262347 .Int => {
......@@ -2360,7 +2381,8 @@ fn booleanOp(
23602381 rhs_ty: Type,
23612382 maybe_inst: ?Air.Inst.Index,
23622383) InnerError!MCValue {
2363 const mod = self.bin_file.comp.module.?;
2384 const pt = self.pt;
2385 const mod = pt.zcu;
23642386 switch (lhs_ty.zigTypeTag(mod)) {
23652387 .Bool => {
23662388 assert((try lhs_bind.resolveToImmediate(self)) == null); // should have been handled by Sema
......@@ -2387,7 +2409,8 @@ fn ptrArithmetic(
23872409 rhs_ty: Type,
23882410 maybe_inst: ?Air.Inst.Index,
23892411) InnerError!MCValue {
2390 const mod = self.bin_file.comp.module.?;
2412 const pt = self.pt;
2413 const mod = pt.zcu;
23912414 switch (lhs_ty.zigTypeTag(mod)) {
23922415 .Pointer => {
23932416 assert(rhs_ty.eql(Type.usize, mod));
......@@ -2397,7 +2420,7 @@ fn ptrArithmetic(
23972420 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
23982421 else => ptr_ty.childType(mod),
23992422 };
2400 const elem_size = elem_ty.abiSize(mod);
2423 const elem_size = elem_ty.abiSize(pt);
24012424
24022425 const base_tag: Air.Inst.Tag = switch (tag) {
24032426 .ptr_add => .add,
......@@ -2510,7 +2533,8 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
25102533 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
25112534 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
25122535 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2513 const mod = self.bin_file.comp.module.?;
2536 const pt = self.pt;
2537 const mod = pt.zcu;
25142538 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
25152539 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
25162540 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2518,9 +2542,9 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
25182542 const rhs_ty = self.typeOf(extra.rhs);
25192543
25202544 const tuple_ty = self.typeOfIndex(inst);
2521 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2522 const tuple_align = tuple_ty.abiAlignment(mod);
2523 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2545 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2546 const tuple_align = tuple_ty.abiAlignment(pt);
2547 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
25242548
25252549 switch (lhs_ty.zigTypeTag(mod)) {
25262550 .Vector => return self.fail("TODO implement add_with_overflow/sub_with_overflow for vectors", .{}),
......@@ -2638,7 +2662,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
26382662 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
26392663 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
26402664 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
2641 const mod = self.bin_file.comp.module.?;
2665 const pt = self.pt;
2666 const mod = pt.zcu;
26422667 const result: MCValue = result: {
26432668 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
26442669 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2646,9 +2671,9 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
26462671 const rhs_ty = self.typeOf(extra.rhs);
26472672
26482673 const tuple_ty = self.typeOfIndex(inst);
2649 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2650 const tuple_align = tuple_ty.abiAlignment(mod);
2651 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2674 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2675 const tuple_align = tuple_ty.abiAlignment(pt);
2676 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
26522677
26532678 switch (lhs_ty.zigTypeTag(mod)) {
26542679 .Vector => return self.fail("TODO implement mul_with_overflow for vectors", .{}),
......@@ -2862,7 +2887,8 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
28622887 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
28632888 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
28642889 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
2865 const mod = self.bin_file.comp.module.?;
2890 const pt = self.pt;
2891 const mod = pt.zcu;
28662892 const result: MCValue = result: {
28672893 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
28682894 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2870,9 +2896,9 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
28702896 const rhs_ty = self.typeOf(extra.rhs);
28712897
28722898 const tuple_ty = self.typeOfIndex(inst);
2873 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2874 const tuple_align = tuple_ty.abiAlignment(mod);
2875 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2899 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2900 const tuple_align = tuple_ty.abiAlignment(pt);
2901 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
28762902
28772903 switch (lhs_ty.zigTypeTag(mod)) {
28782904 .Vector => return self.fail("TODO implement shl_with_overflow for vectors", .{}),
......@@ -3010,9 +3036,10 @@ fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
30103036}
30113037
30123038fn optionalPayload(self: *Self, inst: Air.Inst.Index, mcv: MCValue, optional_ty: Type) !MCValue {
3013 const mod = self.bin_file.comp.module.?;
3039 const pt = self.pt;
3040 const mod = pt.zcu;
30143041 const payload_ty = optional_ty.optionalChild(mod);
3015 if (!payload_ty.hasRuntimeBits(mod)) return MCValue.none;
3042 if (!payload_ty.hasRuntimeBits(pt)) return MCValue.none;
30163043 if (optional_ty.isPtrLikeOptional(mod)) {
30173044 // TODO should we reuse the operand here?
30183045 const raw_reg = try self.register_manager.allocReg(inst, gp);
......@@ -3054,17 +3081,18 @@ fn errUnionErr(
30543081 error_union_ty: Type,
30553082 maybe_inst: ?Air.Inst.Index,
30563083) !MCValue {
3057 const mod = self.bin_file.comp.module.?;
3084 const pt = self.pt;
3085 const mod = pt.zcu;
30583086 const err_ty = error_union_ty.errorUnionSet(mod);
30593087 const payload_ty = error_union_ty.errorUnionPayload(mod);
30603088 if (err_ty.errorSetIsEmpty(mod)) {
30613089 return MCValue{ .immediate = 0 };
30623090 }
3063 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3091 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
30643092 return try error_union_bind.resolveToMcv(self);
30653093 }
30663094
3067 const err_offset = @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod)));
3095 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
30683096 switch (try error_union_bind.resolveToMcv(self)) {
30693097 .register => {
30703098 var operand_reg: Register = undefined;
......@@ -3086,7 +3114,7 @@ fn errUnionErr(
30863114 );
30873115
30883116 const err_bit_offset = err_offset * 8;
3089 const err_bit_size = @as(u32, @intCast(err_ty.abiSize(mod))) * 8;
3117 const err_bit_size = @as(u32, @intCast(err_ty.abiSize(pt))) * 8;
30903118
30913119 _ = try self.addInst(.{
30923120 .tag = .ubfx, // errors are unsigned integers
......@@ -3134,17 +3162,18 @@ fn errUnionPayload(
31343162 error_union_ty: Type,
31353163 maybe_inst: ?Air.Inst.Index,
31363164) !MCValue {
3137 const mod = self.bin_file.comp.module.?;
3165 const pt = self.pt;
3166 const mod = pt.zcu;
31383167 const err_ty = error_union_ty.errorUnionSet(mod);
31393168 const payload_ty = error_union_ty.errorUnionPayload(mod);
31403169 if (err_ty.errorSetIsEmpty(mod)) {
31413170 return try error_union_bind.resolveToMcv(self);
31423171 }
3143 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3172 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
31443173 return MCValue.none;
31453174 }
31463175
3147 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
3176 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
31483177 switch (try error_union_bind.resolveToMcv(self)) {
31493178 .register => {
31503179 var operand_reg: Register = undefined;
......@@ -3166,7 +3195,7 @@ fn errUnionPayload(
31663195 );
31673196
31683197 const payload_bit_offset = payload_offset * 8;
3169 const payload_bit_size = @as(u32, @intCast(payload_ty.abiSize(mod))) * 8;
3198 const payload_bit_size = @as(u32, @intCast(payload_ty.abiSize(pt))) * 8;
31703199
31713200 _ = try self.addInst(.{
31723201 .tag = if (payload_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -3246,7 +3275,8 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
32463275}
32473276
32483277fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
3249 const mod = self.bin_file.comp.module.?;
3278 const pt = self.pt;
3279 const mod = pt.zcu;
32503280 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32513281
32523282 if (self.liveness.isUnused(inst)) {
......@@ -3255,7 +3285,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32553285
32563286 const result: MCValue = result: {
32573287 const payload_ty = self.typeOf(ty_op.operand);
3258 if (!payload_ty.hasRuntimeBits(mod)) {
3288 if (!payload_ty.hasRuntimeBits(pt)) {
32593289 break :result MCValue{ .immediate = 1 };
32603290 }
32613291
......@@ -3275,9 +3305,9 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32753305 break :result MCValue{ .register = reg };
32763306 }
32773307
3278 const optional_abi_size: u32 = @intCast(optional_ty.abiSize(mod));
3279 const optional_abi_align = optional_ty.abiAlignment(mod);
3280 const offset: u32 = @intCast(payload_ty.abiSize(mod));
3308 const optional_abi_size: u32 = @intCast(optional_ty.abiSize(pt));
3309 const optional_abi_align = optional_ty.abiAlignment(pt);
3310 const offset: u32 = @intCast(payload_ty.abiSize(pt));
32813311
32823312 const stack_offset = try self.allocMem(optional_abi_size, optional_abi_align, inst);
32833313 try self.genSetStack(payload_ty, stack_offset, operand);
......@@ -3291,20 +3321,21 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32913321
32923322/// T to E!T
32933323fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
3294 const mod = self.bin_file.comp.module.?;
3324 const pt = self.pt;
3325 const mod = pt.zcu;
32953326 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32963327 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
32973328 const error_union_ty = ty_op.ty.toType();
32983329 const error_ty = error_union_ty.errorUnionSet(mod);
32993330 const payload_ty = error_union_ty.errorUnionPayload(mod);
33003331 const operand = try self.resolveInst(ty_op.operand);
3301 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
3332 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
33023333
3303 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
3304 const abi_align = error_union_ty.abiAlignment(mod);
3334 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
3335 const abi_align = error_union_ty.abiAlignment(pt);
33053336 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
3306 const payload_off = errUnionPayloadOffset(payload_ty, mod);
3307 const err_off = errUnionErrorOffset(payload_ty, mod);
3337 const payload_off = errUnionPayloadOffset(payload_ty, pt);
3338 const err_off = errUnionErrorOffset(payload_ty, pt);
33083339 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), operand);
33093340 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), .{ .immediate = 0 });
33103341
......@@ -3317,18 +3348,19 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
33173348fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
33183349 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
33193350 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
3320 const mod = self.bin_file.comp.module.?;
3351 const pt = self.pt;
3352 const mod = pt.zcu;
33213353 const error_union_ty = ty_op.ty.toType();
33223354 const error_ty = error_union_ty.errorUnionSet(mod);
33233355 const payload_ty = error_union_ty.errorUnionPayload(mod);
33243356 const operand = try self.resolveInst(ty_op.operand);
3325 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
3357 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
33263358
3327 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
3328 const abi_align = error_union_ty.abiAlignment(mod);
3359 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
3360 const abi_align = error_union_ty.abiAlignment(pt);
33293361 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
3330 const payload_off = errUnionPayloadOffset(payload_ty, mod);
3331 const err_off = errUnionErrorOffset(payload_ty, mod);
3362 const payload_off = errUnionPayloadOffset(payload_ty, pt);
3363 const err_off = errUnionErrorOffset(payload_ty, pt);
33323364 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), operand);
33333365 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), .undef);
33343366
......@@ -3420,7 +3452,8 @@ fn airPtrSlicePtrPtr(self: *Self, inst: Air.Inst.Index) !void {
34203452}
34213453
34223454fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
3423 const mod = self.bin_file.comp.module.?;
3455 const pt = self.pt;
3456 const mod = pt.zcu;
34243457 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34253458 const slice_ty = self.typeOf(bin_op.lhs);
34263459 const result: MCValue = if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -3444,9 +3477,10 @@ fn ptrElemVal(
34443477 ptr_ty: Type,
34453478 maybe_inst: ?Air.Inst.Index,
34463479) !MCValue {
3447 const mod = self.bin_file.comp.module.?;
3480 const pt = self.pt;
3481 const mod = pt.zcu;
34483482 const elem_ty = ptr_ty.childType(mod);
3449 const elem_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
3483 const elem_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
34503484
34513485 // TODO optimize for elem_sizes of 1, 2, 4, 8
34523486 switch (elem_size) {
......@@ -3486,7 +3520,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
34863520}
34873521
34883522fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
3489 const mod = self.bin_file.comp.module.?;
3523 const pt = self.pt;
3524 const mod = pt.zcu;
34903525 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34913526 const ptr_ty = self.typeOf(bin_op.lhs);
34923527 const result: MCValue = if (!ptr_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -3609,9 +3644,10 @@ fn reuseOperand(
36093644}
36103645
36113646fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
3612 const mod = self.bin_file.comp.module.?;
3647 const pt = self.pt;
3648 const mod = pt.zcu;
36133649 const elem_ty = ptr_ty.childType(mod);
3614 const elem_size = elem_ty.abiSize(mod);
3650 const elem_size = elem_ty.abiSize(pt);
36153651
36163652 switch (ptr) {
36173653 .none => unreachable,
......@@ -3857,12 +3893,13 @@ fn genInlineMemsetCode(
38573893}
38583894
38593895fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
3860 const mod = self.bin_file.comp.module.?;
3896 const pt = self.pt;
3897 const mod = pt.zcu;
38613898 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38623899 const elem_ty = self.typeOfIndex(inst);
3863 const elem_size = elem_ty.abiSize(mod);
3900 const elem_size = elem_ty.abiSize(pt);
38643901 const result: MCValue = result: {
3865 if (!elem_ty.hasRuntimeBits(mod))
3902 if (!elem_ty.hasRuntimeBits(pt))
38663903 break :result MCValue.none;
38673904
38683905 const ptr = try self.resolveInst(ty_op.operand);
......@@ -3888,8 +3925,9 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
38883925}
38893926
38903927fn genLdrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type) !void {
3891 const mod = self.bin_file.comp.module.?;
3892 const abi_size = ty.abiSize(mod);
3928 const pt = self.pt;
3929 const mod = pt.zcu;
3930 const abi_size = ty.abiSize(pt);
38933931
38943932 const tag: Mir.Inst.Tag = switch (abi_size) {
38953933 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb_immediate else .ldrb_immediate,
......@@ -3911,8 +3949,8 @@ fn genLdrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type
39113949}
39123950
39133951fn genStrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type) !void {
3914 const mod = self.bin_file.comp.module.?;
3915 const abi_size = ty.abiSize(mod);
3952 const pt = self.pt;
3953 const abi_size = ty.abiSize(pt);
39163954
39173955 const tag: Mir.Inst.Tag = switch (abi_size) {
39183956 1 => .strb_immediate,
......@@ -3933,9 +3971,9 @@ fn genStrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type
39333971}
39343972
39353973fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
3936 const mod = self.bin_file.comp.module.?;
3974 const pt = self.pt;
39373975 log.debug("store: storing {} to {}", .{ value, ptr });
3938 const abi_size = value_ty.abiSize(mod);
3976 const abi_size = value_ty.abiSize(pt);
39393977
39403978 switch (ptr) {
39413979 .none => unreachable,
......@@ -4087,11 +4125,12 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
40874125
40884126fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
40894127 return if (self.liveness.isUnused(inst)) .dead else result: {
4090 const mod = self.bin_file.comp.module.?;
4128 const pt = self.pt;
4129 const mod = pt.zcu;
40914130 const mcv = try self.resolveInst(operand);
40924131 const ptr_ty = self.typeOf(operand);
40934132 const struct_ty = ptr_ty.childType(mod);
4094 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4133 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
40954134 switch (mcv) {
40964135 .ptr_stack_offset => |off| {
40974136 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -4112,11 +4151,12 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
41124151 const operand = extra.struct_operand;
41134152 const index = extra.field_index;
41144153 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
4115 const mod = self.bin_file.comp.module.?;
4154 const pt = self.pt;
4155 const mod = pt.zcu;
41164156 const mcv = try self.resolveInst(operand);
41174157 const struct_ty = self.typeOf(operand);
41184158 const struct_field_ty = struct_ty.structFieldType(index, mod);
4119 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4159 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
41204160
41214161 switch (mcv) {
41224162 .dead, .unreach => unreachable,
......@@ -4162,13 +4202,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
41624202}
41634203
41644204fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
4165 const mod = self.bin_file.comp.module.?;
4205 const pt = self.pt;
4206 const mod = pt.zcu;
41664207 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
41674208 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
41684209 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
41694210 const field_ptr = try self.resolveInst(extra.field_ptr);
41704211 const struct_ty = ty_pl.ty.toType().childType(mod);
4171 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(extra.field_index, mod)));
4212 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(extra.field_index, pt)));
41724213 switch (field_ptr) {
41734214 .ptr_stack_offset => |off| {
41744215 break :result MCValue{ .ptr_stack_offset = off + struct_field_offset };
......@@ -4190,7 +4231,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
41904231 while (self.args[arg_index] == .none) arg_index += 1;
41914232 self.arg_index = arg_index + 1;
41924233
4193 const mod = self.bin_file.comp.module.?;
4234 const pt = self.pt;
4235 const mod = pt.zcu;
41944236 const ty = self.typeOfIndex(inst);
41954237 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
41964238 const src_index = self.air.instructions.items(.data)[@intFromEnum(inst)].arg.src_index;
......@@ -4245,7 +4287,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42454287 const extra = self.air.extraData(Air.Call, pl_op.payload);
42464288 const args = @as([]const Air.Inst.Ref, @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]));
42474289 const ty = self.typeOf(callee);
4248 const mod = self.bin_file.comp.module.?;
4290 const pt = self.pt;
4291 const mod = pt.zcu;
42494292
42504293 const fn_ty = switch (ty.zigTypeTag(mod)) {
42514294 .Fn => ty,
......@@ -4269,13 +4312,13 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42694312 if (info.return_value == .stack_offset) {
42704313 log.debug("airCall: return by reference", .{});
42714314 const ret_ty = fn_ty.fnReturnType(mod);
4272 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4273 const ret_abi_align = ret_ty.abiAlignment(mod);
4315 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4316 const ret_abi_align = ret_ty.abiAlignment(pt);
42744317 const stack_offset = try self.allocMem(ret_abi_size, ret_abi_align, inst);
42754318
42764319 const ret_ptr_reg = self.registerAlias(.x0, Type.usize);
42774320
4278 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4321 const ptr_ty = try pt.singleMutPtrType(ret_ty);
42794322 try self.register_manager.getReg(ret_ptr_reg, null);
42804323 try self.genSetReg(ptr_ty, ret_ptr_reg, .{ .ptr_stack_offset = stack_offset });
42814324
......@@ -4308,7 +4351,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43084351
43094352 // Due to incremental compilation, how function calls are generated depends
43104353 // on linking.
4311 if (try self.air.value(callee, mod)) |func_value| {
4354 if (try self.air.value(callee, pt)) |func_value| {
43124355 if (func_value.getFunction(mod)) |func| {
43134356 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
43144357 const sym_index = try elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, func.owner_decl);
......@@ -4421,7 +4464,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
44214464}
44224465
44234466fn airRet(self: *Self, inst: Air.Inst.Index) !void {
4424 const mod = self.bin_file.comp.module.?;
4467 const pt = self.pt;
4468 const mod = pt.zcu;
44254469 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44264470 const operand = try self.resolveInst(un_op);
44274471 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -4440,7 +4484,7 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44404484 //
44414485 // self.ret_mcv is an address to where this function
44424486 // should store its result into
4443 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4487 const ptr_ty = try pt.singleMutPtrType(ret_ty);
44444488 try self.store(self.ret_mcv, operand, ptr_ty, ret_ty);
44454489 },
44464490 else => unreachable,
......@@ -4453,7 +4497,8 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44534497}
44544498
44554499fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
4456 const mod = self.bin_file.comp.module.?;
4500 const pt = self.pt;
4501 const mod = pt.zcu;
44574502 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44584503 const ptr = try self.resolveInst(un_op);
44594504 const ptr_ty = self.typeOf(un_op);
......@@ -4477,8 +4522,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
44774522 // location.
44784523 const op_inst = un_op.toIndex().?;
44794524 if (self.air.instructions.items(.tag)[@intFromEnum(op_inst)] != .ret_ptr) {
4480 const abi_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
4481 const abi_align = ret_ty.abiAlignment(mod);
4525 const abi_size = @as(u32, @intCast(ret_ty.abiSize(pt)));
4526 const abi_align = ret_ty.abiAlignment(pt);
44824527
44834528 const offset = try self.allocMem(abi_size, abi_align, null);
44844529
......@@ -4513,11 +4558,12 @@ fn cmp(
45134558 lhs_ty: Type,
45144559 op: math.CompareOperator,
45154560) !MCValue {
4516 const mod = self.bin_file.comp.module.?;
4561 const pt = self.pt;
4562 const mod = pt.zcu;
45174563 const int_ty = switch (lhs_ty.zigTypeTag(mod)) {
45184564 .Optional => blk: {
45194565 const payload_ty = lhs_ty.optionalChild(mod);
4520 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4566 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45214567 break :blk Type.u1;
45224568 } else if (lhs_ty.isPtrLikeOptional(mod)) {
45234569 break :blk Type.usize;
......@@ -4620,7 +4666,8 @@ fn airDbgStmt(self: *Self, inst: Air.Inst.Index) !void {
46204666}
46214667
46224668fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
4623 const mod = self.bin_file.comp.module.?;
4669 const pt = self.pt;
4670 const mod = pt.zcu;
46244671 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46254672 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
46264673 const func = mod.funcInfo(extra.data.func);
......@@ -4825,13 +4872,14 @@ fn airCondBr(self: *Self, inst: Air.Inst.Index) !void {
48254872}
48264873
48274874fn isNull(self: *Self, operand_bind: ReadArg.Bind, operand_ty: Type) !MCValue {
4828 const mod = self.bin_file.comp.module.?;
4875 const pt = self.pt;
4876 const mod = pt.zcu;
48294877 const sentinel: struct { ty: Type, bind: ReadArg.Bind } = if (!operand_ty.isPtrLikeOptional(mod)) blk: {
48304878 const payload_ty = operand_ty.optionalChild(mod);
4831 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4879 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt))
48324880 break :blk .{ .ty = operand_ty, .bind = operand_bind };
48334881
4834 const offset = @as(u32, @intCast(payload_ty.abiSize(mod)));
4882 const offset = @as(u32, @intCast(payload_ty.abiSize(pt)));
48354883 const operand_mcv = try operand_bind.resolveToMcv(self);
48364884 const new_mcv: MCValue = switch (operand_mcv) {
48374885 .register => |source_reg| new: {
......@@ -4881,7 +4929,8 @@ fn isErr(
48814929 error_union_bind: ReadArg.Bind,
48824930 error_union_ty: Type,
48834931) !MCValue {
4884 const mod = self.bin_file.comp.module.?;
4932 const pt = self.pt;
4933 const mod = pt.zcu;
48854934 const error_type = error_union_ty.errorUnionSet(mod);
48864935
48874936 if (error_type.errorSetIsEmpty(mod)) {
......@@ -4923,7 +4972,8 @@ fn airIsNull(self: *Self, inst: Air.Inst.Index) !void {
49234972}
49244973
49254974fn airIsNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4926 const mod = self.bin_file.comp.module.?;
4975 const pt = self.pt;
4976 const mod = pt.zcu;
49274977 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49284978 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49294979 const operand_ptr = try self.resolveInst(un_op);
......@@ -4950,7 +5000,8 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
49505000}
49515001
49525002fn airIsNonNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4953 const mod = self.bin_file.comp.module.?;
5003 const pt = self.pt;
5004 const mod = pt.zcu;
49545005 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49555006 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49565007 const operand_ptr = try self.resolveInst(un_op);
......@@ -4977,7 +5028,8 @@ fn airIsErr(self: *Self, inst: Air.Inst.Index) !void {
49775028}
49785029
49795030fn airIsErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4980 const mod = self.bin_file.comp.module.?;
5031 const pt = self.pt;
5032 const mod = pt.zcu;
49815033 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49825034 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49835035 const operand_ptr = try self.resolveInst(un_op);
......@@ -5004,7 +5056,8 @@ fn airIsNonErr(self: *Self, inst: Air.Inst.Index) !void {
50045056}
50055057
50065058fn airIsNonErrPtr(self: *Self, inst: Air.Inst.Index) !void {
5007 const mod = self.bin_file.comp.module.?;
5059 const pt = self.pt;
5060 const mod = pt.zcu;
50085061 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
50095062 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
50105063 const operand_ptr = try self.resolveInst(un_op);
......@@ -5225,10 +5278,10 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
52255278}
52265279
52275280fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
5228 const mod = self.bin_file.comp.module.?;
5281 const pt = self.pt;
52295282 const block_data = self.blocks.getPtr(block).?;
52305283
5231 if (self.typeOf(operand).hasRuntimeBits(mod)) {
5284 if (self.typeOf(operand).hasRuntimeBits(pt)) {
52325285 const operand_mcv = try self.resolveInst(operand);
52335286 const block_mcv = block_data.mcv;
52345287 if (block_mcv == .none) {
......@@ -5402,8 +5455,9 @@ fn setRegOrMem(self: *Self, ty: Type, loc: MCValue, val: MCValue) !void {
54025455}
54035456
54045457fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5405 const mod = self.bin_file.comp.module.?;
5406 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
5458 const pt = self.pt;
5459 const mod = pt.zcu;
5460 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
54075461 switch (mcv) {
54085462 .dead => unreachable,
54095463 .unreach, .none => return, // Nothing to do.
......@@ -5462,7 +5516,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54625516 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = rwo.reg });
54635517
54645518 const overflow_bit_ty = ty.structFieldType(1, mod);
5465 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, mod)));
5519 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, pt)));
54665520 const raw_cond_reg = try self.register_manager.allocReg(null, gp);
54675521 const cond_reg = self.registerAlias(raw_cond_reg, overflow_bit_ty);
54685522
......@@ -5495,7 +5549,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54955549 const reg = try self.copyToTmpRegister(ty, mcv);
54965550 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
54975551 } else {
5498 const ptr_ty = try mod.singleMutPtrType(ty);
5552 const ptr_ty = try pt.singleMutPtrType(ty);
54995553
55005554 // TODO call extern memcpy
55015555 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5573,7 +5627,8 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
55735627}
55745628
55755629fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
5576 const mod = self.bin_file.comp.module.?;
5630 const pt = self.pt;
5631 const mod = pt.zcu;
55775632 switch (mcv) {
55785633 .dead => unreachable,
55795634 .unreach, .none => return, // Nothing to do.
......@@ -5685,7 +5740,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
56855740 try self.genLdrRegister(reg, reg.toX(), ty);
56865741 },
56875742 .stack_offset => |off| {
5688 const abi_size = ty.abiSize(mod);
5743 const abi_size = ty.abiSize(pt);
56895744
56905745 switch (abi_size) {
56915746 1, 2, 4, 8 => {
......@@ -5709,7 +5764,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57095764 }
57105765 },
57115766 .stack_argument_offset => |off| {
5712 const abi_size = ty.abiSize(mod);
5767 const abi_size = ty.abiSize(pt);
57135768
57145769 switch (abi_size) {
57155770 1, 2, 4, 8 => {
......@@ -5736,8 +5791,8 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57365791}
57375792
57385793fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5739 const mod = self.bin_file.comp.module.?;
5740 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
5794 const pt = self.pt;
5795 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
57415796 switch (mcv) {
57425797 .dead => unreachable,
57435798 .none, .unreach => return,
......@@ -5745,7 +5800,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
57455800 if (!self.wantSafety())
57465801 return; // The already existing value will do just fine.
57475802 // TODO Upgrade this to a memset call when we have that available.
5748 switch (ty.abiSize(mod)) {
5803 switch (ty.abiSize(pt)) {
57495804 1 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaa }),
57505805 2 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaa }),
57515806 4 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaaaaaa }),
......@@ -5815,7 +5870,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
58155870 const reg = try self.copyToTmpRegister(ty, mcv);
58165871 return self.genSetStackArgument(ty, stack_offset, MCValue{ .register = reg });
58175872 } else {
5818 const ptr_ty = try mod.singleMutPtrType(ty);
5873 const ptr_ty = try pt.singleMutPtrType(ty);
58195874
58205875 // TODO call extern memcpy
58215876 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5936,7 +5991,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
59365991}
59375992
59385993fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
5939 const mod = self.bin_file.comp.module.?;
5994 const pt = self.pt;
5995 const mod = pt.zcu;
59405996 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59415997 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
59425998 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -6056,7 +6112,8 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
60566112}
60576113
60586114fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
6059 const mod = self.bin_file.comp.module.?;
6115 const pt = self.pt;
6116 const mod = pt.zcu;
60606117 const vector_ty = self.typeOfIndex(inst);
60616118 const len = vector_ty.vectorLen(mod);
60626119 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6100,15 +6157,15 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
61006157}
61016158
61026159fn airTry(self: *Self, inst: Air.Inst.Index) !void {
6103 const mod = self.bin_file.comp.module.?;
6160 const pt = self.pt;
61046161 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
61056162 const extra = self.air.extraData(Air.Try, pl_op.payload);
61066163 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
61076164 const result: MCValue = result: {
61086165 const error_union_bind: ReadArg.Bind = .{ .inst = pl_op.operand };
61096166 const error_union_ty = self.typeOf(pl_op.operand);
6110 const error_union_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
6111 const error_union_align = error_union_ty.abiAlignment(mod);
6167 const error_union_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
6168 const error_union_align = error_union_ty.abiAlignment(pt);
61126169
61136170 // The error union will die in the body. However, we need the
61146171 // error union after the body in order to extract the payload
......@@ -6137,14 +6194,15 @@ fn airTryPtr(self: *Self, inst: Air.Inst.Index) !void {
61376194}
61386195
61396196fn resolveInst(self: *Self, inst: Air.Inst.Ref) InnerError!MCValue {
6140 const mod = self.bin_file.comp.module.?;
6197 const pt = self.pt;
6198 const mod = pt.zcu;
61416199
61426200 // If the type has no codegen bits, no need to store it.
61436201 const inst_ty = self.typeOf(inst);
6144 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod) and !inst_ty.isError(mod))
6202 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !inst_ty.isError(mod))
61456203 return MCValue{ .none = {} };
61466204
6147 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, mod)).?);
6205 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, pt)).?);
61486206
61496207 return self.getResolvedInstValue(inst_index);
61506208}
......@@ -6164,6 +6222,7 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
61646222fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
61656223 const mcv: MCValue = switch (try codegen.genTypedValue(
61666224 self.bin_file,
6225 self.pt,
61676226 self.src_loc,
61686227 val,
61696228 self.owner_decl,
......@@ -6199,7 +6258,8 @@ const CallMCValues = struct {
61996258
62006259/// Caller must call `CallMCValues.deinit`.
62016260fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
6202 const mod = self.bin_file.comp.module.?;
6261 const pt = self.pt;
6262 const mod = pt.zcu;
62036263 const ip = &mod.intern_pool;
62046264 const fn_info = mod.typeToFunc(fn_ty).?;
62056265 const cc = fn_info.cc;
......@@ -6229,10 +6289,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62296289
62306290 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62316291 result.return_value = .{ .unreach = {} };
6232 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6292 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62336293 result.return_value = .{ .none = {} };
62346294 } else {
6235 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
6295 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
62366296 if (ret_ty_size == 0) {
62376297 assert(ret_ty.isError(mod));
62386298 result.return_value = .{ .immediate = 0 };
......@@ -6244,7 +6304,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62446304 }
62456305
62466306 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6247 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(mod)));
6307 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(pt)));
62486308 if (param_size == 0) {
62496309 result_arg.* = .{ .none = {} };
62506310 continue;
......@@ -6252,7 +6312,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62526312
62536313 // We round up NCRN only for non-Apple platforms which allow the 16-byte aligned
62546314 // values to spread across odd-numbered registers.
6255 if (Type.fromInterned(ty).abiAlignment(mod) == .@"16" and !self.target.isDarwin()) {
6315 if (Type.fromInterned(ty).abiAlignment(pt) == .@"16" and !self.target.isDarwin()) {
62566316 // Round up NCRN to the next even number
62576317 ncrn += ncrn % 2;
62586318 }
......@@ -6270,7 +6330,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62706330 ncrn = 8;
62716331 // TODO Apple allows the arguments on the stack to be non-8-byte aligned provided
62726332 // that the entire stack space consumed by the arguments is 8-byte aligned.
6273 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8") {
6333 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8") {
62746334 if (nsaa % 8 != 0) {
62756335 nsaa += 8 - (nsaa % 8);
62766336 }
......@@ -6287,10 +6347,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62876347 .Unspecified => {
62886348 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62896349 result.return_value = .{ .unreach = {} };
6290 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6350 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62916351 result.return_value = .{ .none = {} };
62926352 } else {
6293 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
6353 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(pt)));
62946354 if (ret_ty_size == 0) {
62956355 assert(ret_ty.isError(mod));
62966356 result.return_value = .{ .immediate = 0 };
......@@ -6309,9 +6369,9 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
63096369 var stack_offset: u32 = 0;
63106370
63116371 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6312 if (Type.fromInterned(ty).abiSize(mod) > 0) {
6313 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6314 const param_alignment = Type.fromInterned(ty).abiAlignment(mod);
6372 if (Type.fromInterned(ty).abiSize(pt) > 0) {
6373 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
6374 const param_alignment = Type.fromInterned(ty).abiAlignment(pt);
63156375
63166376 stack_offset = @intCast(param_alignment.forward(stack_offset));
63176377 result_arg.* = .{ .stack_argument_offset = stack_offset };
......@@ -6330,7 +6390,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
63306390 return result;
63316391}
63326392
6333/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
6393/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
63346394fn wantSafety(self: *Self) bool {
63356395 return switch (self.bin_file.comp.root_mod.optimize_mode) {
63366396 .Debug => true,
......@@ -6362,8 +6422,7 @@ fn parseRegName(name: []const u8) ?Register {
63626422}
63636423
63646424fn registerAlias(self: *Self, reg: Register, ty: Type) Register {
6365 const mod = self.bin_file.comp.module.?;
6366 const abi_size = ty.abiSize(mod);
6425 const abi_size = ty.abiSize(self.pt);
63676426
63686427 switch (reg.class()) {
63696428 .general_purpose => {
......@@ -6391,11 +6450,9 @@ fn registerAlias(self: *Self, reg: Register, ty: Type) Register {
63916450}
63926451
63936452fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
6394 const mod = self.bin_file.comp.module.?;
6395 return self.air.typeOf(inst, &mod.intern_pool);
6453 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
63966454}
63976455
63986456fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
6399 const mod = self.bin_file.comp.module.?;
6400 return self.air.typeOfIndex(inst, &mod.intern_pool);
6457 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
64016458}
src/arch/aarch64/Emit.zig+2-4
......@@ -8,9 +8,7 @@ const Mir = @import("Mir.zig");
88const bits = @import("bits.zig");
99const link = @import("../../link.zig");
1010const Zcu = @import("../../Zcu.zig");
11/// Deprecated.
12const Module = Zcu;
13const ErrorMsg = Module.ErrorMsg;
11const ErrorMsg = Zcu.ErrorMsg;
1412const assert = std.debug.assert;
1513const Instruction = bits.Instruction;
1614const Register = bits.Register;
......@@ -22,7 +20,7 @@ bin_file: *link.File,
2220debug_output: DebugInfoOutput,
2321target: *const std.Target,
2422err_msg: ?*ErrorMsg = null,
25src_loc: Module.LazySrcLoc,
23src_loc: Zcu.LazySrcLoc,
2624code: *std.ArrayList(u8),
2725
2826prev_di_line: u32,
src/arch/aarch64/abi.zig+29-31
......@@ -5,8 +5,6 @@ const Register = bits.Register;
55const RegisterManagerFn = @import("../../register_manager.zig").RegisterManager;
66const Type = @import("../../Type.zig");
77const Zcu = @import("../../Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108
119pub const Class = union(enum) {
1210 memory,
......@@ -17,44 +15,44 @@ pub const Class = union(enum) {
1715};
1816
1917/// For `float_array` the second element will be the amount of floats.
20pub fn classifyType(ty: Type, mod: *Module) Class {
21 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(mod));
18pub fn classifyType(ty: Type, pt: Zcu.PerThread) Class {
19 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(pt));
2220
2321 var maybe_float_bits: ?u16 = null;
24 switch (ty.zigTypeTag(mod)) {
22 switch (ty.zigTypeTag(pt.zcu)) {
2523 .Struct => {
26 if (ty.containerLayout(mod) == .@"packed") return .byval;
27 const float_count = countFloats(ty, mod, &maybe_float_bits);
24 if (ty.containerLayout(pt.zcu) == .@"packed") return .byval;
25 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
2826 if (float_count <= sret_float_count) return .{ .float_array = float_count };
2927
30 const bit_size = ty.bitSize(mod);
28 const bit_size = ty.bitSize(pt);
3129 if (bit_size > 128) return .memory;
3230 if (bit_size > 64) return .double_integer;
3331 return .integer;
3432 },
3533 .Union => {
36 if (ty.containerLayout(mod) == .@"packed") return .byval;
37 const float_count = countFloats(ty, mod, &maybe_float_bits);
34 if (ty.containerLayout(pt.zcu) == .@"packed") return .byval;
35 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
3836 if (float_count <= sret_float_count) return .{ .float_array = float_count };
3937
40 const bit_size = ty.bitSize(mod);
38 const bit_size = ty.bitSize(pt);
4139 if (bit_size > 128) return .memory;
4240 if (bit_size > 64) return .double_integer;
4341 return .integer;
4442 },
4543 .Int, .Enum, .ErrorSet, .Float, .Bool => return .byval,
4644 .Vector => {
47 const bit_size = ty.bitSize(mod);
45 const bit_size = ty.bitSize(pt);
4846 // TODO is this controlled by a cpu feature?
4947 if (bit_size > 128) return .memory;
5048 return .byval;
5149 },
5250 .Optional => {
53 std.debug.assert(ty.isPtrLikeOptional(mod));
51 std.debug.assert(ty.isPtrLikeOptional(pt.zcu));
5452 return .byval;
5553 },
5654 .Pointer => {
57 std.debug.assert(!ty.isSlice(mod));
55 std.debug.assert(!ty.isSlice(pt.zcu));
5856 return .byval;
5957 },
6058 .ErrorUnion,
......@@ -76,16 +74,16 @@ pub fn classifyType(ty: Type, mod: *Module) Class {
7674}
7775
7876const sret_float_count = 4;
79fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
80 const ip = &mod.intern_pool;
81 const target = mod.getTarget();
77fn countFloats(ty: Type, zcu: *Zcu, maybe_float_bits: *?u16) u8 {
78 const ip = &zcu.intern_pool;
79 const target = zcu.getTarget();
8280 const invalid = std.math.maxInt(u8);
83 switch (ty.zigTypeTag(mod)) {
81 switch (ty.zigTypeTag(zcu)) {
8482 .Union => {
85 const union_obj = mod.typeToUnion(ty).?;
83 const union_obj = zcu.typeToUnion(ty).?;
8684 var max_count: u8 = 0;
8785 for (union_obj.field_types.get(ip)) |field_ty| {
88 const field_count = countFloats(Type.fromInterned(field_ty), mod, maybe_float_bits);
86 const field_count = countFloats(Type.fromInterned(field_ty), zcu, maybe_float_bits);
8987 if (field_count == invalid) return invalid;
9088 if (field_count > max_count) max_count = field_count;
9189 if (max_count > sret_float_count) return invalid;
......@@ -93,12 +91,12 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
9391 return max_count;
9492 },
9593 .Struct => {
96 const fields_len = ty.structFieldCount(mod);
94 const fields_len = ty.structFieldCount(zcu);
9795 var count: u8 = 0;
9896 var i: u32 = 0;
9997 while (i < fields_len) : (i += 1) {
100 const field_ty = ty.structFieldType(i, mod);
101 const field_count = countFloats(field_ty, mod, maybe_float_bits);
98 const field_ty = ty.structFieldType(i, zcu);
99 const field_count = countFloats(field_ty, zcu, maybe_float_bits);
102100 if (field_count == invalid) return invalid;
103101 count += field_count;
104102 if (count > sret_float_count) return invalid;
......@@ -118,22 +116,22 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
118116 }
119117}
120118
121pub fn getFloatArrayType(ty: Type, mod: *Module) ?Type {
122 const ip = &mod.intern_pool;
123 switch (ty.zigTypeTag(mod)) {
119pub fn getFloatArrayType(ty: Type, zcu: *Zcu) ?Type {
120 const ip = &zcu.intern_pool;
121 switch (ty.zigTypeTag(zcu)) {
124122 .Union => {
125 const union_obj = mod.typeToUnion(ty).?;
123 const union_obj = zcu.typeToUnion(ty).?;
126124 for (union_obj.field_types.get(ip)) |field_ty| {
127 if (getFloatArrayType(Type.fromInterned(field_ty), mod)) |some| return some;
125 if (getFloatArrayType(Type.fromInterned(field_ty), zcu)) |some| return some;
128126 }
129127 return null;
130128 },
131129 .Struct => {
132 const fields_len = ty.structFieldCount(mod);
130 const fields_len = ty.structFieldCount(zcu);
133131 var i: u32 = 0;
134132 while (i < fields_len) : (i += 1) {
135 const field_ty = ty.structFieldType(i, mod);
136 if (getFloatArrayType(field_ty, mod)) |some| return some;
133 const field_ty = ty.structFieldType(i, zcu);
134 if (getFloatArrayType(field_ty, zcu)) |some| return some;
137135 }
138136 return null;
139137 },
src/arch/arm/CodeGen.zig+219-164
......@@ -12,11 +12,9 @@ const Type = @import("../../Type.zig");
1212const Value = @import("../../Value.zig");
1313const link = @import("../../link.zig");
1414const Zcu = @import("../../Zcu.zig");
15/// Deprecated.
16const Module = Zcu;
1715const InternPool = @import("../../InternPool.zig");
1816const Compilation = @import("../../Compilation.zig");
19const ErrorMsg = Module.ErrorMsg;
17const ErrorMsg = Zcu.ErrorMsg;
2018const Target = std.Target;
2119const Allocator = mem.Allocator;
2220const trace = @import("../../tracy.zig").trace;
......@@ -48,6 +46,7 @@ const gp = abi.RegisterClass.gp;
4846const InnerError = CodeGenError || error{OutOfRegisters};
4947
5048gpa: Allocator,
49pt: Zcu.PerThread,
5150air: Air,
5251liveness: Liveness,
5352bin_file: *link.File,
......@@ -59,7 +58,7 @@ args: []MCValue,
5958ret_mcv: MCValue,
6059fn_type: Type,
6160arg_index: u32,
62src_loc: Module.LazySrcLoc,
61src_loc: Zcu.LazySrcLoc,
6362stack_align: u32,
6463
6564/// MIR Instructions
......@@ -261,7 +260,6 @@ const DbgInfoReloc = struct {
261260 }
262261
263262 fn genArgDbgInfo(reloc: DbgInfoReloc, function: Self) error{OutOfMemory}!void {
264 const mod = function.bin_file.comp.module.?;
265263 switch (function.debug_output) {
266264 .dwarf => |dw| {
267265 const loc: link.File.Dwarf.DeclState.DbgInfoLoc = switch (reloc.mcv) {
......@@ -282,7 +280,7 @@ const DbgInfoReloc = struct {
282280 else => unreachable, // not a possible argument
283281 };
284282
285 try dw.genArgDbgInfo(reloc.name, reloc.ty, mod.funcOwnerDeclIndex(function.func_index), loc);
283 try dw.genArgDbgInfo(reloc.name, reloc.ty, function.pt.zcu.funcOwnerDeclIndex(function.func_index), loc);
286284 },
287285 .plan9 => {},
288286 .none => {},
......@@ -290,7 +288,6 @@ const DbgInfoReloc = struct {
290288 }
291289
292290 fn genVarDbgInfo(reloc: DbgInfoReloc, function: Self) !void {
293 const mod = function.bin_file.comp.module.?;
294291 const is_ptr = switch (reloc.tag) {
295292 .dbg_var_ptr => true,
296293 .dbg_var_val => false,
......@@ -326,7 +323,7 @@ const DbgInfoReloc = struct {
326323 break :blk .nop;
327324 },
328325 };
329 try dw.genVarDbgInfo(reloc.name, reloc.ty, mod.funcOwnerDeclIndex(function.func_index), is_ptr, loc);
326 try dw.genVarDbgInfo(reloc.name, reloc.ty, function.pt.zcu.funcOwnerDeclIndex(function.func_index), is_ptr, loc);
330327 },
331328 .plan9 => {},
332329 .none => {},
......@@ -338,15 +335,16 @@ const Self = @This();
338335
339336pub fn generate(
340337 lf: *link.File,
341 src_loc: Module.LazySrcLoc,
338 pt: Zcu.PerThread,
339 src_loc: Zcu.LazySrcLoc,
342340 func_index: InternPool.Index,
343341 air: Air,
344342 liveness: Liveness,
345343 code: *std.ArrayList(u8),
346344 debug_output: DebugInfoOutput,
347345) CodeGenError!Result {
348 const gpa = lf.comp.gpa;
349 const zcu = lf.comp.module.?;
346 const zcu = pt.zcu;
347 const gpa = zcu.gpa;
350348 const func = zcu.funcInfo(func_index);
351349 const fn_owner_decl = zcu.declPtr(func.owner_decl);
352350 assert(fn_owner_decl.has_tv);
......@@ -364,6 +362,7 @@ pub fn generate(
364362
365363 var function: Self = .{
366364 .gpa = gpa,
365 .pt = pt,
367366 .air = air,
368367 .liveness = liveness,
369368 .target = target,
......@@ -482,7 +481,8 @@ pub fn addExtraAssumeCapacity(self: *Self, extra: anytype) u32 {
482481}
483482
484483fn gen(self: *Self) !void {
485 const mod = self.bin_file.comp.module.?;
484 const pt = self.pt;
485 const mod = pt.zcu;
486486 const cc = self.fn_type.fnCallingConvention(mod);
487487 if (cc != .Naked) {
488488 // push {fp, lr}
......@@ -526,8 +526,8 @@ fn gen(self: *Self) !void {
526526
527527 const ty = self.typeOfIndex(inst);
528528
529 const abi_size: u32 = @intCast(ty.abiSize(mod));
530 const abi_align = ty.abiAlignment(mod);
529 const abi_size: u32 = @intCast(ty.abiSize(pt));
530 const abi_align = ty.abiAlignment(pt);
531531 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
532532 try self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
533533
......@@ -642,7 +642,8 @@ fn gen(self: *Self) !void {
642642}
643643
644644fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
645 const mod = self.bin_file.comp.module.?;
645 const pt = self.pt;
646 const mod = pt.zcu;
646647 const ip = &mod.intern_pool;
647648 const air_tags = self.air.instructions.items(.tag);
648649
......@@ -1004,10 +1005,11 @@ fn allocMem(
10041005
10051006/// Use a pointer instruction as the basis for allocating stack memory.
10061007fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
1007 const mod = self.bin_file.comp.module.?;
1008 const pt = self.pt;
1009 const mod = pt.zcu;
10081010 const elem_ty = self.typeOfIndex(inst).childType(mod);
10091011
1010 if (!elem_ty.hasRuntimeBits(mod)) {
1012 if (!elem_ty.hasRuntimeBits(pt)) {
10111013 // As this stack item will never be dereferenced at runtime,
10121014 // return the stack offset 0. Stack offset 0 will be where all
10131015 // zero-sized stack allocations live as non-zero-sized
......@@ -1015,21 +1017,21 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
10151017 return 0;
10161018 }
10171019
1018 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1019 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1020 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1021 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10201022 };
10211023 // TODO swap this for inst.ty.ptrAlign
1022 const abi_align = elem_ty.abiAlignment(mod);
1024 const abi_align = elem_ty.abiAlignment(pt);
10231025
10241026 return self.allocMem(abi_size, abi_align, inst);
10251027}
10261028
10271029fn allocRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool, maybe_inst: ?Air.Inst.Index) !MCValue {
1028 const mod = self.bin_file.comp.module.?;
1029 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1030 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1030 const pt = self.pt;
1031 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1032 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10311033 };
1032 const abi_align = elem_ty.abiAlignment(mod);
1034 const abi_align = elem_ty.abiAlignment(pt);
10331035
10341036 if (reg_ok) {
10351037 // Make sure the type can fit in a register before we try to allocate one.
......@@ -1112,14 +1114,15 @@ fn airAlloc(self: *Self, inst: Air.Inst.Index) !void {
11121114}
11131115
11141116fn airRetPtr(self: *Self, inst: Air.Inst.Index) !void {
1115 const mod = self.bin_file.comp.module.?;
1117 const pt = self.pt;
1118 const mod = pt.zcu;
11161119 const result: MCValue = switch (self.ret_mcv) {
11171120 .none, .register => .{ .ptr_stack_offset = try self.allocMemPtr(inst) },
11181121 .stack_offset => blk: {
11191122 // self.ret_mcv is an address to where this function
11201123 // should store its result into
11211124 const ret_ty = self.fn_type.fnReturnType(mod);
1122 const ptr_ty = try mod.singleMutPtrType(ret_ty);
1125 const ptr_ty = try pt.singleMutPtrType(ret_ty);
11231126
11241127 // addr_reg will contain the address of where to store the
11251128 // result into
......@@ -1145,7 +1148,8 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
11451148}
11461149
11471150fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
1148 const mod = self.bin_file.comp.module.?;
1151 const pt = self.pt;
1152 const mod = pt.zcu;
11491153 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
11501154 if (self.liveness.isUnused(inst))
11511155 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
......@@ -1154,8 +1158,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
11541158 const operand_ty = self.typeOf(ty_op.operand);
11551159 const dest_ty = self.typeOfIndex(inst);
11561160
1157 const operand_abi_size = operand_ty.abiSize(mod);
1158 const dest_abi_size = dest_ty.abiSize(mod);
1161 const operand_abi_size = operand_ty.abiSize(pt);
1162 const dest_abi_size = dest_ty.abiSize(pt);
11591163 const info_a = operand_ty.intInfo(mod);
11601164 const info_b = dest_ty.intInfo(mod);
11611165
......@@ -1211,7 +1215,8 @@ fn trunc(
12111215 operand_ty: Type,
12121216 dest_ty: Type,
12131217) !MCValue {
1214 const mod = self.bin_file.comp.module.?;
1218 const pt = self.pt;
1219 const mod = pt.zcu;
12151220 const info_a = operand_ty.intInfo(mod);
12161221 const info_b = dest_ty.intInfo(mod);
12171222
......@@ -1275,7 +1280,8 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
12751280
12761281fn airNot(self: *Self, inst: Air.Inst.Index) !void {
12771282 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1278 const mod = self.bin_file.comp.module.?;
1283 const pt = self.pt;
1284 const mod = pt.zcu;
12791285 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
12801286 const operand_bind: ReadArg.Bind = .{ .inst = ty_op.operand };
12811287 const operand_ty = self.typeOf(ty_op.operand);
......@@ -1371,7 +1377,8 @@ fn minMax(
13711377 rhs_ty: Type,
13721378 maybe_inst: ?Air.Inst.Index,
13731379) !MCValue {
1374 const mod = self.bin_file.comp.module.?;
1380 const pt = self.pt;
1381 const mod = pt.zcu;
13751382 switch (lhs_ty.zigTypeTag(mod)) {
13761383 .Float => return self.fail("TODO ARM min/max on floats", .{}),
13771384 .Vector => return self.fail("TODO ARM min/max on vectors", .{}),
......@@ -1580,7 +1587,8 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
15801587 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
15811588 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
15821589 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
1583 const mod = self.bin_file.comp.module.?;
1590 const pt = self.pt;
1591 const mod = pt.zcu;
15841592 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
15851593 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
15861594 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -1588,9 +1596,9 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
15881596 const rhs_ty = self.typeOf(extra.rhs);
15891597
15901598 const tuple_ty = self.typeOfIndex(inst);
1591 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1592 const tuple_align = tuple_ty.abiAlignment(mod);
1593 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1599 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1600 const tuple_align = tuple_ty.abiAlignment(pt);
1601 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
15941602
15951603 switch (lhs_ty.zigTypeTag(mod)) {
15961604 .Vector => return self.fail("TODO implement add_with_overflow/sub_with_overflow for vectors", .{}),
......@@ -1693,7 +1701,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
16931701 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
16941702 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
16951703 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
1696 const mod = self.bin_file.comp.module.?;
1704 const pt = self.pt;
1705 const mod = pt.zcu;
16971706 const result: MCValue = result: {
16981707 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
16991708 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -1701,9 +1710,9 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
17011710 const rhs_ty = self.typeOf(extra.rhs);
17021711
17031712 const tuple_ty = self.typeOfIndex(inst);
1704 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1705 const tuple_align = tuple_ty.abiAlignment(mod);
1706 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1713 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1714 const tuple_align = tuple_ty.abiAlignment(pt);
1715 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
17071716
17081717 switch (lhs_ty.zigTypeTag(mod)) {
17091718 .Vector => return self.fail("TODO implement mul_with_overflow for vectors", .{}),
......@@ -1857,15 +1866,16 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
18571866 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
18581867 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
18591868 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
1860 const mod = self.bin_file.comp.module.?;
1869 const pt = self.pt;
1870 const mod = pt.zcu;
18611871 const result: MCValue = result: {
18621872 const lhs_ty = self.typeOf(extra.lhs);
18631873 const rhs_ty = self.typeOf(extra.rhs);
18641874
18651875 const tuple_ty = self.typeOfIndex(inst);
1866 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1867 const tuple_align = tuple_ty.abiAlignment(mod);
1868 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1876 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1877 const tuple_align = tuple_ty.abiAlignment(pt);
1878 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
18691879
18701880 switch (lhs_ty.zigTypeTag(mod)) {
18711881 .Vector => return self.fail("TODO implement shl_with_overflow for vectors", .{}),
......@@ -2013,11 +2023,11 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
20132023}
20142024
20152025fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
2016 const mod = self.bin_file.comp.module.?;
2026 const pt = self.pt;
20172027 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20182028 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
20192029 const optional_ty = self.typeOfIndex(inst);
2020 const abi_size: u32 = @intCast(optional_ty.abiSize(mod));
2030 const abi_size: u32 = @intCast(optional_ty.abiSize(pt));
20212031
20222032 // Optional with a zero-bit payload type is just a boolean true
20232033 if (abi_size == 1) {
......@@ -2036,17 +2046,18 @@ fn errUnionErr(
20362046 error_union_ty: Type,
20372047 maybe_inst: ?Air.Inst.Index,
20382048) !MCValue {
2039 const mod = self.bin_file.comp.module.?;
2049 const pt = self.pt;
2050 const mod = pt.zcu;
20402051 const err_ty = error_union_ty.errorUnionSet(mod);
20412052 const payload_ty = error_union_ty.errorUnionPayload(mod);
20422053 if (err_ty.errorSetIsEmpty(mod)) {
20432054 return MCValue{ .immediate = 0 };
20442055 }
2045 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2056 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
20462057 return try error_union_bind.resolveToMcv(self);
20472058 }
20482059
2049 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, mod));
2060 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
20502061 switch (try error_union_bind.resolveToMcv(self)) {
20512062 .register => {
20522063 var operand_reg: Register = undefined;
......@@ -2068,7 +2079,7 @@ fn errUnionErr(
20682079 );
20692080
20702081 const err_bit_offset = err_offset * 8;
2071 const err_bit_size: u32 = @intCast(err_ty.abiSize(mod) * 8);
2082 const err_bit_size: u32 = @intCast(err_ty.abiSize(pt) * 8);
20722083
20732084 _ = try self.addInst(.{
20742085 .tag = .ubfx, // errors are unsigned integers
......@@ -2113,17 +2124,18 @@ fn errUnionPayload(
21132124 error_union_ty: Type,
21142125 maybe_inst: ?Air.Inst.Index,
21152126) !MCValue {
2116 const mod = self.bin_file.comp.module.?;
2127 const pt = self.pt;
2128 const mod = pt.zcu;
21172129 const err_ty = error_union_ty.errorUnionSet(mod);
21182130 const payload_ty = error_union_ty.errorUnionPayload(mod);
21192131 if (err_ty.errorSetIsEmpty(mod)) {
21202132 return try error_union_bind.resolveToMcv(self);
21212133 }
2122 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2134 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
21232135 return MCValue.none;
21242136 }
21252137
2126 const payload_offset: u32 = @intCast(errUnionPayloadOffset(payload_ty, mod));
2138 const payload_offset: u32 = @intCast(errUnionPayloadOffset(payload_ty, pt));
21272139 switch (try error_union_bind.resolveToMcv(self)) {
21282140 .register => {
21292141 var operand_reg: Register = undefined;
......@@ -2145,7 +2157,7 @@ fn errUnionPayload(
21452157 );
21462158
21472159 const payload_bit_offset = payload_offset * 8;
2148 const payload_bit_size: u32 = @intCast(payload_ty.abiSize(mod) * 8);
2160 const payload_bit_size: u32 = @intCast(payload_ty.abiSize(pt) * 8);
21492161
21502162 _ = try self.addInst(.{
21512163 .tag = if (payload_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -2223,20 +2235,21 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
22232235
22242236/// T to E!T
22252237fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
2226 const mod = self.bin_file.comp.module.?;
2238 const pt = self.pt;
2239 const mod = pt.zcu;
22272240 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
22282241 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
22292242 const error_union_ty = ty_op.ty.toType();
22302243 const error_ty = error_union_ty.errorUnionSet(mod);
22312244 const payload_ty = error_union_ty.errorUnionPayload(mod);
22322245 const operand = try self.resolveInst(ty_op.operand);
2233 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
2246 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
22342247
2235 const abi_size: u32 = @intCast(error_union_ty.abiSize(mod));
2236 const abi_align = error_union_ty.abiAlignment(mod);
2248 const abi_size: u32 = @intCast(error_union_ty.abiSize(pt));
2249 const abi_align = error_union_ty.abiAlignment(pt);
22372250 const stack_offset: u32 = @intCast(try self.allocMem(abi_size, abi_align, inst));
2238 const payload_off = errUnionPayloadOffset(payload_ty, mod);
2239 const err_off = errUnionErrorOffset(payload_ty, mod);
2251 const payload_off = errUnionPayloadOffset(payload_ty, pt);
2252 const err_off = errUnionErrorOffset(payload_ty, pt);
22402253 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), operand);
22412254 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), .{ .immediate = 0 });
22422255
......@@ -2247,20 +2260,21 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
22472260
22482261/// E to E!T
22492262fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
2250 const mod = self.bin_file.comp.module.?;
2263 const pt = self.pt;
2264 const mod = pt.zcu;
22512265 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
22522266 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
22532267 const error_union_ty = ty_op.ty.toType();
22542268 const error_ty = error_union_ty.errorUnionSet(mod);
22552269 const payload_ty = error_union_ty.errorUnionPayload(mod);
22562270 const operand = try self.resolveInst(ty_op.operand);
2257 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
2271 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
22582272
2259 const abi_size: u32 = @intCast(error_union_ty.abiSize(mod));
2260 const abi_align = error_union_ty.abiAlignment(mod);
2273 const abi_size: u32 = @intCast(error_union_ty.abiSize(pt));
2274 const abi_align = error_union_ty.abiAlignment(pt);
22612275 const stack_offset: u32 = @intCast(try self.allocMem(abi_size, abi_align, inst));
2262 const payload_off = errUnionPayloadOffset(payload_ty, mod);
2263 const err_off = errUnionErrorOffset(payload_ty, mod);
2276 const payload_off = errUnionPayloadOffset(payload_ty, pt);
2277 const err_off = errUnionErrorOffset(payload_ty, pt);
22642278 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), operand);
22652279 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), .undef);
22662280
......@@ -2364,9 +2378,10 @@ fn ptrElemVal(
23642378 ptr_ty: Type,
23652379 maybe_inst: ?Air.Inst.Index,
23662380) !MCValue {
2367 const mod = self.bin_file.comp.module.?;
2381 const pt = self.pt;
2382 const mod = pt.zcu;
23682383 const elem_ty = ptr_ty.childType(mod);
2369 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
2384 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
23702385
23712386 switch (elem_size) {
23722387 1, 4 => {
......@@ -2423,7 +2438,8 @@ fn ptrElemVal(
24232438}
24242439
24252440fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
2426 const mod = self.bin_file.comp.module.?;
2441 const pt = self.pt;
2442 const mod = pt.zcu;
24272443 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
24282444 const slice_ty = self.typeOf(bin_op.lhs);
24292445 const result: MCValue = if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -2466,7 +2482,8 @@ fn arrayElemVal(
24662482 array_ty: Type,
24672483 maybe_inst: ?Air.Inst.Index,
24682484) InnerError!MCValue {
2469 const mod = self.bin_file.comp.module.?;
2485 const pt = self.pt;
2486 const mod = pt.zcu;
24702487 const elem_ty = array_ty.childType(mod);
24712488
24722489 const mcv = try array_bind.resolveToMcv(self);
......@@ -2501,7 +2518,7 @@ fn arrayElemVal(
25012518
25022519 const base_bind: ReadArg.Bind = .{ .mcv = ptr_to_mcv };
25032520
2504 const ptr_ty = try mod.singleMutPtrType(elem_ty);
2521 const ptr_ty = try pt.singleMutPtrType(elem_ty);
25052522
25062523 return try self.ptrElemVal(base_bind, index_bind, ptr_ty, maybe_inst);
25072524 },
......@@ -2522,7 +2539,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
25222539}
25232540
25242541fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
2525 const mod = self.bin_file.comp.module.?;
2542 const pt = self.pt;
2543 const mod = pt.zcu;
25262544 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
25272545 const ptr_ty = self.typeOf(bin_op.lhs);
25282546 const result: MCValue = if (!ptr_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -2656,9 +2674,10 @@ fn reuseOperand(
26562674}
26572675
26582676fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
2659 const mod = self.bin_file.comp.module.?;
2677 const pt = self.pt;
2678 const mod = pt.zcu;
26602679 const elem_ty = ptr_ty.childType(mod);
2661 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
2680 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
26622681
26632682 switch (ptr) {
26642683 .none => unreachable,
......@@ -2733,11 +2752,12 @@ fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!vo
27332752}
27342753
27352754fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
2736 const mod = self.bin_file.comp.module.?;
2755 const pt = self.pt;
2756 const mod = pt.zcu;
27372757 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27382758 const elem_ty = self.typeOfIndex(inst);
27392759 const result: MCValue = result: {
2740 if (!elem_ty.hasRuntimeBits(mod))
2760 if (!elem_ty.hasRuntimeBits(pt))
27412761 break :result MCValue.none;
27422762
27432763 const ptr = try self.resolveInst(ty_op.operand);
......@@ -2746,7 +2766,7 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
27462766 break :result MCValue.dead;
27472767
27482768 const dest_mcv: MCValue = blk: {
2749 const ptr_fits_dest = elem_ty.abiSize(mod) <= 4;
2769 const ptr_fits_dest = elem_ty.abiSize(pt) <= 4;
27502770 if (ptr_fits_dest and self.reuseOperand(inst, ty_op.operand, 0, ptr)) {
27512771 // The MCValue that holds the pointer can be re-used as the value.
27522772 break :blk ptr;
......@@ -2762,8 +2782,8 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
27622782}
27632783
27642784fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
2765 const mod = self.bin_file.comp.module.?;
2766 const elem_size: u32 = @intCast(value_ty.abiSize(mod));
2785 const pt = self.pt;
2786 const elem_size: u32 = @intCast(value_ty.abiSize(pt));
27672787
27682788 switch (ptr) {
27692789 .none => unreachable,
......@@ -2882,11 +2902,12 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
28822902
28832903fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
28842904 return if (self.liveness.isUnused(inst)) .dead else result: {
2885 const mod = self.bin_file.comp.module.?;
2905 const pt = self.pt;
2906 const mod = pt.zcu;
28862907 const mcv = try self.resolveInst(operand);
28872908 const ptr_ty = self.typeOf(operand);
28882909 const struct_ty = ptr_ty.childType(mod);
2889 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, mod));
2910 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, pt));
28902911 switch (mcv) {
28912912 .ptr_stack_offset => |off| {
28922913 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -2906,11 +2927,12 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29062927 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;
29072928 const operand = extra.struct_operand;
29082929 const index = extra.field_index;
2909 const mod = self.bin_file.comp.module.?;
2930 const pt = self.pt;
2931 const mod = pt.zcu;
29102932 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
29112933 const mcv = try self.resolveInst(operand);
29122934 const struct_ty = self.typeOf(operand);
2913 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, mod));
2935 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, pt));
29142936 const struct_field_ty = struct_ty.structFieldType(index, mod);
29152937
29162938 switch (mcv) {
......@@ -2974,7 +2996,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29742996 );
29752997
29762998 const field_bit_offset = struct_field_offset * 8;
2977 const field_bit_size: u32 = @intCast(struct_field_ty.abiSize(mod) * 8);
2999 const field_bit_size: u32 = @intCast(struct_field_ty.abiSize(pt) * 8);
29783000
29793001 _ = try self.addInst(.{
29803002 .tag = if (struct_field_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -2996,7 +3018,8 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29963018}
29973019
29983020fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
2999 const mod = self.bin_file.comp.module.?;
3021 const pt = self.pt;
3022 const mod = pt.zcu;
30003023 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
30013024 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
30023025 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
......@@ -3007,7 +3030,7 @@ fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
30073030 return self.fail("TODO implement @fieldParentPtr codegen for unions", .{});
30083031 }
30093032
3010 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(extra.field_index, mod));
3033 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(extra.field_index, pt));
30113034 switch (field_ptr) {
30123035 .ptr_stack_offset => |off| {
30133036 break :result MCValue{ .ptr_stack_offset = off + struct_field_offset };
......@@ -3390,7 +3413,8 @@ fn addSub(
33903413 rhs_ty: Type,
33913414 maybe_inst: ?Air.Inst.Index,
33923415) InnerError!MCValue {
3393 const mod = self.bin_file.comp.module.?;
3416 const pt = self.pt;
3417 const mod = pt.zcu;
33943418 switch (lhs_ty.zigTypeTag(mod)) {
33953419 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
33963420 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3446,7 +3470,8 @@ fn mul(
34463470 rhs_ty: Type,
34473471 maybe_inst: ?Air.Inst.Index,
34483472) InnerError!MCValue {
3449 const mod = self.bin_file.comp.module.?;
3473 const pt = self.pt;
3474 const mod = pt.zcu;
34503475 switch (lhs_ty.zigTypeTag(mod)) {
34513476 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
34523477 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3479,7 +3504,8 @@ fn divFloat(
34793504 _ = rhs_ty;
34803505 _ = maybe_inst;
34813506
3482 const mod = self.bin_file.comp.module.?;
3507 const pt = self.pt;
3508 const mod = pt.zcu;
34833509 switch (lhs_ty.zigTypeTag(mod)) {
34843510 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
34853511 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3495,7 +3521,8 @@ fn divTrunc(
34953521 rhs_ty: Type,
34963522 maybe_inst: ?Air.Inst.Index,
34973523) InnerError!MCValue {
3498 const mod = self.bin_file.comp.module.?;
3524 const pt = self.pt;
3525 const mod = pt.zcu;
34993526 switch (lhs_ty.zigTypeTag(mod)) {
35003527 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35013528 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3538,7 +3565,8 @@ fn divFloor(
35383565 rhs_ty: Type,
35393566 maybe_inst: ?Air.Inst.Index,
35403567) InnerError!MCValue {
3541 const mod = self.bin_file.comp.module.?;
3568 const pt = self.pt;
3569 const mod = pt.zcu;
35423570 switch (lhs_ty.zigTypeTag(mod)) {
35433571 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35443572 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3586,7 +3614,8 @@ fn divExact(
35863614 _ = rhs_ty;
35873615 _ = maybe_inst;
35883616
3589 const mod = self.bin_file.comp.module.?;
3617 const pt = self.pt;
3618 const mod = pt.zcu;
35903619 switch (lhs_ty.zigTypeTag(mod)) {
35913620 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35923621 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3603,7 +3632,8 @@ fn rem(
36033632 rhs_ty: Type,
36043633 maybe_inst: ?Air.Inst.Index,
36053634) InnerError!MCValue {
3606 const mod = self.bin_file.comp.module.?;
3635 const pt = self.pt;
3636 const mod = pt.zcu;
36073637 switch (lhs_ty.zigTypeTag(mod)) {
36083638 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
36093639 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3672,7 +3702,8 @@ fn modulo(
36723702 _ = rhs_ty;
36733703 _ = maybe_inst;
36743704
3675 const mod = self.bin_file.comp.module.?;
3705 const pt = self.pt;
3706 const mod = pt.zcu;
36763707 switch (lhs_ty.zigTypeTag(mod)) {
36773708 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
36783709 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3690,7 +3721,8 @@ fn wrappingArithmetic(
36903721 rhs_ty: Type,
36913722 maybe_inst: ?Air.Inst.Index,
36923723) InnerError!MCValue {
3693 const mod = self.bin_file.comp.module.?;
3724 const pt = self.pt;
3725 const mod = pt.zcu;
36943726 switch (lhs_ty.zigTypeTag(mod)) {
36953727 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
36963728 .Int => {
......@@ -3728,7 +3760,8 @@ fn bitwise(
37283760 rhs_ty: Type,
37293761 maybe_inst: ?Air.Inst.Index,
37303762) InnerError!MCValue {
3731 const mod = self.bin_file.comp.module.?;
3763 const pt = self.pt;
3764 const mod = pt.zcu;
37323765 switch (lhs_ty.zigTypeTag(mod)) {
37333766 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
37343767 .Int => {
......@@ -3773,7 +3806,8 @@ fn shiftExact(
37733806 rhs_ty: Type,
37743807 maybe_inst: ?Air.Inst.Index,
37753808) InnerError!MCValue {
3776 const mod = self.bin_file.comp.module.?;
3809 const pt = self.pt;
3810 const mod = pt.zcu;
37773811 switch (lhs_ty.zigTypeTag(mod)) {
37783812 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
37793813 .Int => {
......@@ -3812,7 +3846,8 @@ fn shiftNormal(
38123846 rhs_ty: Type,
38133847 maybe_inst: ?Air.Inst.Index,
38143848) InnerError!MCValue {
3815 const mod = self.bin_file.comp.module.?;
3849 const pt = self.pt;
3850 const mod = pt.zcu;
38163851 switch (lhs_ty.zigTypeTag(mod)) {
38173852 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
38183853 .Int => {
......@@ -3855,7 +3890,8 @@ fn booleanOp(
38553890 rhs_ty: Type,
38563891 maybe_inst: ?Air.Inst.Index,
38573892) InnerError!MCValue {
3858 const mod = self.bin_file.comp.module.?;
3893 const pt = self.pt;
3894 const mod = pt.zcu;
38593895 switch (lhs_ty.zigTypeTag(mod)) {
38603896 .Bool => {
38613897 const lhs_immediate = try lhs_bind.resolveToImmediate(self);
......@@ -3889,7 +3925,8 @@ fn ptrArithmetic(
38893925 rhs_ty: Type,
38903926 maybe_inst: ?Air.Inst.Index,
38913927) InnerError!MCValue {
3892 const mod = self.bin_file.comp.module.?;
3928 const pt = self.pt;
3929 const mod = pt.zcu;
38933930 switch (lhs_ty.zigTypeTag(mod)) {
38943931 .Pointer => {
38953932 assert(rhs_ty.eql(Type.usize, mod));
......@@ -3899,7 +3936,7 @@ fn ptrArithmetic(
38993936 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
39003937 else => ptr_ty.childType(mod),
39013938 };
3902 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
3939 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
39033940
39043941 const base_tag: Air.Inst.Tag = switch (tag) {
39053942 .ptr_add => .add,
......@@ -3926,8 +3963,9 @@ fn ptrArithmetic(
39263963}
39273964
39283965fn genLdrRegister(self: *Self, dest_reg: Register, addr_reg: Register, ty: Type) !void {
3929 const mod = self.bin_file.comp.module.?;
3930 const abi_size = ty.abiSize(mod);
3966 const pt = self.pt;
3967 const mod = pt.zcu;
3968 const abi_size = ty.abiSize(pt);
39313969
39323970 const tag: Mir.Inst.Tag = switch (abi_size) {
39333971 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb else .ldrb,
......@@ -3961,8 +3999,8 @@ fn genLdrRegister(self: *Self, dest_reg: Register, addr_reg: Register, ty: Type)
39613999}
39624000
39634001fn genStrRegister(self: *Self, source_reg: Register, addr_reg: Register, ty: Type) !void {
3964 const mod = self.bin_file.comp.module.?;
3965 const abi_size = ty.abiSize(mod);
4002 const pt = self.pt;
4003 const abi_size = ty.abiSize(pt);
39664004
39674005 const tag: Mir.Inst.Tag = switch (abi_size) {
39684006 1 => .strb,
......@@ -4168,7 +4206,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
41684206 while (self.args[arg_index] == .none) arg_index += 1;
41694207 self.arg_index = arg_index + 1;
41704208
4171 const mod = self.bin_file.comp.module.?;
4209 const pt = self.pt;
4210 const mod = pt.zcu;
41724211 const ty = self.typeOfIndex(inst);
41734212 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
41744213 const src_index = self.air.instructions.items(.data)[@intFromEnum(inst)].arg.src_index;
......@@ -4223,7 +4262,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42234262 const extra = self.air.extraData(Air.Call, pl_op.payload);
42244263 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
42254264 const ty = self.typeOf(callee);
4226 const mod = self.bin_file.comp.module.?;
4265 const pt = self.pt;
4266 const mod = pt.zcu;
42274267
42284268 const fn_ty = switch (ty.zigTypeTag(mod)) {
42294269 .Fn => ty,
......@@ -4253,11 +4293,11 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42534293 const r0_lock: ?RegisterLock = if (info.return_value == .stack_offset) blk: {
42544294 log.debug("airCall: return by reference", .{});
42554295 const ret_ty = fn_ty.fnReturnType(mod);
4256 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4257 const ret_abi_align = ret_ty.abiAlignment(mod);
4296 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4297 const ret_abi_align = ret_ty.abiAlignment(pt);
42584298 const stack_offset = try self.allocMem(ret_abi_size, ret_abi_align, inst);
42594299
4260 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4300 const ptr_ty = try pt.singleMutPtrType(ret_ty);
42614301 try self.register_manager.getReg(.r0, null);
42624302 try self.genSetReg(ptr_ty, .r0, .{ .ptr_stack_offset = stack_offset });
42634303
......@@ -4293,7 +4333,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42934333
42944334 // Due to incremental compilation, how function calls are generated depends
42954335 // on linking.
4296 if (try self.air.value(callee, mod)) |func_value| {
4336 if (try self.air.value(callee, pt)) |func_value| {
42974337 if (func_value.getFunction(mod)) |func| {
42984338 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
42994339 const sym_index = try elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, func.owner_decl);
......@@ -4374,7 +4414,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43744414}
43754415
43764416fn airRet(self: *Self, inst: Air.Inst.Index) !void {
4377 const mod = self.bin_file.comp.module.?;
4417 const pt = self.pt;
4418 const mod = pt.zcu;
43784419 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
43794420 const operand = try self.resolveInst(un_op);
43804421 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -4393,7 +4434,7 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
43934434 //
43944435 // self.ret_mcv is an address to where this function
43954436 // should store its result into
4396 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4437 const ptr_ty = try pt.singleMutPtrType(ret_ty);
43974438 try self.store(self.ret_mcv, operand, ptr_ty, ret_ty);
43984439 },
43994440 else => unreachable, // invalid return result
......@@ -4406,7 +4447,8 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44064447}
44074448
44084449fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
4409 const mod = self.bin_file.comp.module.?;
4450 const pt = self.pt;
4451 const mod = pt.zcu;
44104452 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44114453 const ptr = try self.resolveInst(un_op);
44124454 const ptr_ty = self.typeOf(un_op);
......@@ -4430,8 +4472,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
44304472 // location.
44314473 const op_inst = un_op.toIndex().?;
44324474 if (self.air.instructions.items(.tag)[@intFromEnum(op_inst)] != .ret_ptr) {
4433 const abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4434 const abi_align = ret_ty.abiAlignment(mod);
4475 const abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4476 const abi_align = ret_ty.abiAlignment(pt);
44354477
44364478 const offset = try self.allocMem(abi_size, abi_align, null);
44374479
......@@ -4467,11 +4509,12 @@ fn cmp(
44674509 lhs_ty: Type,
44684510 op: math.CompareOperator,
44694511) !MCValue {
4470 const mod = self.bin_file.comp.module.?;
4512 const pt = self.pt;
4513 const mod = pt.zcu;
44714514 const int_ty = switch (lhs_ty.zigTypeTag(mod)) {
44724515 .Optional => blk: {
44734516 const payload_ty = lhs_ty.optionalChild(mod);
4474 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4517 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44754518 break :blk Type.u1;
44764519 } else if (lhs_ty.isPtrLikeOptional(mod)) {
44774520 break :blk Type.usize;
......@@ -4573,7 +4616,8 @@ fn airDbgStmt(self: *Self, inst: Air.Inst.Index) !void {
45734616}
45744617
45754618fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
4576 const mod = self.bin_file.comp.module.?;
4619 const pt = self.pt;
4620 const mod = pt.zcu;
45774621 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
45784622 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
45794623 const func = mod.funcInfo(extra.data.func);
......@@ -4785,9 +4829,10 @@ fn isNull(
47854829 operand_bind: ReadArg.Bind,
47864830 operand_ty: Type,
47874831) !MCValue {
4788 const mod = self.bin_file.comp.module.?;
4832 const pt = self.pt;
4833 const mod = pt.zcu;
47894834 if (operand_ty.isPtrLikeOptional(mod)) {
4790 assert(operand_ty.abiSize(mod) == 4);
4835 assert(operand_ty.abiSize(pt) == 4);
47914836
47924837 const imm_bind: ReadArg.Bind = .{ .mcv = .{ .immediate = 0 } };
47934838 return self.cmp(operand_bind, imm_bind, Type.usize, .eq);
......@@ -4819,7 +4864,8 @@ fn airIsNull(self: *Self, inst: Air.Inst.Index) !void {
48194864}
48204865
48214866fn airIsNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4822 const mod = self.bin_file.comp.module.?;
4867 const pt = self.pt;
4868 const mod = pt.zcu;
48234869 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48244870 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
48254871 const operand_ptr = try self.resolveInst(un_op);
......@@ -4846,7 +4892,8 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
48464892}
48474893
48484894fn airIsNonNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4849 const mod = self.bin_file.comp.module.?;
4895 const pt = self.pt;
4896 const mod = pt.zcu;
48504897 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48514898 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
48524899 const operand_ptr = try self.resolveInst(un_op);
......@@ -4866,7 +4913,8 @@ fn isErr(
48664913 error_union_bind: ReadArg.Bind,
48674914 error_union_ty: Type,
48684915) !MCValue {
4869 const mod = self.bin_file.comp.module.?;
4916 const pt = self.pt;
4917 const mod = pt.zcu;
48704918 const error_type = error_union_ty.errorUnionSet(mod);
48714919
48724920 if (error_type.errorSetIsEmpty(mod)) {
......@@ -4908,7 +4956,8 @@ fn airIsErr(self: *Self, inst: Air.Inst.Index) !void {
49084956}
49094957
49104958fn airIsErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4911 const mod = self.bin_file.comp.module.?;
4959 const pt = self.pt;
4960 const mod = pt.zcu;
49124961 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49134962 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49144963 const operand_ptr = try self.resolveInst(un_op);
......@@ -4935,7 +4984,8 @@ fn airIsNonErr(self: *Self, inst: Air.Inst.Index) !void {
49354984}
49364985
49374986fn airIsNonErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4938 const mod = self.bin_file.comp.module.?;
4987 const pt = self.pt;
4988 const mod = pt.zcu;
49394989 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49404990 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49414991 const operand_ptr = try self.resolveInst(un_op);
......@@ -5154,10 +5204,10 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
51545204}
51555205
51565206fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
5157 const mod = self.bin_file.comp.module.?;
5207 const pt = self.pt;
51585208 const block_data = self.blocks.getPtr(block).?;
51595209
5160 if (self.typeOf(operand).hasRuntimeBits(mod)) {
5210 if (self.typeOf(operand).hasRuntimeBits(pt)) {
51615211 const operand_mcv = try self.resolveInst(operand);
51625212 const block_mcv = block_data.mcv;
51635213 if (block_mcv == .none) {
......@@ -5325,8 +5375,9 @@ fn setRegOrMem(self: *Self, ty: Type, loc: MCValue, val: MCValue) !void {
53255375}
53265376
53275377fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5328 const mod = self.bin_file.comp.module.?;
5329 const abi_size: u32 = @intCast(ty.abiSize(mod));
5378 const pt = self.pt;
5379 const mod = pt.zcu;
5380 const abi_size: u32 = @intCast(ty.abiSize(pt));
53305381 switch (mcv) {
53315382 .dead => unreachable,
53325383 .unreach, .none => return, // Nothing to do.
......@@ -5407,7 +5458,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54075458 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = reg });
54085459
54095460 const overflow_bit_ty = ty.structFieldType(1, mod);
5410 const overflow_bit_offset: u32 = @intCast(ty.structFieldOffset(1, mod));
5461 const overflow_bit_offset: u32 = @intCast(ty.structFieldOffset(1, pt));
54115462 const cond_reg = try self.register_manager.allocReg(null, gp);
54125463
54135464 // C flag: movcs reg, #1
......@@ -5445,7 +5496,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54455496 const reg = try self.copyToTmpRegister(ty, mcv);
54465497 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
54475498 } else {
5448 const ptr_ty = try mod.singleMutPtrType(ty);
5499 const ptr_ty = try pt.singleMutPtrType(ty);
54495500
54505501 // TODO call extern memcpy
54515502 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5487,7 +5538,8 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54875538}
54885539
54895540fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
5490 const mod = self.bin_file.comp.module.?;
5541 const pt = self.pt;
5542 const mod = pt.zcu;
54915543 switch (mcv) {
54925544 .dead => unreachable,
54935545 .unreach, .none => return, // Nothing to do.
......@@ -5662,7 +5714,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
56625714 },
56635715 .stack_offset => |off| {
56645716 // TODO: maybe addressing from sp instead of fp
5665 const abi_size: u32 = @intCast(ty.abiSize(mod));
5717 const abi_size: u32 = @intCast(ty.abiSize(pt));
56665718
56675719 const tag: Mir.Inst.Tag = switch (abi_size) {
56685720 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb else .ldrb,
......@@ -5713,7 +5765,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57135765 }
57145766 },
57155767 .stack_argument_offset => |off| {
5716 const abi_size = ty.abiSize(mod);
5768 const abi_size = ty.abiSize(pt);
57175769
57185770 const tag: Mir.Inst.Tag = switch (abi_size) {
57195771 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb_stack_argument else .ldrb_stack_argument,
......@@ -5734,8 +5786,8 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57345786}
57355787
57365788fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5737 const mod = self.bin_file.comp.module.?;
5738 const abi_size: u32 = @intCast(ty.abiSize(mod));
5789 const pt = self.pt;
5790 const abi_size: u32 = @intCast(ty.abiSize(pt));
57395791 switch (mcv) {
57405792 .dead => unreachable,
57415793 .none, .unreach => return,
......@@ -5802,7 +5854,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
58025854 const reg = try self.copyToTmpRegister(ty, mcv);
58035855 return self.genSetStackArgument(ty, stack_offset, MCValue{ .register = reg });
58045856 } else {
5805 const ptr_ty = try mod.singleMutPtrType(ty);
5857 const ptr_ty = try pt.singleMutPtrType(ty);
58065858
58075859 // TODO call extern memcpy
58085860 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5890,7 +5942,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
58905942}
58915943
58925944fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
5893 const mod = self.bin_file.comp.module.?;
5945 const pt = self.pt;
5946 const mod = pt.zcu;
58945947 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58955948 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
58965949 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -6009,7 +6062,8 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
60096062}
60106063
60116064fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
6012 const mod = self.bin_file.comp.module.?;
6065 const pt = self.pt;
6066 const mod = pt.zcu;
60136067 const vector_ty = self.typeOfIndex(inst);
60146068 const len = vector_ty.vectorLen(mod);
60156069 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6054,15 +6108,15 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
60546108}
60556109
60566110fn airTry(self: *Self, inst: Air.Inst.Index) !void {
6111 const pt = self.pt;
60576112 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
60586113 const extra = self.air.extraData(Air.Try, pl_op.payload);
60596114 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
60606115 const result: MCValue = result: {
60616116 const error_union_bind: ReadArg.Bind = .{ .inst = pl_op.operand };
60626117 const error_union_ty = self.typeOf(pl_op.operand);
6063 const mod = self.bin_file.comp.module.?;
6064 const error_union_size: u32 = @intCast(error_union_ty.abiSize(mod));
6065 const error_union_align = error_union_ty.abiAlignment(mod);
6118 const error_union_size: u32 = @intCast(error_union_ty.abiSize(pt));
6119 const error_union_align = error_union_ty.abiAlignment(pt);
60666120
60676121 // The error union will die in the body. However, we need the
60686122 // error union after the body in order to extract the payload
......@@ -6091,14 +6145,15 @@ fn airTryPtr(self: *Self, inst: Air.Inst.Index) !void {
60916145}
60926146
60936147fn resolveInst(self: *Self, inst: Air.Inst.Ref) InnerError!MCValue {
6094 const mod = self.bin_file.comp.module.?;
6148 const pt = self.pt;
6149 const mod = pt.zcu;
60956150
60966151 // If the type has no codegen bits, no need to store it.
60976152 const inst_ty = self.typeOf(inst);
6098 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod) and !inst_ty.isError(mod))
6153 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !inst_ty.isError(mod))
60996154 return MCValue{ .none = {} };
61006155
6101 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, mod)).?);
6156 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, pt)).?);
61026157
61036158 return self.getResolvedInstValue(inst_index);
61046159}
......@@ -6116,12 +6171,13 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
61166171}
61176172
61186173fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
6119 const mod = self.bin_file.comp.module.?;
6174 const pt = self.pt;
61206175 const mcv: MCValue = switch (try codegen.genTypedValue(
61216176 self.bin_file,
6177 pt,
61226178 self.src_loc,
61236179 val,
6124 mod.funcOwnerDeclIndex(self.func_index),
6180 pt.zcu.funcOwnerDeclIndex(self.func_index),
61256181 )) {
61266182 .mcv => |mcv| switch (mcv) {
61276183 .none => .none,
......@@ -6152,7 +6208,8 @@ const CallMCValues = struct {
61526208
61536209/// Caller must call `CallMCValues.deinit`.
61546210fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
6155 const mod = self.bin_file.comp.module.?;
6211 const pt = self.pt;
6212 const mod = pt.zcu;
61566213 const ip = &mod.intern_pool;
61576214 const fn_info = mod.typeToFunc(fn_ty).?;
61586215 const cc = fn_info.cc;
......@@ -6182,10 +6239,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
61826239
61836240 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
61846241 result.return_value = .{ .unreach = {} };
6185 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6242 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61866243 result.return_value = .{ .none = {} };
61876244 } else {
6188 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(mod));
6245 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
61896246 // TODO handle cases where multiple registers are used
61906247 if (ret_ty_size <= 4) {
61916248 result.return_value = .{ .register = c_abi_int_return_regs[0] };
......@@ -6200,10 +6257,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62006257 }
62016258
62026259 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6203 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8")
6260 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8")
62046261 ncrn = std.mem.alignForward(usize, ncrn, 2);
62056262
6206 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6263 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
62076264 if (std.math.divCeil(u32, param_size, 4) catch unreachable <= 4 - ncrn) {
62086265 if (param_size <= 4) {
62096266 result_arg.* = .{ .register = c_abi_int_param_regs[ncrn] };
......@@ -6215,7 +6272,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62156272 return self.fail("TODO MCValues split between registers and stack", .{});
62166273 } else {
62176274 ncrn = 4;
6218 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8")
6275 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8")
62196276 nsaa = std.mem.alignForward(u32, nsaa, 8);
62206277
62216278 result_arg.* = .{ .stack_argument_offset = nsaa };
......@@ -6229,10 +6286,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62296286 .Unspecified => {
62306287 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62316288 result.return_value = .{ .unreach = {} };
6232 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6289 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62336290 result.return_value = .{ .none = {} };
62346291 } else {
6235 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(mod));
6292 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
62366293 if (ret_ty_size == 0) {
62376294 assert(ret_ty.isError(mod));
62386295 result.return_value = .{ .immediate = 0 };
......@@ -6250,9 +6307,9 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62506307 var stack_offset: u32 = 0;
62516308
62526309 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6253 if (Type.fromInterned(ty).abiSize(mod) > 0) {
6254 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6255 const param_alignment = Type.fromInterned(ty).abiAlignment(mod);
6310 if (Type.fromInterned(ty).abiSize(pt) > 0) {
6311 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
6312 const param_alignment = Type.fromInterned(ty).abiAlignment(pt);
62566313
62576314 stack_offset = @intCast(param_alignment.forward(stack_offset));
62586315 result_arg.* = .{ .stack_argument_offset = stack_offset };
......@@ -6271,7 +6328,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62716328 return result;
62726329}
62736330
6274/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
6331/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
62756332fn wantSafety(self: *Self) bool {
62766333 return switch (self.bin_file.comp.root_mod.optimize_mode) {
62776334 .Debug => true,
......@@ -6305,11 +6362,9 @@ fn parseRegName(name: []const u8) ?Register {
63056362}
63066363
63076364fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
6308 const mod = self.bin_file.comp.module.?;
6309 return self.air.typeOf(inst, &mod.intern_pool);
6365 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
63106366}
63116367
63126368fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
6313 const mod = self.bin_file.comp.module.?;
6314 return self.air.typeOfIndex(inst, &mod.intern_pool);
6369 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
63156370}
src/arch/arm/Emit.zig+2-4
......@@ -9,10 +9,8 @@ const Mir = @import("Mir.zig");
99const bits = @import("bits.zig");
1010const link = @import("../../link.zig");
1111const Zcu = @import("../../Zcu.zig");
12/// Deprecated.
13const Module = Zcu;
1412const Type = @import("../../Type.zig");
15const ErrorMsg = Module.ErrorMsg;
13const ErrorMsg = Zcu.ErrorMsg;
1614const Target = std.Target;
1715const assert = std.debug.assert;
1816const Instruction = bits.Instruction;
......@@ -26,7 +24,7 @@ bin_file: *link.File,
2624debug_output: DebugInfoOutput,
2725target: *const std.Target,
2826err_msg: ?*ErrorMsg = null,
29src_loc: Module.LazySrcLoc,
27src_loc: Zcu.LazySrcLoc,
3028code: *std.ArrayList(u8),
3129
3230prev_di_line: u32,
src/arch/arm/abi.zig+30-32
......@@ -5,8 +5,6 @@ const Register = bits.Register;
55const RegisterManagerFn = @import("../../register_manager.zig").RegisterManager;
66const Type = @import("../../Type.zig");
77const Zcu = @import("../../Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108
119pub const Class = union(enum) {
1210 memory,
......@@ -26,29 +24,29 @@ pub const Class = union(enum) {
2624
2725pub const Context = enum { ret, arg };
2826
29pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
30 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
27pub fn classifyType(ty: Type, pt: Zcu.PerThread, ctx: Context) Class {
28 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
3129
3230 var maybe_float_bits: ?u16 = null;
3331 const max_byval_size = 512;
34 const ip = &mod.intern_pool;
35 switch (ty.zigTypeTag(mod)) {
32 const ip = &pt.zcu.intern_pool;
33 switch (ty.zigTypeTag(pt.zcu)) {
3634 .Struct => {
37 const bit_size = ty.bitSize(mod);
38 if (ty.containerLayout(mod) == .@"packed") {
35 const bit_size = ty.bitSize(pt);
36 if (ty.containerLayout(pt.zcu) == .@"packed") {
3937 if (bit_size > 64) return .memory;
4038 return .byval;
4139 }
4240 if (bit_size > max_byval_size) return .memory;
43 const float_count = countFloats(ty, mod, &maybe_float_bits);
41 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
4442 if (float_count <= byval_float_count) return .byval;
4543
46 const fields = ty.structFieldCount(mod);
44 const fields = ty.structFieldCount(pt.zcu);
4745 var i: u32 = 0;
4846 while (i < fields) : (i += 1) {
49 const field_ty = ty.structFieldType(i, mod);
50 const field_alignment = ty.structFieldAlign(i, mod);
51 const field_size = field_ty.bitSize(mod);
47 const field_ty = ty.structFieldType(i, pt.zcu);
48 const field_alignment = ty.structFieldAlign(i, pt);
49 const field_size = field_ty.bitSize(pt);
5250 if (field_size > 32 or field_alignment.compare(.gt, .@"32")) {
5351 return Class.arrSize(bit_size, 64);
5452 }
......@@ -56,19 +54,19 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
5654 return Class.arrSize(bit_size, 32);
5755 },
5856 .Union => {
59 const bit_size = ty.bitSize(mod);
60 const union_obj = mod.typeToUnion(ty).?;
57 const bit_size = ty.bitSize(pt);
58 const union_obj = pt.zcu.typeToUnion(ty).?;
6159 if (union_obj.getLayout(ip) == .@"packed") {
6260 if (bit_size > 64) return .memory;
6361 return .byval;
6462 }
6563 if (bit_size > max_byval_size) return .memory;
66 const float_count = countFloats(ty, mod, &maybe_float_bits);
64 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
6765 if (float_count <= byval_float_count) return .byval;
6866
6967 for (union_obj.field_types.get(ip), 0..) |field_ty, field_index| {
70 if (Type.fromInterned(field_ty).bitSize(mod) > 32 or
71 mod.unionFieldNormalAlignment(union_obj, @intCast(field_index)).compare(.gt, .@"32"))
68 if (Type.fromInterned(field_ty).bitSize(pt) > 32 or
69 pt.unionFieldNormalAlignment(union_obj, @intCast(field_index)).compare(.gt, .@"32"))
7270 {
7371 return Class.arrSize(bit_size, 64);
7472 }
......@@ -79,28 +77,28 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
7977 .Int => {
8078 // TODO this is incorrect for _BitInt(128) but implementing
8179 // this correctly makes implementing compiler-rt impossible.
82 // const bit_size = ty.bitSize(mod);
80 // const bit_size = ty.bitSize(pt);
8381 // if (bit_size > 64) return .memory;
8482 return .byval;
8583 },
8684 .Enum, .ErrorSet => {
87 const bit_size = ty.bitSize(mod);
85 const bit_size = ty.bitSize(pt);
8886 if (bit_size > 64) return .memory;
8987 return .byval;
9088 },
9189 .Vector => {
92 const bit_size = ty.bitSize(mod);
90 const bit_size = ty.bitSize(pt);
9391 // TODO is this controlled by a cpu feature?
9492 if (ctx == .ret and bit_size > 128) return .memory;
9593 if (bit_size > 512) return .memory;
9694 return .byval;
9795 },
9896 .Optional => {
99 assert(ty.isPtrLikeOptional(mod));
97 assert(ty.isPtrLikeOptional(pt.zcu));
10098 return .byval;
10199 },
102100 .Pointer => {
103 assert(!ty.isSlice(mod));
101 assert(!ty.isSlice(pt.zcu));
104102 return .byval;
105103 },
106104 .ErrorUnion,
......@@ -122,16 +120,16 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
122120}
123121
124122const byval_float_count = 4;
125fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u32 {
126 const ip = &mod.intern_pool;
127 const target = mod.getTarget();
123fn countFloats(ty: Type, zcu: *Zcu, maybe_float_bits: *?u16) u32 {
124 const ip = &zcu.intern_pool;
125 const target = zcu.getTarget();
128126 const invalid = std.math.maxInt(u32);
129 switch (ty.zigTypeTag(mod)) {
127 switch (ty.zigTypeTag(zcu)) {
130128 .Union => {
131 const union_obj = mod.typeToUnion(ty).?;
129 const union_obj = zcu.typeToUnion(ty).?;
132130 var max_count: u32 = 0;
133131 for (union_obj.field_types.get(ip)) |field_ty| {
134 const field_count = countFloats(Type.fromInterned(field_ty), mod, maybe_float_bits);
132 const field_count = countFloats(Type.fromInterned(field_ty), zcu, maybe_float_bits);
135133 if (field_count == invalid) return invalid;
136134 if (field_count > max_count) max_count = field_count;
137135 if (max_count > byval_float_count) return invalid;
......@@ -139,12 +137,12 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u32 {
139137 return max_count;
140138 },
141139 .Struct => {
142 const fields_len = ty.structFieldCount(mod);
140 const fields_len = ty.structFieldCount(zcu);
143141 var count: u32 = 0;
144142 var i: u32 = 0;
145143 while (i < fields_len) : (i += 1) {
146 const field_ty = ty.structFieldType(i, mod);
147 const field_count = countFloats(field_ty, mod, maybe_float_bits);
144 const field_ty = ty.structFieldType(i, zcu);
145 const field_count = countFloats(field_ty, zcu, maybe_float_bits);
148146 if (field_count == invalid) return invalid;
149147 count += field_count;
150148 if (count > byval_float_count) return invalid;
src/arch/riscv64/CodeGen.zig+267-216
......@@ -46,6 +46,7 @@ const RegisterLock = RegisterManager.RegisterLock;
4646const InnerError = CodeGenError || error{OutOfRegisters};
4747
4848gpa: Allocator,
49pt: Zcu.PerThread,
4950air: Air,
5051mod: *Package.Module,
5152liveness: Liveness,
......@@ -541,14 +542,14 @@ const FrameAlloc = struct {
541542 .ref_count = 0,
542543 };
543544 }
544 fn initType(ty: Type, zcu: *Zcu) FrameAlloc {
545 fn initType(ty: Type, pt: Zcu.PerThread) FrameAlloc {
545546 return init(.{
546 .size = ty.abiSize(zcu),
547 .alignment = ty.abiAlignment(zcu),
547 .size = ty.abiSize(pt),
548 .alignment = ty.abiAlignment(pt),
548549 });
549550 }
550 fn initSpill(ty: Type, zcu: *Zcu) FrameAlloc {
551 const abi_size = ty.abiSize(zcu);
551 fn initSpill(ty: Type, pt: Zcu.PerThread) FrameAlloc {
552 const abi_size = ty.abiSize(pt);
552553 const spill_size = if (abi_size < 8)
553554 math.ceilPowerOfTwoAssert(u64, abi_size)
554555 else
......@@ -556,7 +557,7 @@ const FrameAlloc = struct {
556557 return init(.{
557558 .size = spill_size,
558559 .pad = @intCast(spill_size - abi_size),
559 .alignment = ty.abiAlignment(zcu).maxStrict(
560 .alignment = ty.abiAlignment(pt).maxStrict(
560561 Alignment.fromNonzeroByteUnits(@min(spill_size, 8)),
561562 ),
562563 });
......@@ -696,6 +697,7 @@ const CallView = enum(u1) {
696697
697698pub fn generate(
698699 bin_file: *link.File,
700 pt: Zcu.PerThread,
699701 src_loc: Zcu.LazySrcLoc,
700702 func_index: InternPool.Index,
701703 air: Air,
......@@ -703,9 +705,9 @@ pub fn generate(
703705 code: *std.ArrayList(u8),
704706 debug_output: DebugInfoOutput,
705707) CodeGenError!Result {
706 const comp = bin_file.comp;
707 const gpa = comp.gpa;
708 const zcu = comp.module.?;
708 const zcu = pt.zcu;
709 const comp = zcu.comp;
710 const gpa = zcu.gpa;
709711 const ip = &zcu.intern_pool;
710712 const func = zcu.funcInfo(func_index);
711713 const fn_owner_decl = zcu.declPtr(func.owner_decl);
......@@ -726,6 +728,7 @@ pub fn generate(
726728 var function = Func{
727729 .gpa = gpa,
728730 .air = air,
731 .pt = pt,
729732 .mod = mod,
730733 .liveness = liveness,
731734 .target = target,
......@@ -787,11 +790,11 @@ pub fn generate(
787790 function.args = call_info.args;
788791 function.ret_mcv = call_info.return_value;
789792 function.frame_allocs.set(@intFromEnum(FrameIndex.ret_addr), FrameAlloc.init(.{
790 .size = Type.usize.abiSize(zcu),
791 .alignment = Type.usize.abiAlignment(zcu).min(call_info.stack_align),
793 .size = Type.usize.abiSize(pt),
794 .alignment = Type.usize.abiAlignment(pt).min(call_info.stack_align),
792795 }));
793796 function.frame_allocs.set(@intFromEnum(FrameIndex.base_ptr), FrameAlloc.init(.{
794 .size = Type.usize.abiSize(zcu),
797 .size = Type.usize.abiSize(pt),
795798 .alignment = Alignment.min(
796799 call_info.stack_align,
797800 Alignment.fromNonzeroByteUnits(function.target.stackAlignment()),
......@@ -803,7 +806,7 @@ pub fn generate(
803806 }));
804807 function.frame_allocs.set(@intFromEnum(FrameIndex.spill_frame), FrameAlloc.init(.{
805808 .size = 0,
806 .alignment = Type.usize.abiAlignment(zcu),
809 .alignment = Type.usize.abiAlignment(pt),
807810 }));
808811
809812 function.gen() catch |err| switch (err) {
......@@ -821,9 +824,10 @@ pub fn generate(
821824 };
822825 defer mir.deinit(gpa);
823826
824 var emit = Emit{
827 var emit: Emit = .{
828 .bin_file = bin_file,
825829 .lower = .{
826 .bin_file = bin_file,
830 .pt = pt,
827831 .allocator = gpa,
828832 .mir = mir,
829833 .cc = fn_info.cc,
......@@ -875,10 +879,10 @@ fn formatWipMir(
875879 _: std.fmt.FormatOptions,
876880 writer: anytype,
877881) @TypeOf(writer).Error!void {
878 const comp = data.func.bin_file.comp;
879 const mod = comp.root_mod;
880 var lower = Lower{
881 .bin_file = data.func.bin_file,
882 const pt = data.func.pt;
883 const comp = pt.zcu.comp;
884 var lower: Lower = .{
885 .pt = pt,
882886 .allocator = data.func.gpa,
883887 .mir = .{
884888 .instructions = data.func.mir_instructions.slice(),
......@@ -889,7 +893,7 @@ fn formatWipMir(
889893 .src_loc = data.func.src_loc,
890894 .output_mode = comp.config.output_mode,
891895 .link_mode = comp.config.link_mode,
892 .pic = mod.pic,
896 .pic = comp.root_mod.pic,
893897 };
894898 var first = true;
895899 for ((lower.lowerMir(data.inst) catch |err| switch (err) {
......@@ -933,7 +937,7 @@ fn formatDecl(
933937}
934938fn fmtDecl(func: *Func, decl_index: InternPool.DeclIndex) std.fmt.Formatter(formatDecl) {
935939 return .{ .data = .{
936 .mod = func.bin_file.comp.module.?,
940 .mod = func.pt.zcu,
937941 .decl_index = decl_index,
938942 } };
939943}
......@@ -950,7 +954,7 @@ fn formatAir(
950954) @TypeOf(writer).Error!void {
951955 @import("../../print_air.zig").dumpInst(
952956 data.inst,
953 data.func.bin_file.comp.module.?,
957 data.func.pt,
954958 data.func.air,
955959 data.func.liveness,
956960 );
......@@ -1044,8 +1048,9 @@ const required_features = [_]Target.riscv.Feature{
10441048};
10451049
10461050fn gen(func: *Func) !void {
1047 const mod = func.bin_file.comp.module.?;
1048 const fn_info = mod.typeToFunc(func.fn_type).?;
1051 const pt = func.pt;
1052 const zcu = pt.zcu;
1053 const fn_info = zcu.typeToFunc(func.fn_type).?;
10491054
10501055 inline for (required_features) |feature| {
10511056 if (!func.hasFeature(feature)) {
......@@ -1071,7 +1076,7 @@ fn gen(func: *Func) !void {
10711076 // The address where to store the return value for the caller is in a
10721077 // register which the callee is free to clobber. Therefore, we purposely
10731078 // spill it to stack immediately.
1074 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(Type.usize, mod));
1079 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(Type.usize, pt));
10751080 try func.genSetMem(
10761081 .{ .frame = frame_index },
10771082 0,
......@@ -1205,7 +1210,8 @@ fn gen(func: *Func) !void {
12051210}
12061211
12071212fn genBody(func: *Func, body: []const Air.Inst.Index) InnerError!void {
1208 const zcu = func.bin_file.comp.module.?;
1213 const pt = func.pt;
1214 const zcu = pt.zcu;
12091215 const ip = &zcu.intern_pool;
12101216 const air_tags = func.air.instructions.items(.tag);
12111217
......@@ -1672,44 +1678,46 @@ fn ensureProcessDeathCapacity(func: *Func, additional_count: usize) !void {
16721678}
16731679
16741680fn memSize(func: *Func, ty: Type) Memory.Size {
1675 const mod = func.bin_file.comp.module.?;
1676 return switch (ty.zigTypeTag(mod)) {
1681 const pt = func.pt;
1682 const zcu = pt.zcu;
1683 return switch (ty.zigTypeTag(zcu)) {
16771684 .Float => Memory.Size.fromBitSize(ty.floatBits(func.target.*)),
1678 else => Memory.Size.fromByteSize(ty.abiSize(mod)),
1685 else => Memory.Size.fromByteSize(ty.abiSize(pt)),
16791686 };
16801687}
16811688
16821689fn splitType(func: *Func, ty: Type) ![2]Type {
1683 const zcu = func.bin_file.comp.module.?;
1684 const classes = mem.sliceTo(&abi.classifySystem(ty, zcu), .none);
1690 const pt = func.pt;
1691 const classes = mem.sliceTo(&abi.classifySystem(ty, pt), .none);
16851692 var parts: [2]Type = undefined;
16861693 if (classes.len == 2) for (&parts, classes, 0..) |*part, class, part_i| {
16871694 part.* = switch (class) {
16881695 .integer => switch (part_i) {
16891696 0 => Type.u64,
16901697 1 => part: {
1691 const elem_size = ty.abiAlignment(zcu).minStrict(.@"8").toByteUnits().?;
1692 const elem_ty = try zcu.intType(.unsigned, @intCast(elem_size * 8));
1693 break :part switch (@divExact(ty.abiSize(zcu) - 8, elem_size)) {
1698 const elem_size = ty.abiAlignment(pt).minStrict(.@"8").toByteUnits().?;
1699 const elem_ty = try pt.intType(.unsigned, @intCast(elem_size * 8));
1700 break :part switch (@divExact(ty.abiSize(pt) - 8, elem_size)) {
16941701 1 => elem_ty,
1695 else => |len| try zcu.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
1702 else => |len| try pt.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
16961703 };
16971704 },
16981705 else => unreachable,
16991706 },
17001707 else => return func.fail("TODO: splitType class {}", .{class}),
17011708 };
1702 } else if (parts[0].abiSize(zcu) + parts[1].abiSize(zcu) == ty.abiSize(zcu)) return parts;
1703 return func.fail("TODO implement splitType for {}", .{ty.fmt(zcu)});
1709 } else if (parts[0].abiSize(pt) + parts[1].abiSize(pt) == ty.abiSize(pt)) return parts;
1710 return func.fail("TODO implement splitType for {}", .{ty.fmt(pt)});
17041711}
17051712
17061713/// Truncates the value in the register in place.
17071714/// Clobbers any remaining bits.
17081715fn truncateRegister(func: *Func, ty: Type, reg: Register) !void {
1709 const mod = func.bin_file.comp.module.?;
1710 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{
1716 const pt = func.pt;
1717 const zcu = pt.zcu;
1718 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
17111719 .signedness = .unsigned,
1712 .bits = @intCast(ty.bitSize(mod)),
1720 .bits = @intCast(ty.bitSize(pt)),
17131721 };
17141722 const shift = math.cast(u6, 64 - int_info.bits % 64) orelse return;
17151723 switch (int_info.signedness) {
......@@ -1780,7 +1788,8 @@ fn truncateRegister(func: *Func, ty: Type, reg: Register) !void {
17801788}
17811789
17821790fn symbolIndex(func: *Func) !u32 {
1783 const zcu = func.bin_file.comp.module.?;
1791 const pt = func.pt;
1792 const zcu = pt.zcu;
17841793 const decl_index = zcu.funcOwnerDeclIndex(func.func_index);
17851794 return switch (func.bin_file.tag) {
17861795 .elf => blk: {
......@@ -1817,19 +1826,21 @@ fn allocFrameIndex(func: *Func, alloc: FrameAlloc) !FrameIndex {
18171826
18181827/// Use a pointer instruction as the basis for allocating stack memory.
18191828fn allocMemPtr(func: *Func, inst: Air.Inst.Index) !FrameIndex {
1820 const zcu = func.bin_file.comp.module.?;
1829 const pt = func.pt;
1830 const zcu = pt.zcu;
18211831 const ptr_ty = func.typeOfIndex(inst);
18221832 const val_ty = ptr_ty.childType(zcu);
18231833 return func.allocFrameIndex(FrameAlloc.init(.{
1824 .size = math.cast(u32, val_ty.abiSize(zcu)) orelse {
1825 return func.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(zcu)});
1834 .size = math.cast(u32, val_ty.abiSize(pt)) orelse {
1835 return func.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(pt)});
18261836 },
1827 .alignment = ptr_ty.ptrAlignment(zcu).max(.@"1"),
1837 .alignment = ptr_ty.ptrAlignment(pt).max(.@"1"),
18281838 }));
18291839}
18301840
18311841fn typeRegClass(func: *Func, ty: Type) abi.RegisterClass {
1832 const zcu = func.bin_file.comp.module.?;
1842 const pt = func.pt;
1843 const zcu = pt.zcu;
18331844 return switch (ty.zigTypeTag(zcu)) {
18341845 .Float => .float,
18351846 .Vector => @panic("TODO: typeRegClass for Vectors"),
......@@ -1838,7 +1849,8 @@ fn typeRegClass(func: *Func, ty: Type) abi.RegisterClass {
18381849}
18391850
18401851fn regGeneralClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
1841 const zcu = func.bin_file.comp.module.?;
1852 const pt = func.pt;
1853 const zcu = pt.zcu;
18421854 return switch (ty.zigTypeTag(zcu)) {
18431855 .Float => abi.Registers.Float.general_purpose,
18441856 .Vector => @panic("TODO: regGeneralClassForType for Vectors"),
......@@ -1847,7 +1859,8 @@ fn regGeneralClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet
18471859}
18481860
18491861fn regTempClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
1850 const zcu = func.bin_file.comp.module.?;
1862 const pt = func.pt;
1863 const zcu = pt.zcu;
18511864 return switch (ty.zigTypeTag(zcu)) {
18521865 .Float => abi.Registers.Float.temporary,
18531866 .Vector => @panic("TODO: regTempClassForType for Vectors"),
......@@ -1856,13 +1869,13 @@ fn regTempClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
18561869}
18571870
18581871fn allocRegOrMem(func: *Func, elem_ty: Type, inst: ?Air.Inst.Index, reg_ok: bool) !MCValue {
1859 const zcu = func.bin_file.comp.module.?;
1872 const pt = func.pt;
18601873
1861 const abi_size = math.cast(u32, elem_ty.abiSize(zcu)) orelse {
1862 return func.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(zcu)});
1874 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1875 return func.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
18631876 };
18641877
1865 const min_size: u32 = switch (elem_ty.zigTypeTag(zcu)) {
1878 const min_size: u32 = switch (elem_ty.zigTypeTag(pt.zcu)) {
18661879 .Float => 4,
18671880 .Vector => @panic("allocRegOrMem Vector"),
18681881 else => 8,
......@@ -1874,7 +1887,7 @@ fn allocRegOrMem(func: *Func, elem_ty: Type, inst: ?Air.Inst.Index, reg_ok: bool
18741887 }
18751888 }
18761889
1877 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(elem_ty, zcu));
1890 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(elem_ty, pt));
18781891 return .{ .load_frame = .{ .index = frame_index } };
18791892}
18801893
......@@ -1955,7 +1968,7 @@ pub fn spillInstruction(func: *Func, reg: Register, inst: Air.Inst.Index) !void
19551968/// allocated. A second call to `copyToTmpRegister` may return the same register.
19561969/// This can have a side effect of spilling instructions to the stack to free up a register.
19571970fn copyToTmpRegister(func: *Func, ty: Type, mcv: MCValue) !Register {
1958 log.debug("copyToTmpRegister ty: {}", .{ty.fmt(func.bin_file.comp.module.?)});
1971 log.debug("copyToTmpRegister ty: {}", .{ty.fmt(func.pt)});
19591972 const reg = try func.register_manager.allocReg(null, func.regTempClassForType(ty));
19601973 try func.genSetReg(ty, reg, mcv);
19611974 return reg;
......@@ -2004,7 +2017,8 @@ fn airFpext(func: *Func, inst: Air.Inst.Index) !void {
20042017}
20052018
20062019fn airIntCast(func: *Func, inst: Air.Inst.Index) !void {
2007 const zcu = func.bin_file.comp.module.?;
2020 const pt = func.pt;
2021 const zcu = pt.zcu;
20082022 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20092023 const src_ty = func.typeOf(ty_op.operand);
20102024 const dst_ty = func.typeOfIndex(inst);
......@@ -2040,7 +2054,7 @@ fn airIntCast(func: *Func, inst: Air.Inst.Index) !void {
20402054
20412055 break :result dst_mcv;
20422056 } orelse return func.fail("TODO: implement airIntCast from {} to {}", .{
2043 src_ty.fmt(zcu), dst_ty.fmt(zcu),
2057 src_ty.fmt(pt), dst_ty.fmt(pt),
20442058 });
20452059
20462060 return func.finishAir(inst, result, .{ ty_op.operand, .none, .none });
......@@ -2067,7 +2081,8 @@ fn airIntFromBool(func: *Func, inst: Air.Inst.Index) !void {
20672081fn airNot(func: *Func, inst: Air.Inst.Index) !void {
20682082 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20692083 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
2070 const zcu = func.bin_file.comp.module.?;
2084 const pt = func.pt;
2085 const zcu = pt.zcu;
20712086
20722087 const operand = try func.resolveInst(ty_op.operand);
20732088 const ty = func.typeOf(ty_op.operand);
......@@ -2106,12 +2121,12 @@ fn airNot(func: *Func, inst: Air.Inst.Index) !void {
21062121}
21072122
21082123fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
2109 const zcu = func.bin_file.comp.module.?;
2124 const pt = func.pt;
21102125 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
21112126 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
21122127
21132128 const slice_ty = func.typeOfIndex(inst);
2114 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, zcu));
2129 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
21152130
21162131 const ptr_ty = func.typeOf(bin_op.lhs);
21172132 try func.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, .{ .air_ref = bin_op.lhs });
......@@ -2119,7 +2134,7 @@ fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
21192134 const len_ty = func.typeOf(bin_op.rhs);
21202135 try func.genSetMem(
21212136 .{ .frame = frame_index },
2122 @intCast(ptr_ty.abiSize(zcu)),
2137 @intCast(ptr_ty.abiSize(pt)),
21232138 len_ty,
21242139 .{ .air_ref = bin_op.rhs },
21252140 );
......@@ -2129,14 +2144,15 @@ fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
21292144}
21302145
21312146fn airBinOp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
2132 const zcu = func.bin_file.comp.module.?;
2147 const pt = func.pt;
2148 const zcu = pt.zcu;
21332149 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
21342150 const dst_mcv = try func.binOp(inst, tag, bin_op.lhs, bin_op.rhs);
21352151
21362152 const dst_ty = func.typeOfIndex(inst);
21372153 if (dst_ty.isAbiInt(zcu)) {
2138 const abi_size: u32 = @intCast(dst_ty.abiSize(zcu));
2139 const bit_size: u32 = @intCast(dst_ty.bitSize(zcu));
2154 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
2155 const bit_size: u32 = @intCast(dst_ty.bitSize(pt));
21402156 if (abi_size * 8 > bit_size) {
21412157 const dst_lock = switch (dst_mcv) {
21422158 .register => |dst_reg| func.register_manager.lockRegAssumeUnused(dst_reg),
......@@ -2150,7 +2166,7 @@ fn airBinOp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
21502166 const tmp_reg, const tmp_lock = try func.allocReg(.int);
21512167 defer func.register_manager.unlockReg(tmp_lock);
21522168
2153 const hi_ty = try zcu.intType(.unsigned, @intCast((dst_ty.bitSize(zcu) - 1) % 64 + 1));
2169 const hi_ty = try pt.intType(.unsigned, @intCast((dst_ty.bitSize(pt) - 1) % 64 + 1));
21542170 const hi_mcv = dst_mcv.address().offset(@intCast(bit_size / 64 * 8)).deref();
21552171 try func.genSetReg(hi_ty, tmp_reg, hi_mcv);
21562172 try func.truncateRegister(dst_ty, tmp_reg);
......@@ -2170,7 +2186,7 @@ fn binOp(
21702186 rhs_air: Air.Inst.Ref,
21712187) !MCValue {
21722188 _ = maybe_inst;
2173 const zcu = func.bin_file.comp.module.?;
2189 const pt = func.pt;
21742190 const lhs_ty = func.typeOf(lhs_air);
21752191 const rhs_ty = func.typeOf(rhs_air);
21762192
......@@ -2189,7 +2205,7 @@ fn binOp(
21892205 return func.fail("binOp libcall runtime-float ops", .{});
21902206 }
21912207
2192 if (lhs_ty.bitSize(zcu) > 64) return func.fail("TODO: binOp >= 64 bits", .{});
2208 if (lhs_ty.bitSize(pt) > 64) return func.fail("TODO: binOp >= 64 bits", .{});
21932209
21942210 const lhs_mcv = try func.resolveInst(lhs_air);
21952211 const rhs_mcv = try func.resolveInst(rhs_air);
......@@ -2237,8 +2253,9 @@ fn genBinOp(
22372253 rhs_ty: Type,
22382254 dst_reg: Register,
22392255) !void {
2240 const zcu = func.bin_file.comp.module.?;
2241 const bit_size = lhs_ty.bitSize(zcu);
2256 const pt = func.pt;
2257 const zcu = pt.zcu;
2258 const bit_size = lhs_ty.bitSize(pt);
22422259 assert(bit_size <= 64);
22432260
22442261 const is_unsigned = lhs_ty.isUnsignedInt(zcu);
......@@ -2349,7 +2366,7 @@ fn genBinOp(
23492366 defer func.register_manager.unlockReg(tmp_lock);
23502367
23512368 // RISC-V has no immediate mul, so we copy the size to a temporary register
2352 const elem_size = lhs_ty.elemType2(zcu).abiSize(zcu);
2369 const elem_size = lhs_ty.elemType2(zcu).abiSize(pt);
23532370 const elem_size_reg = try func.copyToTmpRegister(Type.usize, .{ .immediate = elem_size });
23542371
23552372 try func.genBinOp(
......@@ -2613,7 +2630,8 @@ fn airPtrArithmetic(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void
26132630}
26142631
26152632fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2616 const zcu = func.bin_file.comp.module.?;
2633 const pt = func.pt;
2634 const zcu = pt.zcu;
26172635 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
26182636 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
26192637
......@@ -2632,7 +2650,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26322650 const add_result_reg_lock = func.register_manager.lockRegAssumeUnused(add_result_reg);
26332651 defer func.register_manager.unlockReg(add_result_reg_lock);
26342652
2635 const shift_amount: u6 = @intCast(Type.usize.bitSize(zcu) - int_info.bits);
2653 const shift_amount: u6 = @intCast(Type.usize.bitSize(pt) - int_info.bits);
26362654
26372655 const shift_reg, const shift_lock = try func.allocReg(.int);
26382656 defer func.register_manager.unlockReg(shift_lock);
......@@ -2663,7 +2681,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26632681
26642682 try func.genSetMem(
26652683 .{ .frame = offset.index },
2666 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, zcu))),
2684 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
26672685 lhs_ty,
26682686 add_result,
26692687 );
......@@ -2682,7 +2700,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26822700
26832701 try func.genSetMem(
26842702 .{ .frame = offset.index },
2685 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2703 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
26862704 Type.u1,
26872705 .{ .register = overflow_reg },
26882706 );
......@@ -2697,7 +2715,8 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26972715}
26982716
26992717fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2700 const zcu = func.bin_file.comp.module.?;
2718 const pt = func.pt;
2719 const zcu = pt.zcu;
27012720 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
27022721 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
27032722
......@@ -2727,7 +2746,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
27272746
27282747 try func.genSetMem(
27292748 .{ .frame = offset.index },
2730 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, zcu))),
2749 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
27312750 lhs_ty,
27322751 .{ .register = dest_reg },
27332752 );
......@@ -2757,7 +2776,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
27572776
27582777 try func.genSetMem(
27592778 .{ .frame = offset.index },
2760 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2779 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
27612780 Type.u1,
27622781 .{ .register = overflow_reg },
27632782 );
......@@ -2808,7 +2827,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28082827
28092828 try func.genSetMem(
28102829 .{ .frame = offset.index },
2811 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2830 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
28122831 Type.u1,
28132832 .{ .register = overflow_reg },
28142833 );
......@@ -2825,7 +2844,8 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28252844}
28262845
28272846fn airMulWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2828 const zcu = func.bin_file.comp.module.?;
2847 const pt = func.pt;
2848 const zcu = pt.zcu;
28292849 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
28302850 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
28312851
......@@ -2840,8 +2860,8 @@ fn airMulWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28402860 // genSetReg needs to support register_offset src_mcv for this to be true.
28412861 const result_mcv = try func.allocRegOrMem(tuple_ty, inst, false);
28422862
2843 const result_off: i32 = @intCast(tuple_ty.structFieldOffset(0, zcu));
2844 const overflow_off: i32 = @intCast(tuple_ty.structFieldOffset(1, zcu));
2863 const result_off: i32 = @intCast(tuple_ty.structFieldOffset(0, pt));
2864 const overflow_off: i32 = @intCast(tuple_ty.structFieldOffset(1, pt));
28452865
28462866 const dest_reg, const dest_lock = try func.allocReg(.int);
28472867 defer func.register_manager.unlockReg(dest_lock);
......@@ -2957,11 +2977,11 @@ fn airShlSat(func: *Func, inst: Air.Inst.Index) !void {
29572977}
29582978
29592979fn airOptionalPayload(func: *Func, inst: Air.Inst.Index) !void {
2960 const zcu = func.bin_file.comp.module.?;
2980 const pt = func.pt;
29612981 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
29622982 const result: MCValue = result: {
29632983 const pl_ty = func.typeOfIndex(inst);
2964 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
2984 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
29652985
29662986 const opt_mcv = try func.resolveInst(ty_op.operand);
29672987 if (func.reuseOperand(inst, ty_op.operand, 0, opt_mcv)) {
......@@ -2993,7 +3013,8 @@ fn airOptionalPayloadPtrSet(func: *Func, inst: Air.Inst.Index) !void {
29933013
29943014fn airUnwrapErrErr(func: *Func, inst: Air.Inst.Index) !void {
29953015 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
2996 const zcu = func.bin_file.comp.module.?;
3016 const pt = func.pt;
3017 const zcu = pt.zcu;
29973018 const err_union_ty = func.typeOf(ty_op.operand);
29983019 const err_ty = err_union_ty.errorUnionSet(zcu);
29993020 const payload_ty = err_union_ty.errorUnionPayload(zcu);
......@@ -3004,11 +3025,11 @@ fn airUnwrapErrErr(func: *Func, inst: Air.Inst.Index) !void {
30043025 break :result .{ .immediate = 0 };
30053026 }
30063027
3007 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3028 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
30083029 break :result operand;
30093030 }
30103031
3011 const err_off: u32 = @intCast(errUnionErrorOffset(payload_ty, zcu));
3032 const err_off: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
30123033
30133034 switch (operand) {
30143035 .register => |reg| {
......@@ -3052,13 +3073,14 @@ fn genUnwrapErrUnionPayloadMir(
30523073 err_union_ty: Type,
30533074 err_union: MCValue,
30543075) !MCValue {
3055 const zcu = func.bin_file.comp.module.?;
3076 const pt = func.pt;
3077 const zcu = pt.zcu;
30563078 const payload_ty = err_union_ty.errorUnionPayload(zcu);
30573079
30583080 const result: MCValue = result: {
3059 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
3081 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
30603082
3061 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, zcu));
3083 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, pt));
30623084 switch (err_union) {
30633085 .load_frame => |frame_addr| break :result .{ .load_frame = .{
30643086 .index = frame_addr.index,
......@@ -3127,11 +3149,12 @@ fn airSaveErrReturnTraceIndex(func: *Func, inst: Air.Inst.Index) !void {
31273149}
31283150
31293151fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
3130 const zcu = func.bin_file.comp.module.?;
3152 const pt = func.pt;
3153 const zcu = pt.zcu;
31313154 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31323155 const result: MCValue = result: {
31333156 const pl_ty = func.typeOf(ty_op.operand);
3134 if (!pl_ty.hasRuntimeBits(zcu)) break :result .{ .immediate = 1 };
3157 if (!pl_ty.hasRuntimeBits(pt)) break :result .{ .immediate = 1 };
31353158
31363159 const opt_ty = func.typeOfIndex(inst);
31373160 const pl_mcv = try func.resolveInst(ty_op.operand);
......@@ -3148,7 +3171,7 @@ fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
31483171 try func.genCopy(pl_ty, opt_mcv, pl_mcv);
31493172
31503173 if (!same_repr) {
3151 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(zcu));
3174 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
31523175 switch (opt_mcv) {
31533176 .load_frame => |frame_addr| try func.genSetMem(
31543177 .{ .frame = frame_addr.index },
......@@ -3167,7 +3190,8 @@ fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
31673190
31683191/// T to E!T
31693192fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
3170 const zcu = func.bin_file.comp.module.?;
3193 const pt = func.pt;
3194 const zcu = pt.zcu;
31713195 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31723196
31733197 const eu_ty = ty_op.ty.toType();
......@@ -3176,11 +3200,11 @@ fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
31763200 const operand = try func.resolveInst(ty_op.operand);
31773201
31783202 const result: MCValue = result: {
3179 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .{ .immediate = 0 };
3203 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .{ .immediate = 0 };
31803204
3181 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, zcu));
3182 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, zcu));
3183 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, zcu));
3205 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
3206 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
3207 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
31843208 try func.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, operand);
31853209 try func.genSetMem(.{ .frame = frame_index }, err_off, err_ty, .{ .immediate = 0 });
31863210 break :result .{ .load_frame = .{ .index = frame_index } };
......@@ -3191,7 +3215,8 @@ fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
31913215
31923216/// E to E!T
31933217fn airWrapErrUnionErr(func: *Func, inst: Air.Inst.Index) !void {
3194 const zcu = func.bin_file.comp.module.?;
3218 const pt = func.pt;
3219 const zcu = pt.zcu;
31953220 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31963221
31973222 const eu_ty = ty_op.ty.toType();
......@@ -3199,11 +3224,11 @@ fn airWrapErrUnionErr(func: *Func, inst: Air.Inst.Index) !void {
31993224 const err_ty = eu_ty.errorUnionSet(zcu);
32003225
32013226 const result: MCValue = result: {
3202 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result try func.resolveInst(ty_op.operand);
3227 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result try func.resolveInst(ty_op.operand);
32033228
3204 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, zcu));
3205 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, zcu));
3206 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, zcu));
3229 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
3230 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
3231 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
32073232 try func.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, .undef);
32083233 const operand = try func.resolveInst(ty_op.operand);
32093234 try func.genSetMem(.{ .frame = frame_index }, err_off, err_ty, operand);
......@@ -3327,15 +3352,16 @@ fn airPtrSlicePtrPtr(func: *Func, inst: Air.Inst.Index) !void {
33273352}
33283353
33293354fn airSliceElemVal(func: *Func, inst: Air.Inst.Index) !void {
3330 const mod = func.bin_file.comp.module.?;
3355 const pt = func.pt;
3356 const zcu = pt.zcu;
33313357 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
33323358
33333359 const result: MCValue = result: {
33343360 const elem_ty = func.typeOfIndex(inst);
3335 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
3361 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
33363362
33373363 const slice_ty = func.typeOf(bin_op.lhs);
3338 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
3364 const slice_ptr_field_type = slice_ty.slicePtrFieldType(zcu);
33393365 const elem_ptr = try func.genSliceElemPtr(bin_op.lhs, bin_op.rhs);
33403366 const dst_mcv = try func.allocRegOrMem(elem_ty, inst, false);
33413367 try func.load(dst_mcv, elem_ptr, slice_ptr_field_type);
......@@ -3352,7 +3378,8 @@ fn airSliceElemPtr(func: *Func, inst: Air.Inst.Index) !void {
33523378}
33533379
33543380fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
3355 const zcu = func.bin_file.comp.module.?;
3381 const pt = func.pt;
3382 const zcu = pt.zcu;
33563383 const slice_ty = func.typeOf(lhs);
33573384 const slice_mcv = try func.resolveInst(lhs);
33583385 const slice_mcv_lock: ?RegisterLock = switch (slice_mcv) {
......@@ -3362,7 +3389,7 @@ fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
33623389 defer if (slice_mcv_lock) |lock| func.register_manager.unlockReg(lock);
33633390
33643391 const elem_ty = slice_ty.childType(zcu);
3365 const elem_size = elem_ty.abiSize(zcu);
3392 const elem_size = elem_ty.abiSize(pt);
33663393
33673394 const index_ty = func.typeOf(rhs);
33683395 const index_mcv = try func.resolveInst(rhs);
......@@ -3394,7 +3421,8 @@ fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
33943421}
33953422
33963423fn airArrayElemVal(func: *Func, inst: Air.Inst.Index) !void {
3397 const zcu = func.bin_file.comp.module.?;
3424 const pt = func.pt;
3425 const zcu = pt.zcu;
33983426 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
33993427 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
34003428 const result_ty = func.typeOfIndex(inst);
......@@ -3406,14 +3434,14 @@ fn airArrayElemVal(func: *Func, inst: Air.Inst.Index) !void {
34063434 const index_ty = func.typeOf(bin_op.rhs);
34073435
34083436 const elem_ty = array_ty.childType(zcu);
3409 const elem_abi_size = elem_ty.abiSize(zcu);
3437 const elem_abi_size = elem_ty.abiSize(pt);
34103438
34113439 const addr_reg, const addr_reg_lock = try func.allocReg(.int);
34123440 defer func.register_manager.unlockReg(addr_reg_lock);
34133441
34143442 switch (array_mcv) {
34153443 .register => {
3416 const frame_index = try func.allocFrameIndex(FrameAlloc.initType(array_ty, zcu));
3444 const frame_index = try func.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
34173445 try func.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv);
34183446 try func.genSetReg(Type.usize, addr_reg, .{ .lea_frame = .{ .index = frame_index } });
34193447 },
......@@ -3451,7 +3479,8 @@ fn airPtrElemVal(func: *Func, inst: Air.Inst.Index) !void {
34513479}
34523480
34533481fn airPtrElemPtr(func: *Func, inst: Air.Inst.Index) !void {
3454 const zcu = func.bin_file.comp.module.?;
3482 const pt = func.pt;
3483 const zcu = pt.zcu;
34553484 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34563485 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
34573486
......@@ -3474,7 +3503,7 @@ fn airPtrElemPtr(func: *Func, inst: Air.Inst.Index) !void {
34743503 }
34753504
34763505 const elem_ty = base_ptr_ty.elemType2(zcu);
3477 const elem_abi_size = elem_ty.abiSize(zcu);
3506 const elem_abi_size = elem_ty.abiSize(pt);
34783507 const index_ty = func.typeOf(extra.rhs);
34793508 const index_mcv = try func.resolveInst(extra.rhs);
34803509 const index_lock: ?RegisterLock = switch (index_mcv) {
......@@ -3536,7 +3565,8 @@ fn airPopcount(func: *Func, inst: Air.Inst.Index) !void {
35363565}
35373566
35383567fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
3539 const zcu = func.bin_file.comp.module.?;
3568 const pt = func.pt;
3569 const zcu = pt.zcu;
35403570 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35413571 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
35423572 const ty = func.typeOf(ty_op.operand);
......@@ -3545,7 +3575,7 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
35453575
35463576 switch (scalar_ty.zigTypeTag(zcu)) {
35473577 .Int => if (ty.zigTypeTag(zcu) == .Vector) {
3548 return func.fail("TODO implement airAbs for {}", .{ty.fmt(zcu)});
3578 return func.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
35493579 } else {
35503580 const return_mcv = try func.copyToNewRegister(inst, operand);
35513581 const operand_reg = return_mcv.register;
......@@ -3615,7 +3645,7 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
36153645
36163646 break :result return_mcv;
36173647 },
3618 else => return func.fail("TODO: implement airAbs {}", .{scalar_ty.fmt(zcu)}),
3648 else => return func.fail("TODO: implement airAbs {}", .{scalar_ty.fmt(pt)}),
36193649 }
36203650
36213651 break :result .unreach;
......@@ -3626,7 +3656,8 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
36263656fn airByteSwap(func: *Func, inst: Air.Inst.Index) !void {
36273657 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
36283658 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
3629 const zcu = func.bin_file.comp.module.?;
3659 const pt = func.pt;
3660 const zcu = pt.zcu;
36303661 const ty = func.typeOf(ty_op.operand);
36313662 const operand = try func.resolveInst(ty_op.operand);
36323663
......@@ -3746,12 +3777,13 @@ fn reuseOperandAdvanced(
37463777}
37473778
37483779fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
3749 const zcu = func.bin_file.comp.module.?;
3780 const pt = func.pt;
3781 const zcu = pt.zcu;
37503782 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37513783 const elem_ty = func.typeOfIndex(inst);
37523784
37533785 const result: MCValue = result: {
3754 if (!elem_ty.hasRuntimeBits(zcu))
3786 if (!elem_ty.hasRuntimeBits(pt))
37553787 break :result .none;
37563788
37573789 const ptr = try func.resolveInst(ty_op.operand);
......@@ -3759,7 +3791,7 @@ fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
37593791 if (func.liveness.isUnused(inst) and !is_volatile)
37603792 break :result .unreach;
37613793
3762 const elem_size = elem_ty.abiSize(zcu);
3794 const elem_size = elem_ty.abiSize(pt);
37633795
37643796 const dst_mcv: MCValue = blk: {
37653797 // Pointer is 8 bytes, and if the element is more than that, we cannot reuse it.
......@@ -3778,10 +3810,11 @@ fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
37783810}
37793811
37803812fn load(func: *Func, dst_mcv: MCValue, ptr_mcv: MCValue, ptr_ty: Type) InnerError!void {
3781 const zcu = func.bin_file.comp.module.?;
3813 const pt = func.pt;
3814 const zcu = pt.zcu;
37823815 const dst_ty = ptr_ty.childType(zcu);
37833816
3784 log.debug("loading {}:{} into {}", .{ ptr_mcv, ptr_ty.fmt(zcu), dst_mcv });
3817 log.debug("loading {}:{} into {}", .{ ptr_mcv, ptr_ty.fmt(pt), dst_mcv });
37853818
37863819 switch (ptr_mcv) {
37873820 .none,
......@@ -3833,9 +3866,7 @@ fn airStore(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
38333866
38343867/// Loads `value` into the "payload" of `pointer`.
38353868fn store(func: *Func, ptr_mcv: MCValue, src_mcv: MCValue, ptr_ty: Type, src_ty: Type) !void {
3836 const zcu = func.bin_file.comp.module.?;
3837
3838 log.debug("storing {}:{} in {}:{}", .{ src_mcv, src_ty.fmt(zcu), ptr_mcv, ptr_ty.fmt(zcu) });
3869 log.debug("storing {}:{} in {}:{}", .{ src_mcv, src_ty.fmt(func.pt), ptr_mcv, ptr_ty.fmt(func.pt) });
38393870
38403871 switch (ptr_mcv) {
38413872 .none => unreachable,
......@@ -3881,7 +3912,8 @@ fn airStructFieldPtrIndex(func: *Func, inst: Air.Inst.Index, index: u8) !void {
38813912}
38823913
38833914fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
3884 const zcu = func.bin_file.comp.module.?;
3915 const pt = func.pt;
3916 const zcu = pt.zcu;
38853917 const ptr_field_ty = func.typeOfIndex(inst);
38863918 const ptr_container_ty = func.typeOf(operand);
38873919 const ptr_container_ty_info = ptr_container_ty.ptrInfo(zcu);
......@@ -3889,12 +3921,12 @@ fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, inde
38893921
38903922 const field_offset: i32 = if (zcu.typeToPackedStruct(container_ty)) |struct_obj|
38913923 if (ptr_field_ty.ptrInfo(zcu).packed_offset.host_size == 0)
3892 @divExact(zcu.structPackedFieldBitOffset(struct_obj, index) +
3924 @divExact(pt.structPackedFieldBitOffset(struct_obj, index) +
38933925 ptr_container_ty_info.packed_offset.bit_offset, 8)
38943926 else
38953927 0
38963928 else
3897 @intCast(container_ty.structFieldOffset(index, zcu));
3929 @intCast(container_ty.structFieldOffset(index, pt));
38983930
38993931 const src_mcv = try func.resolveInst(operand);
39003932 const dst_mcv = if (switch (src_mcv) {
......@@ -3906,7 +3938,8 @@ fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, inde
39063938}
39073939
39083940fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
3909 const mod = func.bin_file.comp.module.?;
3941 const pt = func.pt;
3942 const zcu = pt.zcu;
39103943
39113944 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39123945 const extra = func.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -3914,16 +3947,15 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39143947 const index = extra.field_index;
39153948
39163949 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
3917 const zcu = func.bin_file.comp.module.?;
39183950 const src_mcv = try func.resolveInst(operand);
39193951 const struct_ty = func.typeOf(operand);
39203952 const field_ty = struct_ty.structFieldType(index, zcu);
3921 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
3953 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
39223954
39233955 const field_off: u32 = switch (struct_ty.containerLayout(zcu)) {
3924 .auto, .@"extern" => @intCast(struct_ty.structFieldOffset(index, zcu) * 8),
3956 .auto, .@"extern" => @intCast(struct_ty.structFieldOffset(index, pt) * 8),
39253957 .@"packed" => if (zcu.typeToStruct(struct_ty)) |struct_type|
3926 zcu.structPackedFieldBitOffset(struct_type, index)
3958 pt.structPackedFieldBitOffset(struct_type, index)
39273959 else
39283960 0,
39293961 };
......@@ -3958,15 +3990,15 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39583990 break :result if (field_off == 0) dst_mcv else try func.copyToNewRegister(inst, dst_mcv);
39593991 },
39603992 .load_frame => {
3961 const field_abi_size: u32 = @intCast(field_ty.abiSize(mod));
3993 const field_abi_size: u32 = @intCast(field_ty.abiSize(pt));
39623994 if (field_off % 8 == 0) {
39633995 const field_byte_off = @divExact(field_off, 8);
39643996 const off_mcv = src_mcv.address().offset(@intCast(field_byte_off)).deref();
3965 const field_bit_size = field_ty.bitSize(mod);
3997 const field_bit_size = field_ty.bitSize(pt);
39663998
39673999 if (field_abi_size <= 8) {
3968 const int_ty = try mod.intType(
3969 if (field_ty.isAbiInt(mod)) field_ty.intInfo(mod).signedness else .unsigned,
4000 const int_ty = try pt.intType(
4001 if (field_ty.isAbiInt(zcu)) field_ty.intInfo(zcu).signedness else .unsigned,
39704002 @intCast(field_bit_size),
39714003 );
39724004
......@@ -3978,7 +4010,7 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39784010 break :result try func.copyToNewRegister(inst, dst_mcv);
39794011 }
39804012
3981 const container_abi_size: u32 = @intCast(struct_ty.abiSize(mod));
4013 const container_abi_size: u32 = @intCast(struct_ty.abiSize(pt));
39824014 const dst_mcv = if (field_byte_off + field_abi_size <= container_abi_size and
39834015 func.reuseOperand(inst, operand, 0, src_mcv))
39844016 off_mcv
......@@ -4014,7 +4046,8 @@ fn airFieldParentPtr(func: *Func, inst: Air.Inst.Index) !void {
40144046}
40154047
40164048fn genArgDbgInfo(func: Func, inst: Air.Inst.Index, mcv: MCValue) !void {
4017 const zcu = func.bin_file.comp.module.?;
4049 const pt = func.pt;
4050 const zcu = pt.zcu;
40184051 const arg = func.air.instructions.items(.data)[@intFromEnum(inst)].arg;
40194052 const ty = arg.ty.toType();
40204053 const owner_decl = zcu.funcOwnerDeclIndex(func.func_index);
......@@ -4139,7 +4172,8 @@ fn genCall(
41394172 arg_tys: []const Type,
41404173 args: []const MCValue,
41414174) !MCValue {
4142 const zcu = func.bin_file.comp.module.?;
4175 const pt = func.pt;
4176 const zcu = pt.zcu;
41434177
41444178 const fn_ty = switch (info) {
41454179 .air => |callee| fn_info: {
......@@ -4150,7 +4184,7 @@ fn genCall(
41504184 else => unreachable,
41514185 };
41524186 },
4153 .lib => |lib| try zcu.funcType(.{
4187 .lib => |lib| try pt.funcType(.{
41544188 .param_types = lib.param_types,
41554189 .return_type = lib.return_type,
41564190 .cc = .C,
......@@ -4208,7 +4242,7 @@ fn genCall(
42084242 try reg_locks.appendSlice(&func.register_manager.lockRegs(2, regs));
42094243 },
42104244 .indirect => |reg_off| {
4211 frame_index.* = try func.allocFrameIndex(FrameAlloc.initType(arg_ty, zcu));
4245 frame_index.* = try func.allocFrameIndex(FrameAlloc.initType(arg_ty, pt));
42124246 try func.genSetMem(.{ .frame = frame_index.* }, 0, arg_ty, src_arg);
42134247 try func.register_manager.getReg(reg_off.reg, null);
42144248 try reg_locks.append(func.register_manager.lockReg(reg_off.reg));
......@@ -4221,7 +4255,7 @@ fn genCall(
42214255 .none, .unreach => {},
42224256 .indirect => |reg_off| {
42234257 const ret_ty = Type.fromInterned(fn_info.return_type);
4224 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(ret_ty, zcu));
4258 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(ret_ty, pt));
42254259 try func.genSetReg(Type.usize, reg_off.reg, .{
42264260 .lea_frame = .{ .index = frame_index, .off = -reg_off.off },
42274261 });
......@@ -4251,7 +4285,7 @@ fn genCall(
42514285 // on linking.
42524286 switch (info) {
42534287 .air => |callee| {
4254 if (try func.air.value(callee, zcu)) |func_value| {
4288 if (try func.air.value(callee, pt)) |func_value| {
42554289 const func_key = zcu.intern_pool.indexToKey(func_value.ip_index);
42564290 switch (switch (func_key) {
42574291 else => func_key,
......@@ -4324,7 +4358,8 @@ fn genCall(
43244358}
43254359
43264360fn airRet(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
4327 const zcu = func.bin_file.comp.module.?;
4361 const pt = func.pt;
4362 const zcu = pt.zcu;
43284363 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
43294364
43304365 if (safety) {
......@@ -4394,7 +4429,8 @@ fn airRetLoad(func: *Func, inst: Air.Inst.Index) !void {
43944429
43954430fn airCmp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
43964431 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
4397 const zcu = func.bin_file.comp.module.?;
4432 const pt = func.pt;
4433 const zcu = pt.zcu;
43984434
43994435 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
44004436 const lhs_ty = func.typeOf(bin_op.lhs);
......@@ -4415,7 +4451,7 @@ fn airCmp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
44154451 .ErrorSet => Type.anyerror,
44164452 .Optional => blk: {
44174453 const payload_ty = lhs_ty.optionalChild(zcu);
4418 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
4454 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44194455 break :blk Type.u1;
44204456 } else if (lhs_ty.isPtrLikeOptional(zcu)) {
44214457 break :blk Type.usize;
......@@ -4503,7 +4539,8 @@ fn genVarDbgInfo(
45034539 mcv: MCValue,
45044540 name: [:0]const u8,
45054541) !void {
4506 const zcu = func.bin_file.comp.module.?;
4542 const pt = func.pt;
4543 const zcu = pt.zcu;
45074544 const is_ptr = switch (tag) {
45084545 .dbg_var_ptr => true,
45094546 .dbg_var_val => false,
......@@ -4595,13 +4632,14 @@ fn condBr(func: *Func, cond_ty: Type, condition: MCValue) !Mir.Inst.Index {
45954632}
45964633
45974634fn isNull(func: *Func, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MCValue {
4598 const zcu = func.bin_file.comp.module.?;
4635 const pt = func.pt;
4636 const zcu = pt.zcu;
45994637 const pl_ty = opt_ty.optionalChild(zcu);
46004638
46014639 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(zcu))
46024640 .{ .off = 0, .ty = if (pl_ty.isSlice(zcu)) pl_ty.slicePtrFieldType(zcu) else pl_ty }
46034641 else
4604 .{ .off = @intCast(pl_ty.abiSize(zcu)), .ty = Type.bool };
4642 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
46054643
46064644 const return_mcv = try func.allocRegOrMem(func.typeOfIndex(inst), inst, true);
46074645 assert(return_mcv == .register); // should not be larger 8 bytes
......@@ -4642,7 +4680,7 @@ fn isNull(func: *Func, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
46424680 return return_mcv;
46434681 }
46444682 assert(some_info.ty.ip_index == .bool_type);
4645 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(zcu));
4683 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(pt));
46464684 _ = opt_abi_size;
46474685 return func.fail("TODO: isNull some_info.off != 0 register", .{});
46484686 },
......@@ -4742,7 +4780,8 @@ fn airIsErr(func: *Func, inst: Air.Inst.Index) !void {
47424780}
47434781
47444782fn airIsErrPtr(func: *Func, inst: Air.Inst.Index) !void {
4745 const zcu = func.bin_file.comp.module.?;
4783 const pt = func.pt;
4784 const zcu = pt.zcu;
47464785 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
47474786 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
47484787 const operand_ptr = try func.resolveInst(un_op);
......@@ -4768,10 +4807,11 @@ fn airIsErrPtr(func: *Func, inst: Air.Inst.Index) !void {
47684807/// Result is in the return register.
47694808fn isErr(func: *Func, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MCValue {
47704809 _ = maybe_inst;
4771 const zcu = func.bin_file.comp.module.?;
4810 const pt = func.pt;
4811 const zcu = pt.zcu;
47724812 const err_ty = eu_ty.errorUnionSet(zcu);
47734813 if (err_ty.errorSetIsEmpty(zcu)) return MCValue{ .immediate = 0 }; // always false
4774 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(zcu), zcu));
4814 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(zcu), pt));
47754815
47764816 const return_reg, const return_lock = try func.allocReg(.int);
47774817 defer func.register_manager.unlockReg(return_lock);
......@@ -4858,7 +4898,8 @@ fn isNonErr(func: *Func, inst: Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MC
48584898}
48594899
48604900fn airIsNonErrPtr(func: *Func, inst: Air.Inst.Index) !void {
4861 const zcu = func.bin_file.comp.module.?;
4901 const pt = func.pt;
4902 const zcu = pt.zcu;
48624903 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48634904 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
48644905 const operand_ptr = try func.resolveInst(un_op);
......@@ -5063,12 +5104,12 @@ fn performReloc(func: *Func, inst: Mir.Inst.Index) void {
50635104}
50645105
50655106fn airBr(func: *Func, inst: Air.Inst.Index) !void {
5066 const mod = func.bin_file.comp.module.?;
5107 const pt = func.pt;
50675108 const br = func.air.instructions.items(.data)[@intFromEnum(inst)].br;
50685109
50695110 const block_ty = func.typeOfIndex(br.block_inst);
50705111 const block_unused =
5071 !block_ty.hasRuntimeBitsIgnoreComptime(mod) or func.liveness.isUnused(br.block_inst);
5112 !block_ty.hasRuntimeBitsIgnoreComptime(pt) or func.liveness.isUnused(br.block_inst);
50725113 const block_tracking = func.inst_tracking.getPtr(br.block_inst).?;
50735114 const block_data = func.blocks.getPtr(br.block_inst).?;
50745115 const first_br = block_data.relocs.items.len == 0;
......@@ -5288,8 +5329,6 @@ fn airAsm(func: *Func, inst: Air.Inst.Index) !void {
52885329
52895330/// Sets the value of `dst_mcv` to the value of `src_mcv`.
52905331fn genCopy(func: *Func, ty: Type, dst_mcv: MCValue, src_mcv: MCValue) !void {
5291 const zcu = func.bin_file.comp.module.?;
5292
52935332 // There isn't anything to store
52945333 if (dst_mcv == .none) return;
52955334
......@@ -5362,7 +5401,7 @@ fn genCopy(func: *Func, ty: Type, dst_mcv: MCValue, src_mcv: MCValue) !void {
53625401 } },
53635402 else => unreachable,
53645403 });
5365 part_disp += @intCast(dst_ty.abiSize(zcu));
5404 part_disp += @intCast(dst_ty.abiSize(func.pt));
53665405 }
53675406 },
53685407 else => return func.fail("TODO: genCopy to {s} from {s}", .{ @tagName(dst_mcv), @tagName(src_mcv) }),
......@@ -5555,8 +5594,9 @@ fn genInlineMemset(
55555594
55565595/// Sets the value of `src_mcv` into `reg`. Assumes you have a lock on it.
55575596fn genSetReg(func: *Func, ty: Type, reg: Register, src_mcv: MCValue) InnerError!void {
5558 const zcu = func.bin_file.comp.module.?;
5559 const abi_size: u32 = @intCast(ty.abiSize(zcu));
5597 const pt = func.pt;
5598 const zcu = pt.zcu;
5599 const abi_size: u32 = @intCast(ty.abiSize(pt));
55605600
55615601 if (abi_size > 8) return std.debug.panic("tried to set reg with size {}", .{abi_size});
55625602
......@@ -5784,8 +5824,8 @@ fn genSetMem(
57845824 ty: Type,
57855825 src_mcv: MCValue,
57865826) InnerError!void {
5787 const mod = func.bin_file.comp.module.?;
5788 const abi_size: u32 = @intCast(ty.abiSize(mod));
5827 const pt = func.pt;
5828 const abi_size: u32 = @intCast(ty.abiSize(pt));
57895829 const dst_ptr_mcv: MCValue = switch (base) {
57905830 .reg => |base_reg| .{ .register_offset = .{ .reg = base_reg, .off = disp } },
57915831 .frame => |base_frame_index| .{ .lea_frame = .{ .index = base_frame_index, .off = disp } },
......@@ -5883,7 +5923,7 @@ fn genSetMem(
58835923 var part_disp: i32 = disp;
58845924 for (try func.splitType(ty), src_regs) |src_ty, src_reg| {
58855925 try func.genSetMem(base, part_disp, src_ty, .{ .register = src_reg });
5886 part_disp += @intCast(src_ty.abiSize(mod));
5926 part_disp += @intCast(src_ty.abiSize(pt));
58875927 }
58885928 },
58895929 .immediate => {
......@@ -5914,7 +5954,8 @@ fn airIntFromPtr(func: *Func, inst: Air.Inst.Index) !void {
59145954}
59155955
59165956fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
5917 const zcu = func.bin_file.comp.module.?;
5957 const pt = func.pt;
5958 const zcu = pt.zcu;
59185959
59195960 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59205961 const result = if (func.liveness.isUnused(inst)) .unreach else result: {
......@@ -5926,10 +5967,10 @@ fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
59265967 const src_lock = if (src_mcv.getReg()) |reg| func.register_manager.lockReg(reg) else null;
59275968 defer if (src_lock) |lock| func.register_manager.unlockReg(lock);
59285969
5929 const dst_mcv = if (dst_ty.abiSize(zcu) <= src_ty.abiSize(zcu) and
5970 const dst_mcv = if (dst_ty.abiSize(pt) <= src_ty.abiSize(pt) and
59305971 func.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: {
59315972 const dst_mcv = try func.allocRegOrMem(dst_ty, inst, true);
5932 try func.genCopy(switch (math.order(dst_ty.abiSize(zcu), src_ty.abiSize(zcu))) {
5973 try func.genCopy(switch (math.order(dst_ty.abiSize(pt), src_ty.abiSize(pt))) {
59335974 .lt => dst_ty,
59345975 .eq => if (!dst_mcv.isMemory() or src_mcv.isMemory()) dst_ty else src_ty,
59355976 .gt => src_ty,
......@@ -5940,17 +5981,18 @@ fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
59405981 if (dst_ty.isAbiInt(zcu) and src_ty.isAbiInt(zcu) and
59415982 dst_ty.intInfo(zcu).signedness == src_ty.intInfo(zcu).signedness) break :result dst_mcv;
59425983
5943 const abi_size = dst_ty.abiSize(zcu);
5944 const bit_size = dst_ty.bitSize(zcu);
5984 const abi_size = dst_ty.abiSize(pt);
5985 const bit_size = dst_ty.bitSize(pt);
59455986 if (abi_size * 8 <= bit_size) break :result dst_mcv;
59465987
5947 return func.fail("TODO: airBitCast {} to {}", .{ src_ty.fmt(zcu), dst_ty.fmt(zcu) });
5988 return func.fail("TODO: airBitCast {} to {}", .{ src_ty.fmt(pt), dst_ty.fmt(pt) });
59485989 };
59495990 return func.finishAir(inst, result, .{ ty_op.operand, .none, .none });
59505991}
59515992
59525993fn airArrayToSlice(func: *Func, inst: Air.Inst.Index) !void {
5953 const zcu = func.bin_file.comp.module.?;
5994 const pt = func.pt;
5995 const zcu = pt.zcu;
59545996 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59555997
59565998 const slice_ty = func.typeOfIndex(inst);
......@@ -5959,11 +6001,11 @@ fn airArrayToSlice(func: *Func, inst: Air.Inst.Index) !void {
59596001 const array_ty = ptr_ty.childType(zcu);
59606002 const array_len = array_ty.arrayLen(zcu);
59616003
5962 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, zcu));
6004 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
59636005 try func.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, ptr);
59646006 try func.genSetMem(
59656007 .{ .frame = frame_index },
5966 @intCast(ptr_ty.abiSize(zcu)),
6008 @intCast(ptr_ty.abiSize(pt)),
59676009 Type.usize,
59686010 .{ .immediate = array_len },
59696011 );
......@@ -6015,7 +6057,8 @@ fn airAtomicStore(func: *Func, inst: Air.Inst.Index, order: std.builtin.AtomicOr
60156057}
60166058
60176059fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
6018 const zcu = func.bin_file.comp.module.?;
6060 const pt = func.pt;
6061 const zcu = pt.zcu;
60196062 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
60206063
60216064 result: {
......@@ -6037,7 +6080,7 @@ fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
60376080 };
60386081 defer if (src_val_lock) |lock| func.register_manager.unlockReg(lock);
60396082
6040 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(zcu));
6083 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(pt));
60416084
60426085 if (elem_abi_size == 1) {
60436086 const ptr: MCValue = switch (dst_ptr_ty.ptrSize(zcu)) {
......@@ -6068,7 +6111,7 @@ fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
60686111 switch (dst_ptr_ty.ptrSize(zcu)) {
60696112 .Slice => return func.fail("TODO: airMemset Slices", .{}),
60706113 .One => {
6071 const elem_ptr_ty = try zcu.singleMutPtrType(elem_ty);
6114 const elem_ptr_ty = try pt.singleMutPtrType(elem_ty);
60726115
60736116 const len = dst_ptr_ty.childType(zcu).arrayLen(zcu);
60746117
......@@ -6110,7 +6153,8 @@ fn airTagName(func: *Func, inst: Air.Inst.Index) !void {
61106153}
61116154
61126155fn airErrorName(func: *Func, inst: Air.Inst.Index) !void {
6113 const zcu = func.bin_file.comp.module.?;
6156 const pt = func.pt;
6157 const zcu = pt.zcu;
61146158 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61156159
61166160 const err_ty = func.typeOf(un_op);
......@@ -6126,7 +6170,7 @@ fn airErrorName(func: *Func, inst: Air.Inst.Index) !void {
61266170 // this is now the base address of the error name table
61276171 const lazy_sym = link.File.LazySymbol.initDecl(.const_data, null, zcu);
61286172 if (func.bin_file.cast(link.File.Elf)) |elf_file| {
6129 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
6173 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
61306174 return func.fail("{s} creating lazy symbol", .{@errorName(err)});
61316175 const sym = elf_file.symbol(sym_index);
61326176 try func.genSetReg(Type.usize, addr_reg, .{ .load_symbol = .{ .sym = sym.esym_index } });
......@@ -6239,7 +6283,8 @@ fn airReduce(func: *Func, inst: Air.Inst.Index) !void {
62396283}
62406284
62416285fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
6242 const zcu = func.bin_file.comp.module.?;
6286 const pt = func.pt;
6287 const zcu = pt.zcu;
62436288 const result_ty = func.typeOfIndex(inst);
62446289 const len: usize = @intCast(result_ty.arrayLen(zcu));
62456290 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6248,21 +6293,21 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62486293 const result: MCValue = result: {
62496294 switch (result_ty.zigTypeTag(zcu)) {
62506295 .Struct => {
6251 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, zcu));
6296 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
62526297 if (result_ty.containerLayout(zcu) == .@"packed") {
62536298 const struct_obj = zcu.typeToStruct(result_ty).?;
62546299 try func.genInlineMemset(
62556300 .{ .lea_frame = .{ .index = frame_index } },
62566301 .{ .immediate = 0 },
6257 .{ .immediate = result_ty.abiSize(zcu) },
6302 .{ .immediate = result_ty.abiSize(pt) },
62586303 );
62596304
62606305 for (elements, 0..) |elem, elem_i_usize| {
62616306 const elem_i: u32 = @intCast(elem_i_usize);
6262 if ((try result_ty.structFieldValueComptime(zcu, elem_i)) != null) continue;
6307 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
62636308
62646309 const elem_ty = result_ty.structFieldType(elem_i, zcu);
6265 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(zcu));
6310 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(pt));
62666311 if (elem_bit_size > 64) {
62676312 return func.fail(
62686313 "TODO airAggregateInit implement packed structs with large fields",
......@@ -6270,9 +6315,9 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62706315 );
62716316 }
62726317
6273 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(zcu));
6318 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
62746319 const elem_abi_bits = elem_abi_size * 8;
6275 const elem_off = zcu.structPackedFieldBitOffset(struct_obj, elem_i);
6320 const elem_off = pt.structPackedFieldBitOffset(struct_obj, elem_i);
62766321 const elem_byte_off: i32 = @intCast(elem_off / elem_abi_bits * elem_abi_size);
62776322 const elem_bit_off = elem_off % elem_abi_bits;
62786323 const elem_mcv = try func.resolveInst(elem);
......@@ -6293,10 +6338,10 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62936338 return func.fail("TODO: airAggregateInit packed structs", .{});
62946339 }
62956340 } else for (elements, 0..) |elem, elem_i| {
6296 if ((try result_ty.structFieldValueComptime(zcu, elem_i)) != null) continue;
6341 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
62976342
62986343 const elem_ty = result_ty.structFieldType(elem_i, zcu);
6299 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, zcu));
6344 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, pt));
63006345 const elem_mcv = try func.resolveInst(elem);
63016346 try func.genSetMem(.{ .frame = frame_index }, elem_off, elem_ty, elem_mcv);
63026347 }
......@@ -6304,8 +6349,8 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
63046349 },
63056350 .Array => {
63066351 const elem_ty = result_ty.childType(zcu);
6307 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, zcu));
6308 const elem_size: u32 = @intCast(elem_ty.abiSize(zcu));
6352 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
6353 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
63096354
63106355 for (elements, 0..) |elem, elem_i| {
63116356 const elem_mcv = try func.resolveInst(elem);
......@@ -6325,7 +6370,7 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
63256370 );
63266371 break :result .{ .load_frame = .{ .index = frame_index } };
63276372 },
6328 else => return func.fail("TODO: airAggregate {}", .{result_ty.fmt(zcu)}),
6373 else => return func.fail("TODO: airAggregate {}", .{result_ty.fmt(pt)}),
63296374 }
63306375 };
63316376
......@@ -6364,11 +6409,11 @@ fn airMulAdd(func: *Func, inst: Air.Inst.Index) !void {
63646409}
63656410
63666411fn resolveInst(func: *Func, ref: Air.Inst.Ref) InnerError!MCValue {
6367 const zcu = func.bin_file.comp.module.?;
6412 const pt = func.pt;
63686413
63696414 // If the type has no codegen bits, no need to store it.
63706415 const inst_ty = func.typeOf(ref);
6371 if (!inst_ty.hasRuntimeBits(zcu))
6416 if (!inst_ty.hasRuntimeBits(pt))
63726417 return .none;
63736418
63746419 const mcv = if (ref.toIndex()) |inst| mcv: {
......@@ -6394,9 +6439,11 @@ fn getResolvedInstValue(func: *Func, inst: Air.Inst.Index) *InstTracking {
63946439}
63956440
63966441fn genTypedValue(func: *Func, val: Value) InnerError!MCValue {
6397 const zcu = func.bin_file.comp.module.?;
6442 const pt = func.pt;
6443 const zcu = pt.zcu;
63986444 const result = try codegen.genTypedValue(
63996445 func.bin_file,
6446 pt,
64006447 func.src_loc,
64016448 val,
64026449 zcu.funcOwnerDeclIndex(func.func_index),
......@@ -6438,7 +6485,8 @@ fn resolveCallingConventionValues(
64386485 fn_info: InternPool.Key.FuncType,
64396486 var_args: []const Type,
64406487) !CallMCValues {
6441 const zcu = func.bin_file.comp.module.?;
6488 const pt = func.pt;
6489 const zcu = pt.zcu;
64426490 const ip = &zcu.intern_pool;
64436491
64446492 const param_types = try func.gpa.alloc(Type, fn_info.param_types.len + var_args.len);
......@@ -6481,14 +6529,14 @@ fn resolveCallingConventionValues(
64816529 // Return values
64826530 if (ret_ty.zigTypeTag(zcu) == .NoReturn) {
64836531 result.return_value = InstTracking.init(.unreach);
6484 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6532 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
64856533 result.return_value = InstTracking.init(.none);
64866534 } else {
64876535 var ret_tracking: [2]InstTracking = undefined;
64886536 var ret_tracking_i: usize = 0;
64896537 var ret_float_reg_i: usize = 0;
64906538
6491 const classes = mem.sliceTo(&abi.classifySystem(ret_ty, zcu), .none);
6539 const classes = mem.sliceTo(&abi.classifySystem(ret_ty, pt), .none);
64926540
64936541 for (classes) |class| switch (class) {
64946542 .integer => {
......@@ -6521,7 +6569,7 @@ fn resolveCallingConventionValues(
65216569 };
65226570
65236571 result.return_value = switch (ret_tracking_i) {
6524 else => return func.fail("ty {} took {} tracking return indices", .{ ret_ty.fmt(zcu), ret_tracking_i }),
6572 else => return func.fail("ty {} took {} tracking return indices", .{ ret_ty.fmt(pt), ret_tracking_i }),
65256573 1 => ret_tracking[0],
65266574 2 => InstTracking.init(.{ .register_pair = .{
65276575 ret_tracking[0].short.register, ret_tracking[1].short.register,
......@@ -6532,7 +6580,7 @@ fn resolveCallingConventionValues(
65326580 var param_float_reg_i: usize = 0;
65336581
65346582 for (param_types, result.args) |ty, *arg| {
6535 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6583 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
65366584 assert(cc == .Unspecified);
65376585 arg.* = .none;
65386586 continue;
......@@ -6541,7 +6589,7 @@ fn resolveCallingConventionValues(
65416589 var arg_mcv: [2]MCValue = undefined;
65426590 var arg_mcv_i: usize = 0;
65436591
6544 const classes = mem.sliceTo(&abi.classifySystem(ty, zcu), .none);
6592 const classes = mem.sliceTo(&abi.classifySystem(ty, pt), .none);
65456593
65466594 for (classes) |class| switch (class) {
65476595 .integer => {
......@@ -6576,7 +6624,7 @@ fn resolveCallingConventionValues(
65766624 else => return func.fail("TODO: C calling convention arg class {}", .{class}),
65776625 } else {
65786626 arg.* = switch (arg_mcv_i) {
6579 else => return func.fail("ty {} took {} tracking arg indices", .{ ty.fmt(zcu), arg_mcv_i }),
6627 else => return func.fail("ty {} took {} tracking arg indices", .{ ty.fmt(pt), arg_mcv_i }),
65806628 1 => arg_mcv[0],
65816629 2 => .{ .register_pair = .{ arg_mcv[0].register, arg_mcv[1].register } },
65826630 };
......@@ -6621,12 +6669,14 @@ fn parseRegName(name: []const u8) ?Register {
66216669}
66226670
66236671fn typeOf(func: *Func, inst: Air.Inst.Ref) Type {
6624 const zcu = func.bin_file.comp.module.?;
6672 const pt = func.pt;
6673 const zcu = pt.zcu;
66256674 return func.air.typeOf(inst, &zcu.intern_pool);
66266675}
66276676
66286677fn typeOfIndex(func: *Func, inst: Air.Inst.Index) Type {
6629 const zcu = func.bin_file.comp.module.?;
6678 const pt = func.pt;
6679 const zcu = pt.zcu;
66306680 return func.air.typeOfIndex(inst, &zcu.intern_pool);
66316681}
66326682
......@@ -6634,40 +6684,41 @@ fn hasFeature(func: *Func, feature: Target.riscv.Feature) bool {
66346684 return Target.riscv.featureSetHas(func.target.cpu.features, feature);
66356685}
66366686
6637pub fn errUnionPayloadOffset(payload_ty: Type, zcu: *Zcu) u64 {
6638 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) return 0;
6639 const payload_align = payload_ty.abiAlignment(zcu);
6640 const error_align = Type.anyerror.abiAlignment(zcu);
6641 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6687pub fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
6688 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
6689 const payload_align = payload_ty.abiAlignment(pt);
6690 const error_align = Type.anyerror.abiAlignment(pt);
6691 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
66426692 return 0;
66436693 } else {
6644 return payload_align.forward(Type.anyerror.abiSize(zcu));
6694 return payload_align.forward(Type.anyerror.abiSize(pt));
66456695 }
66466696}
66476697
6648pub fn errUnionErrorOffset(payload_ty: Type, zcu: *Zcu) u64 {
6649 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) return 0;
6650 const payload_align = payload_ty.abiAlignment(zcu);
6651 const error_align = Type.anyerror.abiAlignment(zcu);
6652 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6653 return error_align.forward(payload_ty.abiSize(zcu));
6698pub fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
6699 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
6700 const payload_align = payload_ty.abiAlignment(pt);
6701 const error_align = Type.anyerror.abiAlignment(pt);
6702 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
6703 return error_align.forward(payload_ty.abiSize(pt));
66546704 } else {
66556705 return 0;
66566706 }
66576707}
66586708
66596709fn promoteInt(func: *Func, ty: Type) Type {
6660 const mod = func.bin_file.comp.module.?;
6710 const pt = func.pt;
6711 const zcu = pt.zcu;
66616712 const int_info: InternPool.Key.IntType = switch (ty.toIntern()) {
66626713 .bool_type => .{ .signedness = .unsigned, .bits = 1 },
6663 else => if (ty.isAbiInt(mod)) ty.intInfo(mod) else return ty,
6714 else => if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else return ty,
66646715 };
66656716 for ([_]Type{
66666717 Type.c_int, Type.c_uint,
66676718 Type.c_long, Type.c_ulong,
66686719 Type.c_longlong, Type.c_ulonglong,
66696720 }) |promote_ty| {
6670 const promote_info = promote_ty.intInfo(mod);
6721 const promote_info = promote_ty.intInfo(zcu);
66716722 if (int_info.signedness == .signed and promote_info.signedness == .unsigned) continue;
66726723 if (int_info.bits + @intFromBool(int_info.signedness == .unsigned and
66736724 promote_info.signedness == .signed) <= promote_info.bits) return promote_ty;
src/arch/riscv64/Emit.zig+3-2
......@@ -1,5 +1,6 @@
11//! This file contains the functionality for emitting RISC-V MIR as machine code
22
3bin_file: *link.File,
34lower: Lower,
45debug_output: DebugInfoOutput,
56code: *std.ArrayList(u8),
......@@ -48,7 +49,7 @@ pub fn emitMir(emit: *Emit) Error!void {
4849 .Lib => emit.lower.link_mode == .static,
4950 };
5051
51 if (emit.lower.bin_file.cast(link.File.Elf)) |elf_file| {
52 if (emit.bin_file.cast(link.File.Elf)) |elf_file| {
5253 const atom_ptr = elf_file.symbol(symbol.atom_index).atom(elf_file).?;
5354 const sym_index = elf_file.zigObjectPtr().?.symbol(symbol.sym_index);
5455 const sym = elf_file.symbol(sym_index);
......@@ -77,7 +78,7 @@ pub fn emitMir(emit: *Emit) Error!void {
7778 } else return emit.fail("TODO: load_symbol_reloc non-ELF", .{});
7879 },
7980 .call_extern_fn_reloc => |symbol| {
80 if (emit.lower.bin_file.cast(link.File.Elf)) |elf_file| {
81 if (emit.bin_file.cast(link.File.Elf)) |elf_file| {
8182 const atom_ptr = elf_file.symbol(symbol.atom_index).atom(elf_file).?;
8283
8384 const r_type: u32 = @intFromEnum(std.elf.R_RISCV.CALL_PLT);
src/arch/riscv64/Lower.zig+6-6
......@@ -1,6 +1,6 @@
11//! This file contains the functionality for lowering RISC-V MIR to Instructions
22
3bin_file: *link.File,
3pt: Zcu.PerThread,
44output_mode: std.builtin.OutputMode,
55link_mode: std.builtin.LinkMode,
66pic: bool,
......@@ -44,7 +44,7 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct {
4444 insts: []const Instruction,
4545 relocs: []const Reloc,
4646} {
47 const zcu = lower.bin_file.comp.module.?;
47 const pt = lower.pt;
4848
4949 lower.result_insts = undefined;
5050 lower.result_relocs = undefined;
......@@ -243,11 +243,11 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct {
243243
244244 const class = rs1.class();
245245 const ty = compare.ty;
246 const size = std.math.ceilPowerOfTwo(u64, ty.bitSize(zcu)) catch {
247 return lower.fail("pseudo_compare size {}", .{ty.bitSize(zcu)});
246 const size = std.math.ceilPowerOfTwo(u64, ty.bitSize(pt)) catch {
247 return lower.fail("pseudo_compare size {}", .{ty.bitSize(pt)});
248248 };
249249
250 const is_unsigned = ty.isUnsignedInt(zcu);
250 const is_unsigned = ty.isUnsignedInt(pt.zcu);
251251
252252 const less_than: Encoding.Mnemonic = if (is_unsigned) .sltu else .slt;
253253
......@@ -502,7 +502,7 @@ pub fn fail(lower: *Lower, comptime format: []const u8, args: anytype) Error {
502502}
503503
504504fn hasFeature(lower: *Lower, feature: std.Target.riscv.Feature) bool {
505 const target = lower.bin_file.comp.module.?.getTarget();
505 const target = lower.pt.zcu.getTarget();
506506 const features = target.cpu.features;
507507 return std.Target.riscv.featureSetHas(features, feature);
508508}
src/arch/riscv64/abi.zig+28-27
......@@ -9,15 +9,15 @@ const assert = std.debug.assert;
99
1010pub const Class = enum { memory, byval, integer, double_integer, fields };
1111
12pub fn classifyType(ty: Type, mod: *Zcu) Class {
13 const target = mod.getTarget();
14 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(mod));
12pub fn classifyType(ty: Type, pt: Zcu.PerThread) Class {
13 const target = pt.zcu.getTarget();
14 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(pt));
1515
1616 const max_byval_size = target.ptrBitWidth() * 2;
17 switch (ty.zigTypeTag(mod)) {
17 switch (ty.zigTypeTag(pt.zcu)) {
1818 .Struct => {
19 const bit_size = ty.bitSize(mod);
20 if (ty.containerLayout(mod) == .@"packed") {
19 const bit_size = ty.bitSize(pt);
20 if (ty.containerLayout(pt.zcu) == .@"packed") {
2121 if (bit_size > max_byval_size) return .memory;
2222 return .byval;
2323 }
......@@ -25,12 +25,12 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
2525 if (std.Target.riscv.featureSetHas(target.cpu.features, .d)) fields: {
2626 var any_fp = false;
2727 var field_count: usize = 0;
28 for (0..ty.structFieldCount(mod)) |field_index| {
29 const field_ty = ty.structFieldType(field_index, mod);
30 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
28 for (0..ty.structFieldCount(pt.zcu)) |field_index| {
29 const field_ty = ty.structFieldType(field_index, pt.zcu);
30 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
3131 if (field_ty.isRuntimeFloat())
3232 any_fp = true
33 else if (!field_ty.isAbiInt(mod))
33 else if (!field_ty.isAbiInt(pt.zcu))
3434 break :fields;
3535 field_count += 1;
3636 if (field_count > 2) break :fields;
......@@ -45,8 +45,8 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
4545 return .integer;
4646 },
4747 .Union => {
48 const bit_size = ty.bitSize(mod);
49 if (ty.containerLayout(mod) == .@"packed") {
48 const bit_size = ty.bitSize(pt);
49 if (ty.containerLayout(pt.zcu) == .@"packed") {
5050 if (bit_size > max_byval_size) return .memory;
5151 return .byval;
5252 }
......@@ -58,21 +58,21 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
5858 .Bool => return .integer,
5959 .Float => return .byval,
6060 .Int, .Enum, .ErrorSet => {
61 const bit_size = ty.bitSize(mod);
61 const bit_size = ty.bitSize(pt);
6262 if (bit_size > max_byval_size) return .memory;
6363 return .byval;
6464 },
6565 .Vector => {
66 const bit_size = ty.bitSize(mod);
66 const bit_size = ty.bitSize(pt);
6767 if (bit_size > max_byval_size) return .memory;
6868 return .integer;
6969 },
7070 .Optional => {
71 std.debug.assert(ty.isPtrLikeOptional(mod));
71 std.debug.assert(ty.isPtrLikeOptional(pt.zcu));
7272 return .byval;
7373 },
7474 .Pointer => {
75 std.debug.assert(!ty.isSlice(mod));
75 std.debug.assert(!ty.isSlice(pt.zcu));
7676 return .byval;
7777 },
7878 .ErrorUnion,
......@@ -97,18 +97,19 @@ pub const SystemClass = enum { integer, float, memory, none };
9797
9898/// There are a maximum of 8 possible return slots. Returned values are in
9999/// the beginning of the array; unused slots are filled with .none.
100pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
100pub fn classifySystem(ty: Type, pt: Zcu.PerThread) [8]SystemClass {
101 const zcu = pt.zcu;
101102 var result = [1]SystemClass{.none} ** 8;
102103 const memory_class = [_]SystemClass{
103104 .memory, .none, .none, .none,
104105 .none, .none, .none, .none,
105106 };
106 switch (ty.zigTypeTag(zcu)) {
107 switch (ty.zigTypeTag(pt.zcu)) {
107108 .Bool, .Void, .NoReturn => {
108109 result[0] = .integer;
109110 return result;
110111 },
111 .Pointer => switch (ty.ptrSize(zcu)) {
112 .Pointer => switch (ty.ptrSize(pt.zcu)) {
112113 .Slice => {
113114 result[0] = .integer;
114115 result[1] = .integer;
......@@ -120,17 +121,17 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
120121 },
121122 },
122123 .Optional => {
123 if (ty.isPtrLikeOptional(zcu)) {
124 if (ty.isPtrLikeOptional(pt.zcu)) {
124125 result[0] = .integer;
125126 return result;
126127 }
127128 result[0] = .integer;
128 if (ty.optionalChild(zcu).abiSize(zcu) == 0) return result;
129 if (ty.optionalChild(zcu).abiSize(pt) == 0) return result;
129130 result[1] = .integer;
130131 return result;
131132 },
132133 .Int, .Enum, .ErrorSet => {
133 const int_bits = ty.intInfo(zcu).bits;
134 const int_bits = ty.intInfo(pt.zcu).bits;
134135 if (int_bits <= 64) {
135136 result[0] = .integer;
136137 return result;
......@@ -155,8 +156,8 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
155156 unreachable; // support split float args
156157 },
157158 .ErrorUnion => {
158 const payload_ty = ty.errorUnionPayload(zcu);
159 const payload_bits = payload_ty.bitSize(zcu);
159 const payload_ty = ty.errorUnionPayload(pt.zcu);
160 const payload_bits = payload_ty.bitSize(pt);
160161
161162 // the error union itself
162163 result[0] = .integer;
......@@ -167,8 +168,8 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
167168 return memory_class;
168169 },
169170 .Struct => {
170 const layout = ty.containerLayout(zcu);
171 const ty_size = ty.abiSize(zcu);
171 const layout = ty.containerLayout(pt.zcu);
172 const ty_size = ty.abiSize(pt);
172173
173174 if (layout == .@"packed") {
174175 assert(ty_size <= 16);
......@@ -180,7 +181,7 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
180181 return memory_class;
181182 },
182183 .Array => {
183 const ty_size = ty.abiSize(zcu);
184 const ty_size = ty.abiSize(pt);
184185 if (ty_size <= 8) {
185186 result[0] = .integer;
186187 return result;
src/arch/sparc64/CodeGen.zig+125-95
......@@ -11,11 +11,9 @@ const Allocator = mem.Allocator;
1111const builtin = @import("builtin");
1212const link = @import("../../link.zig");
1313const Zcu = @import("../../Zcu.zig");
14/// Deprecated.
15const Module = Zcu;
1614const InternPool = @import("../../InternPool.zig");
1715const Value = @import("../../Value.zig");
18const ErrorMsg = Module.ErrorMsg;
16const ErrorMsg = Zcu.ErrorMsg;
1917const codegen = @import("../../codegen.zig");
2018const Air = @import("../../Air.zig");
2119const Mir = @import("Mir.zig");
......@@ -52,6 +50,7 @@ const RegisterView = enum(u1) {
5250};
5351
5452gpa: Allocator,
53pt: Zcu.PerThread,
5554air: Air,
5655liveness: Liveness,
5756bin_file: *link.File,
......@@ -64,7 +63,7 @@ args: []MCValue,
6463ret_mcv: MCValue,
6564fn_type: Type,
6665arg_index: usize,
67src_loc: Module.LazySrcLoc,
66src_loc: Zcu.LazySrcLoc,
6867stack_align: Alignment,
6968
7069/// MIR Instructions
......@@ -263,15 +262,16 @@ const BigTomb = struct {
263262
264263pub fn generate(
265264 lf: *link.File,
266 src_loc: Module.LazySrcLoc,
265 pt: Zcu.PerThread,
266 src_loc: Zcu.LazySrcLoc,
267267 func_index: InternPool.Index,
268268 air: Air,
269269 liveness: Liveness,
270270 code: *std.ArrayList(u8),
271271 debug_output: DebugInfoOutput,
272272) CodeGenError!Result {
273 const gpa = lf.comp.gpa;
274 const zcu = lf.comp.module.?;
273 const zcu = pt.zcu;
274 const gpa = zcu.gpa;
275275 const func = zcu.funcInfo(func_index);
276276 const fn_owner_decl = zcu.declPtr(func.owner_decl);
277277 assert(fn_owner_decl.has_tv);
......@@ -289,11 +289,12 @@ pub fn generate(
289289
290290 var function = Self{
291291 .gpa = gpa,
292 .pt = pt,
292293 .air = air,
293294 .liveness = liveness,
294295 .target = target,
295 .func_index = func_index,
296296 .bin_file = lf,
297 .func_index = func_index,
297298 .code = code,
298299 .debug_output = debug_output,
299300 .err_msg = null,
......@@ -365,7 +366,8 @@ pub fn generate(
365366}
366367
367368fn gen(self: *Self) !void {
368 const mod = self.bin_file.comp.module.?;
369 const pt = self.pt;
370 const mod = pt.zcu;
369371 const cc = self.fn_type.fnCallingConvention(mod);
370372 if (cc != .Naked) {
371373 // TODO Finish function prologue and epilogue for sparc64.
......@@ -493,7 +495,8 @@ fn gen(self: *Self) !void {
493495}
494496
495497fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
496 const mod = self.bin_file.comp.module.?;
498 const pt = self.pt;
499 const mod = pt.zcu;
497500 const ip = &mod.intern_pool;
498501 const air_tags = self.air.instructions.items(.tag);
499502
......@@ -757,7 +760,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
757760 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
758761 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
759762 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
760 const mod = self.bin_file.comp.module.?;
763 const pt = self.pt;
764 const mod = pt.zcu;
761765 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
762766 const lhs = try self.resolveInst(extra.lhs);
763767 const rhs = try self.resolveInst(extra.rhs);
......@@ -835,7 +839,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
835839}
836840
837841fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
838 const mod = self.bin_file.comp.module.?;
842 const pt = self.pt;
843 const mod = pt.zcu;
839844 const vector_ty = self.typeOfIndex(inst);
840845 const len = vector_ty.vectorLen(mod);
841846 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -869,7 +874,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
869874}
870875
871876fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
872 const mod = self.bin_file.comp.module.?;
877 const pt = self.pt;
878 const mod = pt.zcu;
873879 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
874880 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
875881 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -1006,7 +1012,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
10061012}
10071013
10081014fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1009 const mod = self.bin_file.comp.module.?;
1015 const pt = self.pt;
10101016 const arg_index = self.arg_index;
10111017 self.arg_index += 1;
10121018
......@@ -1016,8 +1022,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
10161022 const mcv = blk: {
10171023 switch (arg) {
10181024 .stack_offset => |off| {
1019 const abi_size = math.cast(u32, ty.abiSize(mod)) orelse {
1020 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(mod)});
1025 const abi_size = math.cast(u32, ty.abiSize(pt)) orelse {
1026 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(pt)});
10211027 };
10221028 const offset = off + abi_size;
10231029 break :blk MCValue{ .stack_offset = offset };
......@@ -1205,7 +1211,8 @@ fn airBreakpoint(self: *Self) !void {
12051211}
12061212
12071213fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
1208 const mod = self.bin_file.comp.module.?;
1214 const pt = self.pt;
1215 const mod = pt.zcu;
12091216 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
12101217
12111218 // We have hardware byteswapper in SPARCv9, don't let mainstream compilers mislead you.
......@@ -1228,7 +1235,7 @@ fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
12281235 if (int_info.bits == 8) break :result operand;
12291236
12301237 const abi_size = int_info.bits >> 3;
1231 const abi_align = operand_ty.abiAlignment(mod);
1238 const abi_align = operand_ty.abiAlignment(pt);
12321239 const opposite_endian_asi = switch (self.target.cpu.arch.endian()) {
12331240 Endian.big => ASI.asi_primary_little,
12341241 Endian.little => ASI.asi_primary,
......@@ -1297,7 +1304,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
12971304 const extra = self.air.extraData(Air.Call, pl_op.payload);
12981305 const args = @as([]const Air.Inst.Ref, @ptrCast(self.air.extra[extra.end .. extra.end + extra.data.args_len]));
12991306 const ty = self.typeOf(callee);
1300 const mod = self.bin_file.comp.module.?;
1307 const pt = self.pt;
1308 const mod = pt.zcu;
13011309 const fn_ty = switch (ty.zigTypeTag(mod)) {
13021310 .Fn => ty,
13031311 .Pointer => ty.childType(mod),
......@@ -1341,7 +1349,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
13411349
13421350 // Due to incremental compilation, how function calls are generated depends
13431351 // on linking.
1344 if (try self.air.value(callee, mod)) |func_value| {
1352 if (try self.air.value(callee, pt)) |func_value| {
13451353 if (self.bin_file.tag == link.File.Elf.base_tag) {
13461354 switch (mod.intern_pool.indexToKey(func_value.ip_index)) {
13471355 .func => |func| {
......@@ -1429,7 +1437,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
14291437
14301438fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
14311439 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1432 const mod = self.bin_file.comp.module.?;
1440 const pt = self.pt;
1441 const mod = pt.zcu;
14331442 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
14341443 const lhs = try self.resolveInst(bin_op.lhs);
14351444 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -1444,7 +1453,7 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
14441453 .ErrorSet => Type.u16,
14451454 .Optional => blk: {
14461455 const payload_ty = lhs_ty.optionalChild(mod);
1447 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1456 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
14481457 break :blk Type.u1;
14491458 } else if (lhs_ty.isPtrLikeOptional(mod)) {
14501459 break :blk Type.usize;
......@@ -1655,7 +1664,8 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
16551664}
16561665
16571666fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
1658 const mod = self.bin_file.comp.module.?;
1667 const pt = self.pt;
1668 const mod = pt.zcu;
16591669 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
16601670 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
16611671 const func = mod.funcInfo(extra.data.func);
......@@ -1753,7 +1763,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
17531763 if (self.liveness.isUnused(inst))
17541764 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
17551765
1756 const mod = self.bin_file.comp.module.?;
1766 const pt = self.pt;
1767 const mod = pt.zcu;
17571768 const operand_ty = self.typeOf(ty_op.operand);
17581769 const operand = try self.resolveInst(ty_op.operand);
17591770 const info_a = operand_ty.intInfo(mod);
......@@ -1814,12 +1825,13 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
18141825}
18151826
18161827fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
1817 const mod = self.bin_file.comp.module.?;
1828 const pt = self.pt;
1829 const mod = pt.zcu;
18181830 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
18191831 const elem_ty = self.typeOfIndex(inst);
1820 const elem_size = elem_ty.abiSize(mod);
1832 const elem_size = elem_ty.abiSize(pt);
18211833 const result: MCValue = result: {
1822 if (!elem_ty.hasRuntimeBits(mod))
1834 if (!elem_ty.hasRuntimeBits(pt))
18231835 break :result MCValue.none;
18241836
18251837 const ptr = try self.resolveInst(ty_op.operand);
......@@ -1898,7 +1910,7 @@ fn airMod(self: *Self, inst: Air.Inst.Index) !void {
18981910 const rhs = try self.resolveInst(bin_op.rhs);
18991911 const lhs_ty = self.typeOf(bin_op.lhs);
19001912 const rhs_ty = self.typeOf(bin_op.rhs);
1901 assert(lhs_ty.eql(rhs_ty, self.bin_file.comp.module.?));
1913 assert(lhs_ty.eql(rhs_ty, self.pt.zcu));
19021914
19031915 if (self.liveness.isUnused(inst))
19041916 return self.finishAir(inst, .dead, .{ bin_op.lhs, bin_op.rhs, .none });
......@@ -2040,7 +2052,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
20402052 //const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
20412053 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
20422054 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2043 const mod = self.bin_file.comp.module.?;
2055 const pt = self.pt;
2056 const mod = pt.zcu;
20442057 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
20452058 const lhs = try self.resolveInst(extra.lhs);
20462059 const rhs = try self.resolveInst(extra.rhs);
......@@ -2104,7 +2117,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
21042117
21052118fn airNot(self: *Self, inst: Air.Inst.Index) !void {
21062119 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
2107 const mod = self.bin_file.comp.module.?;
2120 const pt = self.pt;
2121 const mod = pt.zcu;
21082122 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
21092123 const operand = try self.resolveInst(ty_op.operand);
21102124 const operand_ty = self.typeOf(ty_op.operand);
......@@ -2336,7 +2350,8 @@ fn airShlSat(self: *Self, inst: Air.Inst.Index) !void {
23362350fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
23372351 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
23382352 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2339 const mod = self.bin_file.comp.module.?;
2353 const pt = self.pt;
2354 const mod = pt.zcu;
23402355 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
23412356 const lhs = try self.resolveInst(extra.lhs);
23422357 const rhs = try self.resolveInst(extra.rhs);
......@@ -2441,7 +2456,8 @@ fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
24412456}
24422457
24432458fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
2444 const mod = self.bin_file.comp.module.?;
2459 const pt = self.pt;
2460 const mod = pt.zcu;
24452461 const is_volatile = false; // TODO
24462462 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
24472463
......@@ -2452,7 +2468,7 @@ fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
24522468
24532469 const slice_ty = self.typeOf(bin_op.lhs);
24542470 const elem_ty = slice_ty.childType(mod);
2455 const elem_size = elem_ty.abiSize(mod);
2471 const elem_size = elem_ty.abiSize(pt);
24562472
24572473 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
24582474
......@@ -2566,10 +2582,10 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
25662582 const operand = extra.struct_operand;
25672583 const index = extra.field_index;
25682584 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
2569 const mod = self.bin_file.comp.module.?;
2585 const pt = self.pt;
25702586 const mcv = try self.resolveInst(operand);
25712587 const struct_ty = self.typeOf(operand);
2572 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
2588 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
25732589
25742590 switch (mcv) {
25752591 .dead, .unreach => unreachable,
......@@ -2699,13 +2715,14 @@ fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
26992715}
27002716
27012717fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
2702 const mod = self.bin_file.comp.module.?;
2718 const pt = self.pt;
2719 const mod = pt.zcu;
27032720 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27042721 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27052722 const error_union_ty = self.typeOf(ty_op.operand);
27062723 const payload_ty = error_union_ty.errorUnionPayload(mod);
27072724 const mcv = try self.resolveInst(ty_op.operand);
2708 if (!payload_ty.hasRuntimeBits(mod)) break :result mcv;
2725 if (!payload_ty.hasRuntimeBits(pt)) break :result mcv;
27092726
27102727 return self.fail("TODO implement unwrap error union error for non-empty payloads", .{});
27112728 };
......@@ -2713,12 +2730,13 @@ fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
27132730}
27142731
27152732fn airUnwrapErrPayload(self: *Self, inst: Air.Inst.Index) !void {
2716 const mod = self.bin_file.comp.module.?;
2733 const pt = self.pt;
2734 const mod = pt.zcu;
27172735 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27182736 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27192737 const error_union_ty = self.typeOf(ty_op.operand);
27202738 const payload_ty = error_union_ty.errorUnionPayload(mod);
2721 if (!payload_ty.hasRuntimeBits(mod)) break :result MCValue.none;
2739 if (!payload_ty.hasRuntimeBits(pt)) break :result MCValue.none;
27222740
27232741 return self.fail("TODO implement unwrap error union payload for non-empty payloads", .{});
27242742 };
......@@ -2727,13 +2745,14 @@ fn airUnwrapErrPayload(self: *Self, inst: Air.Inst.Index) !void {
27272745
27282746/// E to E!T
27292747fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
2730 const mod = self.bin_file.comp.module.?;
2748 const pt = self.pt;
2749 const mod = pt.zcu;
27312750 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27322751 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27332752 const error_union_ty = ty_op.ty.toType();
27342753 const payload_ty = error_union_ty.errorUnionPayload(mod);
27352754 const mcv = try self.resolveInst(ty_op.operand);
2736 if (!payload_ty.hasRuntimeBits(mod)) break :result mcv;
2755 if (!payload_ty.hasRuntimeBits(pt)) break :result mcv;
27372756
27382757 return self.fail("TODO implement wrap errunion error for non-empty payloads", .{});
27392758 };
......@@ -2748,13 +2767,13 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
27482767}
27492768
27502769fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
2751 const mod = self.bin_file.comp.module.?;
2770 const pt = self.pt;
27522771 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27532772 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27542773 const optional_ty = self.typeOfIndex(inst);
27552774
27562775 // Optional with a zero-bit payload type is just a boolean true
2757 if (optional_ty.abiSize(mod) == 1)
2776 if (optional_ty.abiSize(pt) == 1)
27582777 break :result MCValue{ .immediate = 1 };
27592778
27602779 return self.fail("TODO implement wrap optional for {}", .{self.target.cpu.arch});
......@@ -2788,10 +2807,11 @@ fn allocMem(self: *Self, inst: Air.Inst.Index, abi_size: u32, abi_align: Alignme
27882807
27892808/// Use a pointer instruction as the basis for allocating stack memory.
27902809fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
2791 const mod = self.bin_file.comp.module.?;
2810 const pt = self.pt;
2811 const mod = pt.zcu;
27922812 const elem_ty = self.typeOfIndex(inst).childType(mod);
27932813
2794 if (!elem_ty.hasRuntimeBits(mod)) {
2814 if (!elem_ty.hasRuntimeBits(pt)) {
27952815 // As this stack item will never be dereferenced at runtime,
27962816 // return the stack offset 0. Stack offset 0 will be where all
27972817 // zero-sized stack allocations live as non-zero-sized
......@@ -2799,21 +2819,21 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
27992819 return @as(u32, 0);
28002820 }
28012821
2802 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
2803 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
2822 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
2823 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
28042824 };
28052825 // TODO swap this for inst.ty.ptrAlign
2806 const abi_align = elem_ty.abiAlignment(mod);
2826 const abi_align = elem_ty.abiAlignment(pt);
28072827 return self.allocMem(inst, abi_size, abi_align);
28082828}
28092829
28102830fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
2811 const mod = self.bin_file.comp.module.?;
2831 const pt = self.pt;
28122832 const elem_ty = self.typeOfIndex(inst);
2813 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
2814 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
2833 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
2834 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
28152835 };
2816 const abi_align = elem_ty.abiAlignment(mod);
2836 const abi_align = elem_ty.abiAlignment(pt);
28172837 self.stack_align = self.stack_align.max(abi_align);
28182838
28192839 if (reg_ok) {
......@@ -2855,7 +2875,8 @@ fn binOp(
28552875 rhs_ty: Type,
28562876 metadata: ?BinOpMetadata,
28572877) InnerError!MCValue {
2858 const mod = self.bin_file.comp.module.?;
2878 const pt = self.pt;
2879 const mod = pt.zcu;
28592880 switch (tag) {
28602881 .add,
28612882 .sub,
......@@ -2996,7 +3017,7 @@ fn binOp(
29963017 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
29973018 else => ptr_ty.childType(mod),
29983019 };
2999 const elem_size = elem_ty.abiSize(mod);
3020 const elem_size = elem_ty.abiSize(pt);
30003021
30013022 if (elem_size == 1) {
30023023 const base_tag: Mir.Inst.Tag = switch (tag) {
......@@ -3396,8 +3417,8 @@ fn binOpRegister(
33963417fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
33973418 const block_data = self.blocks.getPtr(block).?;
33983419
3399 const mod = self.bin_file.comp.module.?;
3400 if (self.typeOf(operand).hasRuntimeBits(mod)) {
3420 const pt = self.pt;
3421 if (self.typeOf(operand).hasRuntimeBits(pt)) {
34013422 const operand_mcv = try self.resolveInst(operand);
34023423 const block_mcv = block_data.mcv;
34033424 if (block_mcv == .none) {
......@@ -3516,17 +3537,18 @@ fn ensureProcessDeathCapacity(self: *Self, additional_count: usize) !void {
35163537
35173538/// Given an error union, returns the payload
35183539fn errUnionPayload(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
3519 const mod = self.bin_file.comp.module.?;
3540 const pt = self.pt;
3541 const mod = pt.zcu;
35203542 const err_ty = error_union_ty.errorUnionSet(mod);
35213543 const payload_ty = error_union_ty.errorUnionPayload(mod);
35223544 if (err_ty.errorSetIsEmpty(mod)) {
35233545 return error_union_mcv;
35243546 }
3525 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3547 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35263548 return MCValue.none;
35273549 }
35283550
3529 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
3551 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
35303552 switch (error_union_mcv) {
35313553 .register => return self.fail("TODO errUnionPayload for registers", .{}),
35323554 .stack_offset => |off| {
......@@ -3587,7 +3609,8 @@ fn finishAir(self: *Self, inst: Air.Inst.Index, result: MCValue, operands: [Live
35873609}
35883610
35893611fn genArgDbgInfo(self: Self, inst: Air.Inst.Index, mcv: MCValue) !void {
3590 const mod = self.bin_file.comp.module.?;
3612 const pt = self.pt;
3613 const mod = pt.zcu;
35913614 const arg = self.air.instructions.items(.data)[@intFromEnum(inst)].arg;
35923615 const ty = arg.ty.toType();
35933616 const owner_decl = mod.funcOwnerDeclIndex(self.func_index);
......@@ -3736,7 +3759,7 @@ fn genLoadASI(self: *Self, value_reg: Register, addr_reg: Register, off_reg: Reg
37363759}
37373760
37383761fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
3739 const mod = self.bin_file.comp.module.?;
3762 const pt = self.pt;
37403763 switch (mcv) {
37413764 .dead => unreachable,
37423765 .unreach, .none => return, // Nothing to do.
......@@ -3935,20 +3958,21 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
39353958 // The value is in memory at a hard-coded address.
39363959 // If the type is a pointer, it means the pointer address is at this memory location.
39373960 try self.genSetReg(ty, reg, .{ .immediate = addr });
3938 try self.genLoad(reg, reg, i13, 0, ty.abiSize(mod));
3961 try self.genLoad(reg, reg, i13, 0, ty.abiSize(pt));
39393962 },
39403963 .stack_offset => |off| {
39413964 const real_offset = realStackOffset(off);
39423965 const simm13 = math.cast(i13, real_offset) orelse
39433966 return self.fail("TODO larger stack offsets: {}", .{real_offset});
3944 try self.genLoad(reg, .sp, i13, simm13, ty.abiSize(mod));
3967 try self.genLoad(reg, .sp, i13, simm13, ty.abiSize(pt));
39453968 },
39463969 }
39473970}
39483971
39493972fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
3950 const mod = self.bin_file.comp.module.?;
3951 const abi_size = ty.abiSize(mod);
3973 const pt = self.pt;
3974 const mod = pt.zcu;
3975 const abi_size = ty.abiSize(pt);
39523976 switch (mcv) {
39533977 .dead => unreachable,
39543978 .unreach, .none => return, // Nothing to do.
......@@ -3956,7 +3980,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
39563980 if (!self.wantSafety())
39573981 return; // The already existing value will do just fine.
39583982 // TODO Upgrade this to a memset call when we have that available.
3959 switch (ty.abiSize(mod)) {
3983 switch (ty.abiSize(pt)) {
39603984 1 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaa }),
39613985 2 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaa }),
39623986 4 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaaaaaa }),
......@@ -3986,7 +4010,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
39864010 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = rwo.reg });
39874011
39884012 const overflow_bit_ty = ty.structFieldType(1, mod);
3989 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, mod)));
4013 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, pt)));
39904014 const cond_reg = try self.register_manager.allocReg(null, gp);
39914015
39924016 // TODO handle floating point CCRs
......@@ -4032,7 +4056,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
40324056 const reg = try self.copyToTmpRegister(ty, mcv);
40334057 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
40344058 } else {
4035 const ptr_ty = try mod.singleMutPtrType(ty);
4059 const ptr_ty = try pt.singleMutPtrType(ty);
40364060
40374061 const regs = try self.register_manager.allocRegs(4, .{ null, null, null, null }, gp);
40384062 const regs_locks = self.register_manager.lockRegsAssumeUnused(4, regs);
......@@ -4121,12 +4145,13 @@ fn genStoreASI(self: *Self, value_reg: Register, addr_reg: Register, off_reg: Re
41214145}
41224146
41234147fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
4124 const mod = self.bin_file.comp.module.?;
4148 const pt = self.pt;
41254149 const mcv: MCValue = switch (try codegen.genTypedValue(
41264150 self.bin_file,
4151 pt,
41274152 self.src_loc,
41284153 val,
4129 mod.funcOwnerDeclIndex(self.func_index),
4154 pt.zcu.funcOwnerDeclIndex(self.func_index),
41304155 )) {
41314156 .mcv => |mcv| switch (mcv) {
41324157 .none => .none,
......@@ -4157,14 +4182,15 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
41574182}
41584183
41594184fn isErr(self: *Self, ty: Type, operand: MCValue) !MCValue {
4160 const mod = self.bin_file.comp.module.?;
4185 const pt = self.pt;
4186 const mod = pt.zcu;
41614187 const error_type = ty.errorUnionSet(mod);
41624188 const payload_type = ty.errorUnionPayload(mod);
41634189
4164 if (!error_type.hasRuntimeBits(mod)) {
4190 if (!error_type.hasRuntimeBits(pt)) {
41654191 return MCValue{ .immediate = 0 }; // always false
4166 } else if (!payload_type.hasRuntimeBits(mod)) {
4167 if (error_type.abiSize(mod) <= 8) {
4192 } else if (!payload_type.hasRuntimeBits(pt)) {
4193 if (error_type.abiSize(pt) <= 8) {
41684194 const reg_mcv: MCValue = switch (operand) {
41694195 .register => operand,
41704196 else => .{ .register = try self.copyToTmpRegister(error_type, operand) },
......@@ -4255,9 +4281,10 @@ fn jump(self: *Self, inst: Mir.Inst.Index) !void {
42554281}
42564282
42574283fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
4258 const mod = self.bin_file.comp.module.?;
4284 const pt = self.pt;
4285 const mod = pt.zcu;
42594286 const elem_ty = ptr_ty.childType(mod);
4260 const elem_size = elem_ty.abiSize(mod);
4287 const elem_size = elem_ty.abiSize(pt);
42614288
42624289 switch (ptr) {
42634290 .none => unreachable,
......@@ -4326,7 +4353,8 @@ fn minMax(
43264353 lhs_ty: Type,
43274354 rhs_ty: Type,
43284355) InnerError!MCValue {
4329 const mod = self.bin_file.comp.module.?;
4356 const pt = self.pt;
4357 const mod = pt.zcu;
43304358 assert(lhs_ty.eql(rhs_ty, mod));
43314359 switch (lhs_ty.zigTypeTag(mod)) {
43324360 .Float => return self.fail("TODO min/max on floats", .{}),
......@@ -4446,7 +4474,8 @@ fn realStackOffset(off: u32) u32 {
44464474
44474475/// Caller must call `CallMCValues.deinit`.
44484476fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView) !CallMCValues {
4449 const mod = self.bin_file.comp.module.?;
4477 const pt = self.pt;
4478 const mod = pt.zcu;
44504479 const ip = &mod.intern_pool;
44514480 const fn_info = mod.typeToFunc(fn_ty).?;
44524481 const cc = fn_info.cc;
......@@ -4487,7 +4516,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
44874516 };
44884517
44894518 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
4490 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(mod)));
4519 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(pt)));
44914520 if (param_size <= 8) {
44924521 if (next_register < argument_registers.len) {
44934522 result_arg.* = .{ .register = argument_registers[next_register] };
......@@ -4516,10 +4545,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
45164545
45174546 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
45184547 result.return_value = .{ .unreach = {} };
4519 } else if (!ret_ty.hasRuntimeBits(mod)) {
4548 } else if (!ret_ty.hasRuntimeBits(pt)) {
45204549 result.return_value = .{ .none = {} };
45214550 } else {
4522 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
4551 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
45234552 // The callee puts the return values in %i0-%i3, which becomes %o0-%o3 inside the caller.
45244553 if (ret_ty_size <= 8) {
45254554 result.return_value = switch (role) {
......@@ -4538,21 +4567,22 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
45384567}
45394568
45404569fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!MCValue {
4541 const mod = self.bin_file.comp.module.?;
4570 const pt = self.pt;
45424571 const ty = self.typeOf(ref);
45434572
45444573 // If the type has no codegen bits, no need to store it.
4545 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
4574 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
45464575
45474576 if (ref.toIndex()) |inst| {
45484577 return self.getResolvedInstValue(inst);
45494578 }
45504579
4551 return self.genTypedValue((try self.air.value(ref, mod)).?);
4580 return self.genTypedValue((try self.air.value(ref, pt)).?);
45524581}
45534582
45544583fn ret(self: *Self, mcv: MCValue) !void {
4555 const mod = self.bin_file.comp.module.?;
4584 const pt = self.pt;
4585 const mod = pt.zcu;
45564586 const ret_ty = self.fn_type.fnReturnType(mod);
45574587 try self.setRegOrMem(ret_ty, self.ret_mcv, mcv);
45584588
......@@ -4654,8 +4684,8 @@ pub fn spillInstruction(self: *Self, reg: Register, inst: Air.Inst.Index) !void
46544684}
46554685
46564686fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
4657 const mod = self.bin_file.comp.module.?;
4658 const abi_size = value_ty.abiSize(mod);
4687 const pt = self.pt;
4688 const abi_size = value_ty.abiSize(pt);
46594689
46604690 switch (ptr) {
46614691 .none => unreachable,
......@@ -4696,11 +4726,12 @@ fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type
46964726
46974727fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
46984728 return if (self.liveness.isUnused(inst)) .dead else result: {
4699 const mod = self.bin_file.comp.module.?;
4729 const pt = self.pt;
4730 const mod = pt.zcu;
47004731 const mcv = try self.resolveInst(operand);
47014732 const ptr_ty = self.typeOf(operand);
47024733 const struct_ty = ptr_ty.childType(mod);
4703 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4734 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
47044735 switch (mcv) {
47054736 .ptr_stack_offset => |off| {
47064737 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -4738,7 +4769,8 @@ fn trunc(
47384769 operand_ty: Type,
47394770 dest_ty: Type,
47404771) !MCValue {
4741 const mod = self.bin_file.comp.module.?;
4772 const pt = self.pt;
4773 const mod = pt.zcu;
47424774 const info_a = operand_ty.intInfo(mod);
47434775 const info_b = dest_ty.intInfo(mod);
47444776
......@@ -4848,7 +4880,7 @@ fn truncRegister(
48484880 }
48494881}
48504882
4851/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
4883/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
48524884fn wantSafety(self: *Self) bool {
48534885 return switch (self.bin_file.comp.root_mod.optimize_mode) {
48544886 .Debug => true,
......@@ -4859,11 +4891,9 @@ fn wantSafety(self: *Self) bool {
48594891}
48604892
48614893fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
4862 const mod = self.bin_file.comp.module.?;
4863 return self.air.typeOf(inst, &mod.intern_pool);
4894 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
48644895}
48654896
48664897fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
4867 const mod = self.bin_file.comp.module.?;
4868 return self.air.typeOfIndex(inst, &mod.intern_pool);
4898 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
48694899}
src/arch/sparc64/Emit.zig+2-4
......@@ -6,9 +6,7 @@ const Endian = std.builtin.Endian;
66const assert = std.debug.assert;
77const link = @import("../../link.zig");
88const Zcu = @import("../../Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
11const ErrorMsg = Module.ErrorMsg;
9const ErrorMsg = Zcu.ErrorMsg;
1210const Liveness = @import("../../Liveness.zig");
1311const log = std.log.scoped(.sparcv9_emit);
1412const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput;
......@@ -24,7 +22,7 @@ bin_file: *link.File,
2422debug_output: DebugInfoOutput,
2523target: *const std.Target,
2624err_msg: ?*ErrorMsg = null,
27src_loc: Module.LazySrcLoc,
25src_loc: Zcu.LazySrcLoc,
2826code: *std.ArrayList(u8),
2927
3028prev_di_line: u32,
src/arch/wasm/CodeGen.zig+532-429
......@@ -684,6 +684,7 @@ simd_immediates: std.ArrayListUnmanaged([16]u8) = .{},
684684target: std.Target,
685685/// Represents the wasm binary file that is being linked.
686686bin_file: *link.File.Wasm,
687pt: Zcu.PerThread,
687688/// List of MIR Instructions
688689mir_instructions: std.MultiArrayList(Mir.Inst) = .{},
689690/// Contains extra data for MIR
......@@ -764,8 +765,7 @@ pub fn deinit(func: *CodeGen) void {
764765
765766/// Sets `err_msg` on `CodeGen` and returns `error.CodegenFail` which is caught in link/Wasm.zig
766767fn fail(func: *CodeGen, comptime fmt: []const u8, args: anytype) InnerError {
767 const mod = func.bin_file.base.comp.module.?;
768 const src_loc = func.decl.navSrcLoc(mod);
768 const src_loc = func.decl.navSrcLoc(func.pt.zcu);
769769 func.err_msg = try Zcu.ErrorMsg.create(func.gpa, src_loc, fmt, args);
770770 return error.CodegenFail;
771771}
......@@ -788,10 +788,11 @@ fn resolveInst(func: *CodeGen, ref: Air.Inst.Ref) InnerError!WValue {
788788 const gop = try func.branches.items[0].values.getOrPut(func.gpa, ref);
789789 assert(!gop.found_existing);
790790
791 const mod = func.bin_file.base.comp.module.?;
792 const val = (try func.air.value(ref, mod)).?;
791 const pt = func.pt;
792 const mod = pt.zcu;
793 const val = (try func.air.value(ref, pt)).?;
793794 const ty = func.typeOf(ref);
794 if (!ty.hasRuntimeBitsIgnoreComptime(mod) and !ty.isInt(mod) and !ty.isError(mod)) {
795 if (!ty.hasRuntimeBitsIgnoreComptime(pt) and !ty.isInt(mod) and !ty.isError(mod)) {
795796 gop.value_ptr.* = WValue{ .none = {} };
796797 return gop.value_ptr.*;
797798 }
......@@ -802,8 +803,8 @@ fn resolveInst(func: *CodeGen, ref: Air.Inst.Ref) InnerError!WValue {
802803 //
803804 // In the other cases, we will simply lower the constant to a value that fits
804805 // into a single local (such as a pointer, integer, bool, etc).
805 const result = if (isByRef(ty, mod)) blk: {
806 const sym_index = try func.bin_file.lowerUnnamedConst(val, func.decl_index);
806 const result = if (isByRef(ty, pt)) blk: {
807 const sym_index = try func.bin_file.lowerUnnamedConst(pt, val, func.decl_index);
807808 break :blk WValue{ .memory = sym_index };
808809 } else try func.lowerConstant(val, ty);
809810
......@@ -990,7 +991,8 @@ fn addExtraAssumeCapacity(func: *CodeGen, extra: anytype) error{OutOfMemory}!u32
990991}
991992
992993/// Using a given `Type`, returns the corresponding type
993fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
994fn typeToValtype(ty: Type, pt: Zcu.PerThread) wasm.Valtype {
995 const mod = pt.zcu;
994996 const target = mod.getTarget();
995997 const ip = &mod.intern_pool;
996998 return switch (ty.zigTypeTag(mod)) {
......@@ -1002,26 +1004,26 @@ fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
10021004 else => unreachable,
10031005 },
10041006 .Int, .Enum => blk: {
1005 const info = ty.intInfo(mod);
1007 const info = ty.intInfo(pt.zcu);
10061008 if (info.bits <= 32) break :blk wasm.Valtype.i32;
10071009 if (info.bits > 32 and info.bits <= 128) break :blk wasm.Valtype.i64;
10081010 break :blk wasm.Valtype.i32; // represented as pointer to stack
10091011 },
10101012 .Struct => {
1011 if (mod.typeToPackedStruct(ty)) |packed_struct| {
1012 return typeToValtype(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
1013 if (pt.zcu.typeToPackedStruct(ty)) |packed_struct| {
1014 return typeToValtype(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
10131015 } else {
10141016 return wasm.Valtype.i32;
10151017 }
10161018 },
1017 .Vector => switch (determineSimdStoreStrategy(ty, mod)) {
1019 .Vector => switch (determineSimdStoreStrategy(ty, pt)) {
10181020 .direct => wasm.Valtype.v128,
10191021 .unrolled => wasm.Valtype.i32,
10201022 },
1021 .Union => switch (ty.containerLayout(mod)) {
1023 .Union => switch (ty.containerLayout(pt.zcu)) {
10221024 .@"packed" => {
1023 const int_ty = mod.intType(.unsigned, @as(u16, @intCast(ty.bitSize(mod)))) catch @panic("out of memory");
1024 return typeToValtype(int_ty, mod);
1025 const int_ty = pt.intType(.unsigned, @as(u16, @intCast(ty.bitSize(pt)))) catch @panic("out of memory");
1026 return typeToValtype(int_ty, pt);
10251027 },
10261028 else => wasm.Valtype.i32,
10271029 },
......@@ -1030,17 +1032,17 @@ fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
10301032}
10311033
10321034/// Using a given `Type`, returns the byte representation of its wasm value type
1033fn genValtype(ty: Type, mod: *Zcu) u8 {
1034 return wasm.valtype(typeToValtype(ty, mod));
1035fn genValtype(ty: Type, pt: Zcu.PerThread) u8 {
1036 return wasm.valtype(typeToValtype(ty, pt));
10351037}
10361038
10371039/// Using a given `Type`, returns the corresponding wasm value type
10381040/// Differently from `genValtype` this also allows `void` to create a block
10391041/// with no return type
1040fn genBlockType(ty: Type, mod: *Zcu) u8 {
1042fn genBlockType(ty: Type, pt: Zcu.PerThread) u8 {
10411043 return switch (ty.ip_index) {
10421044 .void_type, .noreturn_type => wasm.block_empty,
1043 else => genValtype(ty, mod),
1045 else => genValtype(ty, pt),
10441046 };
10451047}
10461048
......@@ -1101,8 +1103,8 @@ fn getResolvedInst(func: *CodeGen, ref: Air.Inst.Ref) *WValue {
11011103/// Creates one locals for a given `Type`.
11021104/// Returns a corresponding `Wvalue` with `local` as active tag
11031105fn allocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
1104 const mod = func.bin_file.base.comp.module.?;
1105 const valtype = typeToValtype(ty, mod);
1106 const pt = func.pt;
1107 const valtype = typeToValtype(ty, pt);
11061108 switch (valtype) {
11071109 .i32 => if (func.free_locals_i32.popOrNull()) |index| {
11081110 log.debug("reusing local ({d}) of type {}", .{ index, valtype });
......@@ -1133,8 +1135,8 @@ fn allocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
11331135/// Ensures a new local will be created. This is useful when it's useful
11341136/// to use a zero-initialized local.
11351137fn ensureAllocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
1136 const mod = func.bin_file.base.comp.module.?;
1137 try func.locals.append(func.gpa, genValtype(ty, mod));
1138 const pt = func.pt;
1139 try func.locals.append(func.gpa, genValtype(ty, pt));
11381140 const initial_index = func.local_index;
11391141 func.local_index += 1;
11401142 return WValue{ .local = .{ .value = initial_index, .references = 1 } };
......@@ -1147,23 +1149,24 @@ fn genFunctype(
11471149 cc: std.builtin.CallingConvention,
11481150 params: []const InternPool.Index,
11491151 return_type: Type,
1150 mod: *Zcu,
1152 pt: Zcu.PerThread,
11511153) !wasm.Type {
1154 const mod = pt.zcu;
11521155 var temp_params = std.ArrayList(wasm.Valtype).init(gpa);
11531156 defer temp_params.deinit();
11541157 var returns = std.ArrayList(wasm.Valtype).init(gpa);
11551158 defer returns.deinit();
11561159
1157 if (firstParamSRet(cc, return_type, mod)) {
1160 if (firstParamSRet(cc, return_type, pt)) {
11581161 try temp_params.append(.i32); // memory address is always a 32-bit handle
1159 } else if (return_type.hasRuntimeBitsIgnoreComptime(mod)) {
1162 } else if (return_type.hasRuntimeBitsIgnoreComptime(pt)) {
11601163 if (cc == .C) {
1161 const res_classes = abi.classifyType(return_type, mod);
1164 const res_classes = abi.classifyType(return_type, pt);
11621165 assert(res_classes[0] == .direct and res_classes[1] == .none);
1163 const scalar_type = abi.scalarType(return_type, mod);
1164 try returns.append(typeToValtype(scalar_type, mod));
1166 const scalar_type = abi.scalarType(return_type, pt);
1167 try returns.append(typeToValtype(scalar_type, pt));
11651168 } else {
1166 try returns.append(typeToValtype(return_type, mod));
1169 try returns.append(typeToValtype(return_type, pt));
11671170 }
11681171 } else if (return_type.isError(mod)) {
11691172 try returns.append(.i32);
......@@ -1172,25 +1175,25 @@ fn genFunctype(
11721175 // param types
11731176 for (params) |param_type_ip| {
11741177 const param_type = Type.fromInterned(param_type_ip);
1175 if (!param_type.hasRuntimeBitsIgnoreComptime(mod)) continue;
1178 if (!param_type.hasRuntimeBitsIgnoreComptime(pt)) continue;
11761179
11771180 switch (cc) {
11781181 .C => {
1179 const param_classes = abi.classifyType(param_type, mod);
1182 const param_classes = abi.classifyType(param_type, pt);
11801183 for (param_classes) |class| {
11811184 if (class == .none) continue;
11821185 if (class == .direct) {
1183 const scalar_type = abi.scalarType(param_type, mod);
1184 try temp_params.append(typeToValtype(scalar_type, mod));
1186 const scalar_type = abi.scalarType(param_type, pt);
1187 try temp_params.append(typeToValtype(scalar_type, pt));
11851188 } else {
1186 try temp_params.append(typeToValtype(param_type, mod));
1189 try temp_params.append(typeToValtype(param_type, pt));
11871190 }
11881191 }
11891192 },
1190 else => if (isByRef(param_type, mod))
1193 else => if (isByRef(param_type, pt))
11911194 try temp_params.append(.i32)
11921195 else
1193 try temp_params.append(typeToValtype(param_type, mod)),
1196 try temp_params.append(typeToValtype(param_type, pt)),
11941197 }
11951198 }
11961199
......@@ -1202,6 +1205,7 @@ fn genFunctype(
12021205
12031206pub fn generate(
12041207 bin_file: *link.File,
1208 pt: Zcu.PerThread,
12051209 src_loc: Zcu.LazySrcLoc,
12061210 func_index: InternPool.Index,
12071211 air: Air,
......@@ -1210,15 +1214,15 @@ pub fn generate(
12101214 debug_output: codegen.DebugInfoOutput,
12111215) codegen.CodeGenError!codegen.Result {
12121216 _ = src_loc;
1213 const comp = bin_file.comp;
1214 const gpa = comp.gpa;
1215 const zcu = comp.module.?;
1217 const zcu = pt.zcu;
1218 const gpa = zcu.gpa;
12161219 const func = zcu.funcInfo(func_index);
12171220 const decl = zcu.declPtr(func.owner_decl);
12181221 const namespace = zcu.namespacePtr(decl.src_namespace);
12191222 const target = namespace.fileScope(zcu).mod.resolved_target.result;
12201223 var code_gen: CodeGen = .{
12211224 .gpa = gpa,
1225 .pt = pt,
12221226 .air = air,
12231227 .liveness = liveness,
12241228 .code = code,
......@@ -1242,10 +1246,11 @@ pub fn generate(
12421246}
12431247
12441248fn genFunc(func: *CodeGen) InnerError!void {
1245 const mod = func.bin_file.base.comp.module.?;
1249 const pt = func.pt;
1250 const mod = pt.zcu;
12461251 const ip = &mod.intern_pool;
12471252 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
1248 var func_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), mod);
1253 var func_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), pt);
12491254 defer func_type.deinit(func.gpa);
12501255 _ = try func.bin_file.storeDeclType(func.decl_index, func_type);
12511256
......@@ -1272,7 +1277,7 @@ fn genFunc(func: *CodeGen) InnerError!void {
12721277 if (func_type.returns.len != 0 and func.air.instructions.len > 0) {
12731278 const inst: Air.Inst.Index = @enumFromInt(func.air.instructions.len - 1);
12741279 const last_inst_ty = func.typeOfIndex(inst);
1275 if (!last_inst_ty.hasRuntimeBitsIgnoreComptime(mod) or last_inst_ty.isNoReturn(mod)) {
1280 if (!last_inst_ty.hasRuntimeBitsIgnoreComptime(pt) or last_inst_ty.isNoReturn(mod)) {
12761281 try func.addTag(.@"unreachable");
12771282 }
12781283 }
......@@ -1354,7 +1359,8 @@ const CallWValues = struct {
13541359};
13551360
13561361fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWValues {
1357 const mod = func.bin_file.base.comp.module.?;
1362 const pt = func.pt;
1363 const mod = pt.zcu;
13581364 const ip = &mod.intern_pool;
13591365 const fn_info = mod.typeToFunc(fn_ty).?;
13601366 const cc = fn_info.cc;
......@@ -1369,7 +1375,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13691375
13701376 // Check if we store the result as a pointer to the stack rather than
13711377 // by value
1372 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
1378 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
13731379 // the sret arg will be passed as first argument, therefore we
13741380 // set the `return_value` before allocating locals for regular args.
13751381 result.return_value = .{ .local = .{ .value = func.local_index, .references = 1 } };
......@@ -1379,7 +1385,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13791385 switch (cc) {
13801386 .Unspecified => {
13811387 for (fn_info.param_types.get(ip)) |ty| {
1382 if (!Type.fromInterned(ty).hasRuntimeBitsIgnoreComptime(mod)) {
1388 if (!Type.fromInterned(ty).hasRuntimeBitsIgnoreComptime(pt)) {
13831389 continue;
13841390 }
13851391
......@@ -1389,7 +1395,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13891395 },
13901396 .C => {
13911397 for (fn_info.param_types.get(ip)) |ty| {
1392 const ty_classes = abi.classifyType(Type.fromInterned(ty), mod);
1398 const ty_classes = abi.classifyType(Type.fromInterned(ty), pt);
13931399 for (ty_classes) |class| {
13941400 if (class == .none) continue;
13951401 try args.append(.{ .local = .{ .value = func.local_index, .references = 1 } });
......@@ -1403,11 +1409,11 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
14031409 return result;
14041410}
14051411
1406fn firstParamSRet(cc: std.builtin.CallingConvention, return_type: Type, mod: *Zcu) bool {
1412fn firstParamSRet(cc: std.builtin.CallingConvention, return_type: Type, pt: Zcu.PerThread) bool {
14071413 switch (cc) {
1408 .Unspecified, .Inline => return isByRef(return_type, mod),
1414 .Unspecified, .Inline => return isByRef(return_type, pt),
14091415 .C => {
1410 const ty_classes = abi.classifyType(return_type, mod);
1416 const ty_classes = abi.classifyType(return_type, pt);
14111417 if (ty_classes[0] == .indirect) return true;
14121418 if (ty_classes[0] == .direct and ty_classes[1] == .direct) return true;
14131419 return false;
......@@ -1423,8 +1429,9 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14231429 return func.lowerToStack(value);
14241430 }
14251431
1426 const mod = func.bin_file.base.comp.module.?;
1427 const ty_classes = abi.classifyType(ty, mod);
1432 const pt = func.pt;
1433 const mod = pt.zcu;
1434 const ty_classes = abi.classifyType(ty, pt);
14281435 assert(ty_classes[0] != .none);
14291436 switch (ty.zigTypeTag(mod)) {
14301437 .Struct, .Union => {
......@@ -1432,7 +1439,7 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14321439 return func.lowerToStack(value);
14331440 }
14341441 assert(ty_classes[0] == .direct);
1435 const scalar_type = abi.scalarType(ty, mod);
1442 const scalar_type = abi.scalarType(ty, pt);
14361443 switch (value) {
14371444 .memory,
14381445 .memory_offset,
......@@ -1447,7 +1454,7 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14471454 return func.lowerToStack(value);
14481455 }
14491456 assert(ty_classes[0] == .direct and ty_classes[1] == .direct);
1450 assert(ty.abiSize(mod) == 16);
1457 assert(ty.abiSize(pt) == 16);
14511458 // in this case we have an integer or float that must be lowered as 2 i64's.
14521459 try func.emitWValue(value);
14531460 try func.addMemArg(.i64_load, .{ .offset = value.offset(), .alignment = 8 });
......@@ -1514,18 +1521,18 @@ fn restoreStackPointer(func: *CodeGen) !void {
15141521///
15151522/// Asserts Type has codegenbits
15161523fn allocStack(func: *CodeGen, ty: Type) !WValue {
1517 const mod = func.bin_file.base.comp.module.?;
1518 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
1524 const pt = func.pt;
1525 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
15191526 if (func.initial_stack_value == .none) {
15201527 try func.initializeStack();
15211528 }
15221529
1523 const abi_size = std.math.cast(u32, ty.abiSize(mod)) orelse {
1530 const abi_size = std.math.cast(u32, ty.abiSize(pt)) orelse {
15241531 return func.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1525 ty.fmt(mod), ty.abiSize(mod),
1532 ty.fmt(pt), ty.abiSize(pt),
15261533 });
15271534 };
1528 const abi_align = ty.abiAlignment(mod);
1535 const abi_align = ty.abiAlignment(pt);
15291536
15301537 func.stack_alignment = func.stack_alignment.max(abi_align);
15311538
......@@ -1540,7 +1547,8 @@ fn allocStack(func: *CodeGen, ty: Type) !WValue {
15401547/// This is different from allocStack where this will use the pointer's alignment
15411548/// if it is set, to ensure the stack alignment will be set correctly.
15421549fn allocStackPtr(func: *CodeGen, inst: Air.Inst.Index) !WValue {
1543 const mod = func.bin_file.base.comp.module.?;
1550 const pt = func.pt;
1551 const mod = pt.zcu;
15441552 const ptr_ty = func.typeOfIndex(inst);
15451553 const pointee_ty = ptr_ty.childType(mod);
15461554
......@@ -1548,14 +1556,14 @@ fn allocStackPtr(func: *CodeGen, inst: Air.Inst.Index) !WValue {
15481556 try func.initializeStack();
15491557 }
15501558
1551 if (!pointee_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1559 if (!pointee_ty.hasRuntimeBitsIgnoreComptime(pt)) {
15521560 return func.allocStack(Type.usize); // create a value containing just the stack pointer.
15531561 }
15541562
1555 const abi_alignment = ptr_ty.ptrAlignment(mod);
1556 const abi_size = std.math.cast(u32, pointee_ty.abiSize(mod)) orelse {
1563 const abi_alignment = ptr_ty.ptrAlignment(pt);
1564 const abi_size = std.math.cast(u32, pointee_ty.abiSize(pt)) orelse {
15571565 return func.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1558 pointee_ty.fmt(mod), pointee_ty.abiSize(mod),
1566 pointee_ty.fmt(pt), pointee_ty.abiSize(pt),
15591567 });
15601568 };
15611569 func.stack_alignment = func.stack_alignment.max(abi_alignment);
......@@ -1711,7 +1719,8 @@ fn arch(func: *const CodeGen) std.Target.Cpu.Arch {
17111719
17121720/// For a given `Type`, will return true when the type will be passed
17131721/// by reference, rather than by value
1714fn isByRef(ty: Type, mod: *Zcu) bool {
1722fn isByRef(ty: Type, pt: Zcu.PerThread) bool {
1723 const mod = pt.zcu;
17151724 const ip = &mod.intern_pool;
17161725 const target = mod.getTarget();
17171726 switch (ty.zigTypeTag(mod)) {
......@@ -1734,28 +1743,28 @@ fn isByRef(ty: Type, mod: *Zcu) bool {
17341743
17351744 .Array,
17361745 .Frame,
1737 => return ty.hasRuntimeBitsIgnoreComptime(mod),
1746 => return ty.hasRuntimeBitsIgnoreComptime(pt),
17381747 .Union => {
17391748 if (mod.typeToUnion(ty)) |union_obj| {
17401749 if (union_obj.getLayout(ip) == .@"packed") {
1741 return ty.abiSize(mod) > 8;
1750 return ty.abiSize(pt) > 8;
17421751 }
17431752 }
1744 return ty.hasRuntimeBitsIgnoreComptime(mod);
1753 return ty.hasRuntimeBitsIgnoreComptime(pt);
17451754 },
17461755 .Struct => {
17471756 if (mod.typeToPackedStruct(ty)) |packed_struct| {
1748 return isByRef(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
1757 return isByRef(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
17491758 }
1750 return ty.hasRuntimeBitsIgnoreComptime(mod);
1759 return ty.hasRuntimeBitsIgnoreComptime(pt);
17511760 },
1752 .Vector => return determineSimdStoreStrategy(ty, mod) == .unrolled,
1761 .Vector => return determineSimdStoreStrategy(ty, pt) == .unrolled,
17531762 .Int => return ty.intInfo(mod).bits > 64,
17541763 .Enum => return ty.intInfo(mod).bits > 64,
17551764 .Float => return ty.floatBits(target) > 64,
17561765 .ErrorUnion => {
17571766 const pl_ty = ty.errorUnionPayload(mod);
1758 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1767 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17591768 return false;
17601769 }
17611770 return true;
......@@ -1764,7 +1773,7 @@ fn isByRef(ty: Type, mod: *Zcu) bool {
17641773 if (ty.isPtrLikeOptional(mod)) return false;
17651774 const pl_type = ty.optionalChild(mod);
17661775 if (pl_type.zigTypeTag(mod) == .ErrorSet) return false;
1767 return pl_type.hasRuntimeBitsIgnoreComptime(mod);
1776 return pl_type.hasRuntimeBitsIgnoreComptime(pt);
17681777 },
17691778 .Pointer => {
17701779 // Slices act like struct and will be passed by reference
......@@ -1783,11 +1792,11 @@ const SimdStoreStrategy = enum {
17831792/// This means when a given type is 128 bits and either the simd128 or relaxed-simd
17841793/// features are enabled, the function will return `.direct`. This would allow to store
17851794/// it using a instruction, rather than an unrolled version.
1786fn determineSimdStoreStrategy(ty: Type, mod: *Zcu) SimdStoreStrategy {
1787 std.debug.assert(ty.zigTypeTag(mod) == .Vector);
1788 if (ty.bitSize(mod) != 128) return .unrolled;
1795fn determineSimdStoreStrategy(ty: Type, pt: Zcu.PerThread) SimdStoreStrategy {
1796 std.debug.assert(ty.zigTypeTag(pt.zcu) == .Vector);
1797 if (ty.bitSize(pt) != 128) return .unrolled;
17891798 const hasFeature = std.Target.wasm.featureSetHas;
1790 const target = mod.getTarget();
1799 const target = pt.zcu.getTarget();
17911800 const features = target.cpu.features;
17921801 if (hasFeature(features, .relaxed_simd) or hasFeature(features, .simd128)) {
17931802 return .direct;
......@@ -2064,7 +2073,8 @@ fn genInst(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
20642073}
20652074
20662075fn genBody(func: *CodeGen, body: []const Air.Inst.Index) InnerError!void {
2067 const mod = func.bin_file.base.comp.module.?;
2076 const pt = func.pt;
2077 const mod = pt.zcu;
20682078 const ip = &mod.intern_pool;
20692079
20702080 for (body) |inst| {
......@@ -2085,7 +2095,8 @@ fn genBody(func: *CodeGen, body: []const Air.Inst.Index) InnerError!void {
20852095}
20862096
20872097fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2088 const mod = func.bin_file.base.comp.module.?;
2098 const pt = func.pt;
2099 const mod = pt.zcu;
20892100 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
20902101 const operand = try func.resolveInst(un_op);
20912102 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
......@@ -2095,27 +2106,27 @@ fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
20952106 // to the stack instead
20962107 if (func.return_value != .none) {
20972108 try func.store(func.return_value, operand, ret_ty, 0);
2098 } else if (fn_info.cc == .C and ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2109 } else if (fn_info.cc == .C and ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
20992110 switch (ret_ty.zigTypeTag(mod)) {
21002111 // Aggregate types can be lowered as a singular value
21012112 .Struct, .Union => {
2102 const scalar_type = abi.scalarType(ret_ty, mod);
2113 const scalar_type = abi.scalarType(ret_ty, pt);
21032114 try func.emitWValue(operand);
21042115 const opcode = buildOpcode(.{
21052116 .op = .load,
2106 .width = @as(u8, @intCast(scalar_type.abiSize(mod) * 8)),
2117 .width = @as(u8, @intCast(scalar_type.abiSize(pt) * 8)),
21072118 .signedness = if (scalar_type.isSignedInt(mod)) .signed else .unsigned,
2108 .valtype1 = typeToValtype(scalar_type, mod),
2119 .valtype1 = typeToValtype(scalar_type, pt),
21092120 });
21102121 try func.addMemArg(Mir.Inst.Tag.fromOpcode(opcode), .{
21112122 .offset = operand.offset(),
2112 .alignment = @intCast(scalar_type.abiAlignment(mod).toByteUnits().?),
2123 .alignment = @intCast(scalar_type.abiAlignment(pt).toByteUnits().?),
21132124 });
21142125 },
21152126 else => try func.emitWValue(operand),
21162127 }
21172128 } else {
2118 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and ret_ty.isError(mod)) {
2129 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and ret_ty.isError(mod)) {
21192130 try func.addImm32(0);
21202131 } else {
21212132 try func.emitWValue(operand);
......@@ -2128,16 +2139,17 @@ fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
21282139}
21292140
21302141fn airRetPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2131 const mod = func.bin_file.base.comp.module.?;
2142 const pt = func.pt;
2143 const mod = pt.zcu;
21322144 const child_type = func.typeOfIndex(inst).childType(mod);
21332145
21342146 const result = result: {
2135 if (!child_type.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
2147 if (!child_type.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
21362148 break :result try func.allocStack(Type.usize); // create pointer to void
21372149 }
21382150
21392151 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
2140 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
2152 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
21412153 break :result func.return_value;
21422154 }
21432155
......@@ -2148,17 +2160,18 @@ fn airRetPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
21482160}
21492161
21502162fn airRetLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2151 const mod = func.bin_file.base.comp.module.?;
2163 const pt = func.pt;
2164 const mod = pt.zcu;
21522165 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
21532166 const operand = try func.resolveInst(un_op);
21542167 const ret_ty = func.typeOf(un_op).childType(mod);
21552168
21562169 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
2157 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2170 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
21582171 if (ret_ty.isError(mod)) {
21592172 try func.addImm32(0);
21602173 }
2161 } else if (!firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
2174 } else if (!firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
21622175 // leave on the stack
21632176 _ = try func.load(operand, ret_ty, 0);
21642177 }
......@@ -2175,7 +2188,8 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21752188 const args = @as([]const Air.Inst.Ref, @ptrCast(func.air.extra[extra.end..][0..extra.data.args_len]));
21762189 const ty = func.typeOf(pl_op.operand);
21772190
2178 const mod = func.bin_file.base.comp.module.?;
2191 const pt = func.pt;
2192 const mod = pt.zcu;
21792193 const ip = &mod.intern_pool;
21802194 const fn_ty = switch (ty.zigTypeTag(mod)) {
21812195 .Fn => ty,
......@@ -2184,10 +2198,10 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21842198 };
21852199 const ret_ty = fn_ty.fnReturnType(mod);
21862200 const fn_info = mod.typeToFunc(fn_ty).?;
2187 const first_param_sret = firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod);
2201 const first_param_sret = firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt);
21882202
21892203 const callee: ?InternPool.DeclIndex = blk: {
2190 const func_val = (try func.air.value(pl_op.operand, mod)) orelse break :blk null;
2204 const func_val = (try func.air.value(pl_op.operand, pt)) orelse break :blk null;
21912205
21922206 if (func_val.getFunction(mod)) |function| {
21932207 _ = try func.bin_file.getOrCreateAtomForDecl(function.owner_decl);
......@@ -2195,7 +2209,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21952209 } else if (func_val.getExternFunc(mod)) |extern_func| {
21962210 const ext_decl = mod.declPtr(extern_func.decl);
21972211 const ext_info = mod.typeToFunc(ext_decl.typeOf(mod)).?;
2198 var func_type = try genFunctype(func.gpa, ext_info.cc, ext_info.param_types.get(ip), Type.fromInterned(ext_info.return_type), mod);
2212 var func_type = try genFunctype(func.gpa, ext_info.cc, ext_info.param_types.get(ip), Type.fromInterned(ext_info.return_type), pt);
21992213 defer func_type.deinit(func.gpa);
22002214 const atom_index = try func.bin_file.getOrCreateAtomForDecl(extern_func.decl);
22012215 const atom = func.bin_file.getAtomPtr(atom_index);
......@@ -2230,7 +2244,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22302244 const arg_val = try func.resolveInst(arg);
22312245
22322246 const arg_ty = func.typeOf(arg);
2233 if (!arg_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2247 if (!arg_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
22342248
22352249 try func.lowerArg(mod.typeToFunc(fn_ty).?.cc, arg_ty, arg_val);
22362250 }
......@@ -2245,7 +2259,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22452259 const operand = try func.resolveInst(pl_op.operand);
22462260 try func.emitWValue(operand);
22472261
2248 var fn_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), mod);
2262 var fn_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), pt);
22492263 defer fn_type.deinit(func.gpa);
22502264
22512265 const fn_type_index = try func.bin_file.zigObjectPtr().?.putOrGetFuncType(func.gpa, fn_type);
......@@ -2253,7 +2267,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22532267 }
22542268
22552269 const result_value = result_value: {
2256 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
2270 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
22572271 break :result_value WValue{ .none = {} };
22582272 } else if (ret_ty.isNoReturn(mod)) {
22592273 try func.addTag(.@"unreachable");
......@@ -2264,7 +2278,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22642278 } else if (mod.typeToFunc(fn_ty).?.cc == .C and ret_ty.zigTypeTag(mod) == .Struct or ret_ty.zigTypeTag(mod) == .Union) {
22652279 const result_local = try func.allocLocal(ret_ty);
22662280 try func.addLabel(.local_set, result_local.local.value);
2267 const scalar_type = abi.scalarType(ret_ty, mod);
2281 const scalar_type = abi.scalarType(ret_ty, pt);
22682282 const result = try func.allocStack(scalar_type);
22692283 try func.store(result, result_local, scalar_type, 0);
22702284 break :result_value result;
......@@ -2287,7 +2301,8 @@ fn airAlloc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
22872301}
22882302
22892303fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void {
2290 const mod = func.bin_file.base.comp.module.?;
2304 const pt = func.pt;
2305 const mod = pt.zcu;
22912306 if (safety) {
22922307 // TODO if the value is undef, write 0xaa bytes to dest
22932308 } else {
......@@ -2306,13 +2321,13 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23062321 } else {
23072322 // at this point we have a non-natural alignment, we must
23082323 // load the value, and then shift+or the rhs into the result location.
2309 const int_elem_ty = try mod.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
2324 const int_elem_ty = try pt.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
23102325
2311 if (isByRef(int_elem_ty, mod)) {
2326 if (isByRef(int_elem_ty, pt)) {
23122327 return func.fail("TODO: airStore for pointers to bitfields with backing type larger than 64bits", .{});
23132328 }
23142329
2315 var mask = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(ty.bitSize(mod)))) - 1));
2330 var mask = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(ty.bitSize(pt)))) - 1));
23162331 mask <<= @as(u6, @intCast(ptr_info.packed_offset.bit_offset));
23172332 mask ^= ~@as(u64, 0);
23182333 const shift_val = if (ptr_info.packed_offset.host_size <= 4)
......@@ -2324,9 +2339,9 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23242339 else
23252340 WValue{ .imm64 = mask };
23262341 const wrap_mask_val = if (ptr_info.packed_offset.host_size <= 4)
2327 WValue{ .imm32 = @truncate(~@as(u64, 0) >> @intCast(64 - ty.bitSize(mod))) }
2342 WValue{ .imm32 = @truncate(~@as(u64, 0) >> @intCast(64 - ty.bitSize(pt))) }
23282343 else
2329 WValue{ .imm64 = ~@as(u64, 0) >> @intCast(64 - ty.bitSize(mod)) };
2344 WValue{ .imm64 = ~@as(u64, 0) >> @intCast(64 - ty.bitSize(pt)) };
23302345
23312346 try func.emitWValue(lhs);
23322347 const loaded = try func.load(lhs, int_elem_ty, 0);
......@@ -2346,12 +2361,13 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23462361
23472362fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerError!void {
23482363 assert(!(lhs != .stack and rhs == .stack));
2349 const mod = func.bin_file.base.comp.module.?;
2350 const abi_size = ty.abiSize(mod);
2364 const pt = func.pt;
2365 const mod = pt.zcu;
2366 const abi_size = ty.abiSize(pt);
23512367 switch (ty.zigTypeTag(mod)) {
23522368 .ErrorUnion => {
23532369 const pl_ty = ty.errorUnionPayload(mod);
2354 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2370 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23552371 return func.store(lhs, rhs, Type.anyerror, 0);
23562372 }
23572373
......@@ -2363,7 +2379,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23632379 return func.store(lhs, rhs, Type.usize, 0);
23642380 }
23652381 const pl_ty = ty.optionalChild(mod);
2366 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2382 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23672383 return func.store(lhs, rhs, Type.u8, 0);
23682384 }
23692385 if (pl_ty.zigTypeTag(mod) == .ErrorSet) {
......@@ -2373,11 +2389,11 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23732389 const len = @as(u32, @intCast(abi_size));
23742390 return func.memcpy(lhs, rhs, .{ .imm32 = len });
23752391 },
2376 .Struct, .Array, .Union => if (isByRef(ty, mod)) {
2392 .Struct, .Array, .Union => if (isByRef(ty, pt)) {
23772393 const len = @as(u32, @intCast(abi_size));
23782394 return func.memcpy(lhs, rhs, .{ .imm32 = len });
23792395 },
2380 .Vector => switch (determineSimdStoreStrategy(ty, mod)) {
2396 .Vector => switch (determineSimdStoreStrategy(ty, pt)) {
23812397 .unrolled => {
23822398 const len: u32 = @intCast(abi_size);
23832399 return func.memcpy(lhs, rhs, .{ .imm32 = len });
......@@ -2391,7 +2407,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23912407 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
23922408 std.wasm.simdOpcode(.v128_store),
23932409 offset + lhs.offset(),
2394 @intCast(ty.abiAlignment(mod).toByteUnits() orelse 0),
2410 @intCast(ty.abiAlignment(pt).toByteUnits() orelse 0),
23952411 });
23962412 return func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
23972413 },
......@@ -2421,11 +2437,11 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24212437 try func.store(.{ .stack = {} }, msb, Type.u64, 8 + lhs.offset());
24222438 return;
24232439 } else if (abi_size > 16) {
2424 try func.memcpy(lhs, rhs, .{ .imm32 = @as(u32, @intCast(ty.abiSize(mod))) });
2440 try func.memcpy(lhs, rhs, .{ .imm32 = @as(u32, @intCast(ty.abiSize(pt))) });
24252441 },
24262442 else => if (abi_size > 8) {
24272443 return func.fail("TODO: `store` for type `{}` with abisize `{d}`", .{
2428 ty.fmt(func.bin_file.base.comp.module.?),
2444 ty.fmt(pt),
24292445 abi_size,
24302446 });
24312447 },
......@@ -2435,7 +2451,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24352451 // into lhs, so we calculate that and emit that instead
24362452 try func.lowerToStack(rhs);
24372453
2438 const valtype = typeToValtype(ty, mod);
2454 const valtype = typeToValtype(ty, pt);
24392455 const opcode = buildOpcode(.{
24402456 .valtype1 = valtype,
24412457 .width = @as(u8, @intCast(abi_size * 8)),
......@@ -2447,23 +2463,24 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24472463 Mir.Inst.Tag.fromOpcode(opcode),
24482464 .{
24492465 .offset = offset + lhs.offset(),
2450 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
2466 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
24512467 },
24522468 );
24532469}
24542470
24552471fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2456 const mod = func.bin_file.base.comp.module.?;
2472 const pt = func.pt;
2473 const mod = pt.zcu;
24572474 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
24582475 const operand = try func.resolveInst(ty_op.operand);
24592476 const ty = ty_op.ty.toType();
24602477 const ptr_ty = func.typeOf(ty_op.operand);
24612478 const ptr_info = ptr_ty.ptrInfo(mod);
24622479
2463 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return func.finishAir(inst, .none, &.{ty_op.operand});
2480 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return func.finishAir(inst, .none, &.{ty_op.operand});
24642481
24652482 const result = result: {
2466 if (isByRef(ty, mod)) {
2483 if (isByRef(ty, pt)) {
24672484 const new_local = try func.allocStack(ty);
24682485 try func.store(new_local, operand, ty, 0);
24692486 break :result new_local;
......@@ -2476,7 +2493,7 @@ fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
24762493
24772494 // at this point we have a non-natural alignment, we must
24782495 // shift the value to obtain the correct bit.
2479 const int_elem_ty = try mod.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
2496 const int_elem_ty = try pt.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
24802497 const shift_val = if (ptr_info.packed_offset.host_size <= 4)
24812498 WValue{ .imm32 = ptr_info.packed_offset.bit_offset }
24822499 else if (ptr_info.packed_offset.host_size <= 8)
......@@ -2496,7 +2513,8 @@ fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
24962513/// Loads an operand from the linear memory section.
24972514/// NOTE: Leaves the value on the stack.
24982515fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValue {
2499 const mod = func.bin_file.base.comp.module.?;
2516 const pt = func.pt;
2517 const mod = pt.zcu;
25002518 // load local's value from memory by its stack position
25012519 try func.emitWValue(operand);
25022520
......@@ -2507,15 +2525,15 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25072525 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
25082526 std.wasm.simdOpcode(.v128_load),
25092527 offset + operand.offset(),
2510 @intCast(ty.abiAlignment(mod).toByteUnits().?),
2528 @intCast(ty.abiAlignment(pt).toByteUnits().?),
25112529 });
25122530 try func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
25132531 return WValue{ .stack = {} };
25142532 }
25152533
2516 const abi_size: u8 = @intCast(ty.abiSize(mod));
2534 const abi_size: u8 = @intCast(ty.abiSize(pt));
25172535 const opcode = buildOpcode(.{
2518 .valtype1 = typeToValtype(ty, mod),
2536 .valtype1 = typeToValtype(ty, pt),
25192537 .width = abi_size * 8,
25202538 .op = .load,
25212539 .signedness = if (ty.isSignedInt(mod)) .signed else .unsigned,
......@@ -2525,7 +2543,7 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25252543 Mir.Inst.Tag.fromOpcode(opcode),
25262544 .{
25272545 .offset = offset + operand.offset(),
2528 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
2546 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
25292547 },
25302548 );
25312549
......@@ -2533,13 +2551,14 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25332551}
25342552
25352553fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2536 const mod = func.bin_file.base.comp.module.?;
2554 const pt = func.pt;
2555 const mod = pt.zcu;
25372556 const arg_index = func.arg_index;
25382557 const arg = func.args[arg_index];
25392558 const cc = mod.typeToFunc(func.decl.typeOf(mod)).?.cc;
25402559 const arg_ty = func.typeOfIndex(inst);
25412560 if (cc == .C) {
2542 const arg_classes = abi.classifyType(arg_ty, mod);
2561 const arg_classes = abi.classifyType(arg_ty, pt);
25432562 for (arg_classes) |class| {
25442563 if (class != .none) {
25452564 func.arg_index += 1;
......@@ -2552,7 +2571,7 @@ fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
25522571 if (arg_ty.zigTypeTag(mod) != .Int and arg_ty.zigTypeTag(mod) != .Float) {
25532572 return func.fail(
25542573 "TODO: Implement C-ABI argument for type '{}'",
2555 .{arg_ty.fmt(func.bin_file.base.comp.module.?)},
2574 .{arg_ty.fmt(pt)},
25562575 );
25572576 }
25582577 const result = try func.allocStack(arg_ty);
......@@ -2579,7 +2598,7 @@ fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
25792598}
25802599
25812600fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
2582 const mod = func.bin_file.base.comp.module.?;
2601 const pt = func.pt;
25832602 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
25842603 const lhs = try func.resolveInst(bin_op.lhs);
25852604 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -2593,10 +2612,10 @@ fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
25932612 // For big integers we can ignore this as we will call into compiler-rt which handles this.
25942613 const result = switch (op) {
25952614 .shr, .shl => res: {
2596 const lhs_wasm_bits = toWasmBits(@as(u16, @intCast(lhs_ty.bitSize(mod)))) orelse {
2615 const lhs_wasm_bits = toWasmBits(@intCast(lhs_ty.bitSize(pt))) orelse {
25972616 return func.fail("TODO: implement '{s}' for types larger than 128 bits", .{@tagName(op)});
25982617 };
2599 const rhs_wasm_bits = toWasmBits(@as(u16, @intCast(rhs_ty.bitSize(mod)))).?;
2618 const rhs_wasm_bits = toWasmBits(@intCast(rhs_ty.bitSize(pt))).?;
26002619 const new_rhs = if (lhs_wasm_bits != rhs_wasm_bits and lhs_wasm_bits != 128) blk: {
26012620 const tmp = try func.intcast(rhs, rhs_ty, lhs_ty);
26022621 break :blk try tmp.toLocal(func, lhs_ty);
......@@ -2616,7 +2635,8 @@ fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
26162635/// Performs a binary operation on the given `WValue`'s
26172636/// NOTE: THis leaves the value on top of the stack.
26182637fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
2619 const mod = func.bin_file.base.comp.module.?;
2638 const pt = func.pt;
2639 const mod = pt.zcu;
26202640 assert(!(lhs != .stack and rhs == .stack));
26212641
26222642 if (ty.isAnyFloat()) {
......@@ -2624,20 +2644,20 @@ fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!
26242644 return func.floatOp(float_op, ty, &.{ lhs, rhs });
26252645 }
26262646
2627 if (isByRef(ty, mod)) {
2647 if (isByRef(ty, pt)) {
26282648 if (ty.zigTypeTag(mod) == .Int) {
26292649 return func.binOpBigInt(lhs, rhs, ty, op);
26302650 } else {
26312651 return func.fail(
26322652 "TODO: Implement binary operation for type: {}",
2633 .{ty.fmt(func.bin_file.base.comp.module.?)},
2653 .{ty.fmt(pt)},
26342654 );
26352655 }
26362656 }
26372657
26382658 const opcode: wasm.Opcode = buildOpcode(.{
26392659 .op = op,
2640 .valtype1 = typeToValtype(ty, mod),
2660 .valtype1 = typeToValtype(ty, pt),
26412661 .signedness = if (ty.isSignedInt(mod)) .signed else .unsigned,
26422662 });
26432663 try func.emitWValue(lhs);
......@@ -2649,7 +2669,8 @@ fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!
26492669}
26502670
26512671fn binOpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
2652 const mod = func.bin_file.base.comp.module.?;
2672 const pt = func.pt;
2673 const mod = pt.zcu;
26532674 const int_info = ty.intInfo(mod);
26542675 if (int_info.bits > 128) {
26552676 return func.fail("TODO: Implement binary operation for big integers larger than 128 bits", .{});
......@@ -2785,7 +2806,8 @@ const FloatOp = enum {
27852806};
27862807
27872808fn airAbs(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2788 const mod = func.bin_file.base.comp.module.?;
2809 const pt = func.pt;
2810 const mod = pt.zcu;
27892811 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27902812 const operand = try func.resolveInst(ty_op.operand);
27912813 const ty = func.typeOf(ty_op.operand);
......@@ -2793,7 +2815,7 @@ fn airAbs(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
27932815
27942816 switch (scalar_ty.zigTypeTag(mod)) {
27952817 .Int => if (ty.zigTypeTag(mod) == .Vector) {
2796 return func.fail("TODO implement airAbs for {}", .{ty.fmt(mod)});
2818 return func.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
27972819 } else {
27982820 const int_bits = ty.intInfo(mod).bits;
27992821 const wasm_bits = toWasmBits(int_bits) orelse {
......@@ -2877,7 +2899,8 @@ fn airUnaryFloatOp(func: *CodeGen, inst: Air.Inst.Index, op: FloatOp) InnerError
28772899}
28782900
28792901fn floatOp(func: *CodeGen, float_op: FloatOp, ty: Type, args: []const WValue) InnerError!WValue {
2880 const mod = func.bin_file.base.comp.module.?;
2902 const pt = func.pt;
2903 const mod = pt.zcu;
28812904 if (ty.zigTypeTag(mod) == .Vector) {
28822905 return func.fail("TODO: Implement floatOps for vectors", .{});
28832906 }
......@@ -2893,7 +2916,7 @@ fn floatOp(func: *CodeGen, float_op: FloatOp, ty: Type, args: []const WValue) In
28932916 for (args) |operand| {
28942917 try func.emitWValue(operand);
28952918 }
2896 const opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(ty, mod) });
2919 const opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(ty, pt) });
28972920 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
28982921 return .stack;
28992922 }
......@@ -2983,7 +3006,8 @@ fn floatNeg(func: *CodeGen, ty: Type, arg: WValue) InnerError!WValue {
29833006}
29843007
29853008fn airWrapBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
2986 const mod = func.bin_file.base.comp.module.?;
3009 const pt = func.pt;
3010 const mod = pt.zcu;
29873011 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
29883012
29893013 const lhs = try func.resolveInst(bin_op.lhs);
......@@ -3002,10 +3026,10 @@ fn airWrapBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
30023026 // For big integers we can ignore this as we will call into compiler-rt which handles this.
30033027 const result = switch (op) {
30043028 .shr, .shl => res: {
3005 const lhs_wasm_bits = toWasmBits(@as(u16, @intCast(lhs_ty.bitSize(mod)))) orelse {
3029 const lhs_wasm_bits = toWasmBits(@intCast(lhs_ty.bitSize(pt))) orelse {
30063030 return func.fail("TODO: implement '{s}' for types larger than 128 bits", .{@tagName(op)});
30073031 };
3008 const rhs_wasm_bits = toWasmBits(@as(u16, @intCast(rhs_ty.bitSize(mod)))).?;
3032 const rhs_wasm_bits = toWasmBits(@intCast(rhs_ty.bitSize(pt))).?;
30093033 const new_rhs = if (lhs_wasm_bits != rhs_wasm_bits and lhs_wasm_bits != 128) blk: {
30103034 const tmp = try func.intcast(rhs, rhs_ty, lhs_ty);
30113035 break :blk try tmp.toLocal(func, lhs_ty);
......@@ -3034,9 +3058,10 @@ fn wrapBinOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerEr
30343058/// Asserts `Type` is <= 128 bits.
30353059/// NOTE: When the Type is <= 64 bits, leaves the value on top of the stack, if wrapping was needed.
30363060fn wrapOperand(func: *CodeGen, operand: WValue, ty: Type) InnerError!WValue {
3037 const mod = func.bin_file.base.comp.module.?;
3038 assert(ty.abiSize(mod) <= 16);
3039 const int_bits = @as(u16, @intCast(ty.bitSize(mod))); // TODO use ty.intInfo(mod).bits
3061 const pt = func.pt;
3062 const mod = pt.zcu;
3063 assert(ty.abiSize(pt) <= 16);
3064 const int_bits: u16 = @intCast(ty.bitSize(pt)); // TODO use ty.intInfo(mod).bits
30403065 const wasm_bits = toWasmBits(int_bits) orelse {
30413066 return func.fail("TODO: Implement wrapOperand for bitsize '{d}'", .{int_bits});
30423067 };
......@@ -3098,13 +3123,14 @@ fn wrapOperand(func: *CodeGen, operand: WValue, ty: Type) InnerError!WValue {
30983123}
30993124
31003125fn lowerPtr(func: *CodeGen, ptr_val: InternPool.Index, prev_offset: u64) InnerError!WValue {
3101 const zcu = func.bin_file.base.comp.module.?;
3126 const pt = func.pt;
3127 const zcu = pt.zcu;
31023128 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
31033129 const offset: u64 = prev_offset + ptr.byte_offset;
31043130 return switch (ptr.base_addr) {
31053131 .decl => |decl| return func.lowerDeclRefValue(decl, @intCast(offset)),
31063132 .anon_decl => |ad| return func.lowerAnonDeclRef(ad, @intCast(offset)),
3107 .int => return func.lowerConstant(try zcu.intValue(Type.usize, offset), Type.usize),
3133 .int => return func.lowerConstant(try pt.intValue(Type.usize, offset), Type.usize),
31083134 .eu_payload => return func.fail("Wasm TODO: lower error union payload pointer", .{}),
31093135 .opt_payload => |opt_ptr| return func.lowerPtr(opt_ptr, offset),
31103136 .field => |field| {
......@@ -3120,13 +3146,13 @@ fn lowerPtr(func: *CodeGen, ptr_val: InternPool.Index, prev_offset: u64) InnerEr
31203146 };
31213147 },
31223148 .Struct => switch (base_ty.containerLayout(zcu)) {
3123 .auto => base_ty.structFieldOffset(@intCast(field.index), zcu),
3149 .auto => base_ty.structFieldOffset(@intCast(field.index), pt),
31243150 .@"extern", .@"packed" => unreachable,
31253151 },
31263152 .Union => switch (base_ty.containerLayout(zcu)) {
31273153 .auto => off: {
31283154 // Keep in sync with the `un` case of `generateSymbol`.
3129 const layout = base_ty.unionGetLayout(zcu);
3155 const layout = base_ty.unionGetLayout(pt);
31303156 if (layout.payload_size == 0) break :off 0;
31313157 if (layout.tag_size == 0) break :off 0;
31323158 if (layout.tag_align.compare(.gte, layout.payload_align)) {
......@@ -3152,17 +3178,18 @@ fn lowerAnonDeclRef(
31523178 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
31533179 offset: u32,
31543180) InnerError!WValue {
3155 const mod = func.bin_file.base.comp.module.?;
3181 const pt = func.pt;
3182 const mod = pt.zcu;
31563183 const decl_val = anon_decl.val;
31573184 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
31583185
31593186 const is_fn_body = ty.zigTypeTag(mod) == .Fn;
3160 if (!is_fn_body and !ty.hasRuntimeBitsIgnoreComptime(mod)) {
3187 if (!is_fn_body and !ty.hasRuntimeBitsIgnoreComptime(pt)) {
31613188 return WValue{ .imm32 = 0xaaaaaaaa };
31623189 }
31633190
31643191 const decl_align = mod.intern_pool.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;
3165 const res = try func.bin_file.lowerAnonDecl(decl_val, decl_align, func.decl.navSrcLoc(mod));
3192 const res = try func.bin_file.lowerAnonDecl(pt, decl_val, decl_align, func.decl.navSrcLoc(mod));
31663193 switch (res) {
31673194 .ok => {},
31683195 .fail => |em| {
......@@ -3180,7 +3207,8 @@ fn lowerAnonDeclRef(
31803207}
31813208
31823209fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u32) InnerError!WValue {
3183 const mod = func.bin_file.base.comp.module.?;
3210 const pt = func.pt;
3211 const mod = pt.zcu;
31843212
31853213 const decl = mod.declPtr(decl_index);
31863214 // check if decl is an alias to a function, in which case we
......@@ -3195,7 +3223,7 @@ fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u
31953223 }
31963224 }
31973225 const decl_ty = decl.typeOf(mod);
3198 if (decl_ty.zigTypeTag(mod) != .Fn and !decl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3226 if (decl_ty.zigTypeTag(mod) != .Fn and !decl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
31993227 return WValue{ .imm32 = 0xaaaaaaaa };
32003228 }
32013229
......@@ -3212,8 +3240,9 @@ fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u
32123240
32133241/// Asserts that `isByRef` returns `false` for `ty`.
32143242fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
3215 const mod = func.bin_file.base.comp.module.?;
3216 assert(!isByRef(ty, mod));
3243 const pt = func.pt;
3244 const mod = pt.zcu;
3245 assert(!isByRef(ty, pt));
32173246 const ip = &mod.intern_pool;
32183247 if (val.isUndefDeep(mod)) return func.emitUndefined(ty);
32193248
......@@ -3261,13 +3290,13 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
32613290 const int_info = ty.intInfo(mod);
32623291 switch (int_info.signedness) {
32633292 .signed => switch (int_info.bits) {
3264 0...32 => return WValue{ .imm32 = @bitCast(@as(i32, @intCast(val.toSignedInt(mod)))) },
3265 33...64 => return WValue{ .imm64 = @bitCast(val.toSignedInt(mod)) },
3293 0...32 => return WValue{ .imm32 = @bitCast(@as(i32, @intCast(val.toSignedInt(pt)))) },
3294 33...64 => return WValue{ .imm64 = @bitCast(val.toSignedInt(pt)) },
32663295 else => unreachable,
32673296 },
32683297 .unsigned => switch (int_info.bits) {
3269 0...32 => return WValue{ .imm32 = @intCast(val.toUnsignedInt(mod)) },
3270 33...64 => return WValue{ .imm64 = val.toUnsignedInt(mod) },
3298 0...32 => return WValue{ .imm32 = @intCast(val.toUnsignedInt(pt)) },
3299 33...64 => return WValue{ .imm64 = val.toUnsignedInt(pt) },
32713300 else => unreachable,
32723301 },
32733302 }
......@@ -3277,22 +3306,22 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
32773306 return WValue{ .imm32 = int };
32783307 },
32793308 .error_union => |error_union| {
3280 const err_int_ty = try mod.errorIntType();
3309 const err_int_ty = try pt.errorIntType();
32813310 const err_ty, const err_val = switch (error_union.val) {
32823311 .err_name => |err_name| .{
32833312 ty.errorUnionSet(mod),
3284 Value.fromInterned((try mod.intern(.{ .err = .{
3313 Value.fromInterned(try pt.intern(.{ .err = .{
32853314 .ty = ty.errorUnionSet(mod).toIntern(),
32863315 .name = err_name,
3287 } }))),
3316 } })),
32883317 },
32893318 .payload => .{
32903319 err_int_ty,
3291 try mod.intValue(err_int_ty, 0),
3320 try pt.intValue(err_int_ty, 0),
32923321 },
32933322 };
32943323 const payload_type = ty.errorUnionPayload(mod);
3295 if (!payload_type.hasRuntimeBitsIgnoreComptime(mod)) {
3324 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
32963325 // We use the error type directly as the type.
32973326 return func.lowerConstant(err_val, err_ty);
32983327 }
......@@ -3318,7 +3347,7 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33183347 .field => |base_index| ptr = ip.indexToKey(base_index.base).ptr,
33193348 .arr_elem, .comptime_field, .comptime_alloc => unreachable,
33203349 };
3321 return .{ .memory = try func.bin_file.lowerUnnamedConst(val, owner_decl) };
3350 return .{ .memory = try func.bin_file.lowerUnnamedConst(pt, val, owner_decl) };
33223351 },
33233352 .ptr => return func.lowerPtr(val.toIntern(), 0),
33243353 .opt => if (ty.optionalReprIsPayload(mod)) {
......@@ -3332,11 +3361,11 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33323361 return WValue{ .imm32 = @intFromBool(!val.isNull(mod)) };
33333362 },
33343363 .aggregate => switch (ip.indexToKey(ty.ip_index)) {
3335 .array_type => return func.fail("Wasm TODO: LowerConstant for {}", .{ty.fmt(mod)}),
3364 .array_type => return func.fail("Wasm TODO: LowerConstant for {}", .{ty.fmt(pt)}),
33363365 .vector_type => {
3337 assert(determineSimdStoreStrategy(ty, mod) == .direct);
3366 assert(determineSimdStoreStrategy(ty, pt) == .direct);
33383367 var buf: [16]u8 = undefined;
3339 val.writeToMemory(ty, mod, &buf) catch unreachable;
3368 val.writeToMemory(ty, pt, &buf) catch unreachable;
33403369 return func.storeSimdImmd(buf);
33413370 },
33423371 .struct_type => {
......@@ -3345,9 +3374,9 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33453374 // are by-ref types.
33463375 assert(struct_type.layout == .@"packed");
33473376 var buf: [8]u8 = .{0} ** 8; // zero the buffer so we do not read 0xaa as integer
3348 val.writeToPackedMemory(ty, mod, &buf, 0) catch unreachable;
3377 val.writeToPackedMemory(ty, pt, &buf, 0) catch unreachable;
33493378 const backing_int_ty = Type.fromInterned(struct_type.backingIntType(ip).*);
3350 const int_val = try mod.intValue(
3379 const int_val = try pt.intValue(
33513380 backing_int_ty,
33523381 mem.readInt(u64, &buf, .little),
33533382 );
......@@ -3358,7 +3387,7 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33583387 .un => |un| {
33593388 // in this case we have a packed union which will not be passed by reference.
33603389 const constant_ty = if (un.tag == .none)
3361 try ty.unionBackingType(mod)
3390 try ty.unionBackingType(pt)
33623391 else field_ty: {
33633392 const union_obj = mod.typeToUnion(ty).?;
33643393 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
......@@ -3379,7 +3408,8 @@ fn storeSimdImmd(func: *CodeGen, value: [16]u8) !WValue {
33793408}
33803409
33813410fn emitUndefined(func: *CodeGen, ty: Type) InnerError!WValue {
3382 const mod = func.bin_file.base.comp.module.?;
3411 const pt = func.pt;
3412 const mod = pt.zcu;
33833413 const ip = &mod.intern_pool;
33843414 switch (ty.zigTypeTag(mod)) {
33853415 .Bool, .ErrorSet => return WValue{ .imm32 = 0xaaaaaaaa },
......@@ -3421,15 +3451,16 @@ fn emitUndefined(func: *CodeGen, ty: Type) InnerError!WValue {
34213451/// It's illegal to provide a value with a type that cannot be represented
34223452/// as an integer value.
34233453fn valueAsI32(func: *const CodeGen, val: Value, ty: Type) i32 {
3424 const mod = func.bin_file.base.comp.module.?;
3454 const pt = func.pt;
3455 const mod = pt.zcu;
34253456
34263457 switch (val.ip_index) {
34273458 .none => {},
34283459 .bool_true => return 1,
34293460 .bool_false => return 0,
34303461 else => return switch (mod.intern_pool.indexToKey(val.ip_index)) {
3431 .enum_tag => |enum_tag| intIndexAsI32(&mod.intern_pool, enum_tag.int, mod),
3432 .int => |int| intStorageAsI32(int.storage, mod),
3462 .enum_tag => |enum_tag| intIndexAsI32(&mod.intern_pool, enum_tag.int, pt),
3463 .int => |int| intStorageAsI32(int.storage, pt),
34333464 .ptr => |ptr| {
34343465 assert(ptr.base_addr == .int);
34353466 return @intCast(ptr.byte_offset);
......@@ -3445,17 +3476,17 @@ fn valueAsI32(func: *const CodeGen, val: Value, ty: Type) i32 {
34453476 };
34463477}
34473478
3448fn intIndexAsI32(ip: *const InternPool, int: InternPool.Index, mod: *Zcu) i32 {
3449 return intStorageAsI32(ip.indexToKey(int).int.storage, mod);
3479fn intIndexAsI32(ip: *const InternPool, int: InternPool.Index, pt: Zcu.PerThread) i32 {
3480 return intStorageAsI32(ip.indexToKey(int).int.storage, pt);
34503481}
34513482
3452fn intStorageAsI32(storage: InternPool.Key.Int.Storage, mod: *Zcu) i32 {
3483fn intStorageAsI32(storage: InternPool.Key.Int.Storage, pt: Zcu.PerThread) i32 {
34533484 return switch (storage) {
34543485 .i64 => |x| @as(i32, @intCast(x)),
34553486 .u64 => |x| @as(i32, @bitCast(@as(u32, @intCast(x)))),
34563487 .big_int => unreachable,
3457 .lazy_align => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0)))),
3458 .lazy_size => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiSize(mod))))),
3488 .lazy_align => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0)))),
3489 .lazy_size => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiSize(pt))))),
34593490 };
34603491}
34613492
......@@ -3466,12 +3497,12 @@ fn airBlock(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
34663497}
34673498
34683499fn lowerBlock(func: *CodeGen, inst: Air.Inst.Index, block_ty: Type, body: []const Air.Inst.Index) InnerError!void {
3469 const mod = func.bin_file.base.comp.module.?;
3470 const wasm_block_ty = genBlockType(block_ty, mod);
3500 const pt = func.pt;
3501 const wasm_block_ty = genBlockType(block_ty, pt);
34713502
34723503 // if wasm_block_ty is non-empty, we create a register to store the temporary value
34733504 const block_result: WValue = if (wasm_block_ty != wasm.block_empty) blk: {
3474 const ty: Type = if (isByRef(block_ty, mod)) Type.u32 else block_ty;
3505 const ty: Type = if (isByRef(block_ty, pt)) Type.u32 else block_ty;
34753506 break :blk try func.ensureAllocLocal(ty); // make sure it's a clean local as it may never get overwritten
34763507 } else WValue.none;
34773508
......@@ -3583,10 +3614,11 @@ fn airCmp(func: *CodeGen, inst: Air.Inst.Index, op: std.math.CompareOperator) In
35833614/// NOTE: This leaves the result on top of the stack, rather than a new local.
35843615fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareOperator) InnerError!WValue {
35853616 assert(!(lhs != .stack and rhs == .stack));
3586 const mod = func.bin_file.base.comp.module.?;
3617 const pt = func.pt;
3618 const mod = pt.zcu;
35873619 if (ty.zigTypeTag(mod) == .Optional and !ty.optionalReprIsPayload(mod)) {
35883620 const payload_ty = ty.optionalChild(mod);
3589 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3621 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35903622 // When we hit this case, we must check the value of optionals
35913623 // that are not pointers. This means first checking against non-null for
35923624 // both lhs and rhs, as well as checking the payload are matching of lhs and rhs
......@@ -3594,7 +3626,7 @@ fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareO
35943626 }
35953627 } else if (ty.isAnyFloat()) {
35963628 return func.cmpFloat(ty, lhs, rhs, op);
3597 } else if (isByRef(ty, mod)) {
3629 } else if (isByRef(ty, pt)) {
35983630 return func.cmpBigInt(lhs, rhs, ty, op);
35993631 }
36003632
......@@ -3612,7 +3644,7 @@ fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareO
36123644 try func.lowerToStack(rhs);
36133645
36143646 const opcode: wasm.Opcode = buildOpcode(.{
3615 .valtype1 = typeToValtype(ty, mod),
3647 .valtype1 = typeToValtype(ty, pt),
36163648 .op = switch (op) {
36173649 .lt => .lt,
36183650 .lte => .le,
......@@ -3683,8 +3715,8 @@ fn airCmpLtErrorsLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
36833715 const errors_len = WValue{ .memory = @intFromEnum(sym_index) };
36843716
36853717 try func.emitWValue(operand);
3686 const mod = func.bin_file.base.comp.module.?;
3687 const err_int_ty = try mod.errorIntType();
3718 const pt = func.pt;
3719 const err_int_ty = try pt.errorIntType();
36883720 const errors_len_val = try func.load(errors_len, err_int_ty, 0);
36893721 const result = try func.cmp(.stack, errors_len_val, err_int_ty, .lt);
36903722
......@@ -3692,12 +3724,12 @@ fn airCmpLtErrorsLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
36923724}
36933725
36943726fn airBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3695 const mod = func.bin_file.base.comp.module.?;
3727 const pt = func.pt;
36963728 const br = func.air.instructions.items(.data)[@intFromEnum(inst)].br;
36973729 const block = func.blocks.get(br.block_inst).?;
36983730
36993731 // if operand has codegen bits we should break with a value
3700 if (func.typeOf(br.operand).hasRuntimeBitsIgnoreComptime(mod)) {
3732 if (func.typeOf(br.operand).hasRuntimeBitsIgnoreComptime(pt)) {
37013733 const operand = try func.resolveInst(br.operand);
37023734 try func.lowerToStack(operand);
37033735
......@@ -3719,7 +3751,8 @@ fn airNot(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37193751
37203752 const operand = try func.resolveInst(ty_op.operand);
37213753 const operand_ty = func.typeOf(ty_op.operand);
3722 const mod = func.bin_file.base.comp.module.?;
3754 const pt = func.pt;
3755 const mod = pt.zcu;
37233756
37243757 const result = result: {
37253758 if (operand_ty.zigTypeTag(mod) == .Bool) {
......@@ -3731,7 +3764,7 @@ fn airNot(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37313764 } else {
37323765 const int_info = operand_ty.intInfo(mod);
37333766 const wasm_bits = toWasmBits(int_info.bits) orelse {
3734 return func.fail("TODO: Implement binary NOT for {}", .{operand_ty.fmt(mod)});
3767 return func.fail("TODO: Implement binary NOT for {}", .{operand_ty.fmt(pt)});
37353768 };
37363769
37373770 switch (wasm_bits) {
......@@ -3798,13 +3831,14 @@ fn airUnreachable(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37983831}
37993832
38003833fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3801 const mod = func.bin_file.base.comp.module.?;
3834 const pt = func.pt;
3835 const mod = pt.zcu;
38023836 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38033837 const operand = try func.resolveInst(ty_op.operand);
38043838 const wanted_ty = func.typeOfIndex(inst);
38053839 const given_ty = func.typeOf(ty_op.operand);
38063840
3807 const bit_size = given_ty.bitSize(mod);
3841 const bit_size = given_ty.bitSize(pt);
38083842 const needs_wrapping = (given_ty.isSignedInt(mod) != wanted_ty.isSignedInt(mod)) and
38093843 bit_size != 32 and bit_size != 64 and bit_size != 128;
38103844
......@@ -3814,7 +3848,7 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38143848 break :result try bitcast_result.toLocal(func, wanted_ty);
38153849 }
38163850
3817 if (isByRef(given_ty, mod) and !isByRef(wanted_ty, mod)) {
3851 if (isByRef(given_ty, pt) and !isByRef(wanted_ty, pt)) {
38183852 const loaded_memory = try func.load(operand, wanted_ty, 0);
38193853 if (needs_wrapping) {
38203854 break :result try (try func.wrapOperand(loaded_memory, wanted_ty)).toLocal(func, wanted_ty);
......@@ -3822,7 +3856,7 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38223856 break :result try loaded_memory.toLocal(func, wanted_ty);
38233857 }
38243858 }
3825 if (!isByRef(given_ty, mod) and isByRef(wanted_ty, mod)) {
3859 if (!isByRef(given_ty, pt) and isByRef(wanted_ty, pt)) {
38263860 const stack_memory = try func.allocStack(wanted_ty);
38273861 try func.store(stack_memory, operand, given_ty, 0);
38283862 if (needs_wrapping) {
......@@ -3842,17 +3876,18 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38423876}
38433877
38443878fn bitcast(func: *CodeGen, wanted_ty: Type, given_ty: Type, operand: WValue) InnerError!WValue {
3845 const mod = func.bin_file.base.comp.module.?;
3879 const pt = func.pt;
3880 const mod = pt.zcu;
38463881 // if we bitcast a float to or from an integer we must use the 'reinterpret' instruction
38473882 if (!(wanted_ty.isAnyFloat() or given_ty.isAnyFloat())) return operand;
38483883 if (wanted_ty.ip_index == .f16_type or given_ty.ip_index == .f16_type) return operand;
3849 if (wanted_ty.bitSize(mod) > 64) return operand;
3884 if (wanted_ty.bitSize(pt) > 64) return operand;
38503885 assert((wanted_ty.isInt(mod) and given_ty.isAnyFloat()) or (wanted_ty.isAnyFloat() and given_ty.isInt(mod)));
38513886
38523887 const opcode = buildOpcode(.{
38533888 .op = .reinterpret,
3854 .valtype1 = typeToValtype(wanted_ty, mod),
3855 .valtype2 = typeToValtype(given_ty, mod),
3889 .valtype1 = typeToValtype(wanted_ty, pt),
3890 .valtype2 = typeToValtype(given_ty, pt),
38563891 });
38573892 try func.emitWValue(operand);
38583893 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
......@@ -3860,7 +3895,8 @@ fn bitcast(func: *CodeGen, wanted_ty: Type, given_ty: Type, operand: WValue) Inn
38603895}
38613896
38623897fn airStructFieldPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3863 const mod = func.bin_file.base.comp.module.?;
3898 const pt = func.pt;
3899 const mod = pt.zcu;
38643900 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
38653901 const extra = func.air.extraData(Air.StructField, ty_pl.payload);
38663902
......@@ -3872,7 +3908,8 @@ fn airStructFieldPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38723908}
38733909
38743910fn airStructFieldPtrIndex(func: *CodeGen, inst: Air.Inst.Index, index: u32) InnerError!void {
3875 const mod = func.bin_file.base.comp.module.?;
3911 const pt = func.pt;
3912 const mod = pt.zcu;
38763913 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38773914 const struct_ptr = try func.resolveInst(ty_op.operand);
38783915 const struct_ptr_ty = func.typeOf(ty_op.operand);
......@@ -3891,7 +3928,8 @@ fn structFieldPtr(
38913928 struct_ty: Type,
38923929 index: u32,
38933930) InnerError!WValue {
3894 const mod = func.bin_file.base.comp.module.?;
3931 const pt = func.pt;
3932 const mod = pt.zcu;
38953933 const result_ty = func.typeOfIndex(inst);
38963934 const struct_ptr_ty_info = struct_ptr_ty.ptrInfo(mod);
38973935
......@@ -3902,12 +3940,12 @@ fn structFieldPtr(
39023940 break :offset @as(u32, 0);
39033941 }
39043942 const struct_type = mod.typeToStruct(struct_ty).?;
3905 break :offset @divExact(mod.structPackedFieldBitOffset(struct_type, index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
3943 break :offset @divExact(pt.structPackedFieldBitOffset(struct_type, index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
39063944 },
39073945 .Union => 0,
39083946 else => unreachable,
39093947 },
3910 else => struct_ty.structFieldOffset(index, mod),
3948 else => struct_ty.structFieldOffset(index, pt),
39113949 };
39123950 // save a load and store when we can simply reuse the operand
39133951 if (offset == 0) {
......@@ -3922,7 +3960,8 @@ fn structFieldPtr(
39223960}
39233961
39243962fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3925 const mod = func.bin_file.base.comp.module.?;
3963 const pt = func.pt;
3964 const mod = pt.zcu;
39263965 const ip = &mod.intern_pool;
39273966 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39283967 const struct_field = func.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -3931,13 +3970,13 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39313970 const operand = try func.resolveInst(struct_field.struct_operand);
39323971 const field_index = struct_field.field_index;
39333972 const field_ty = struct_ty.structFieldType(field_index, mod);
3934 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return func.finishAir(inst, .none, &.{struct_field.struct_operand});
3973 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return func.finishAir(inst, .none, &.{struct_field.struct_operand});
39353974
39363975 const result = switch (struct_ty.containerLayout(mod)) {
39373976 .@"packed" => switch (struct_ty.zigTypeTag(mod)) {
39383977 .Struct => result: {
39393978 const packed_struct = mod.typeToPackedStruct(struct_ty).?;
3940 const offset = mod.structPackedFieldBitOffset(packed_struct, field_index);
3979 const offset = pt.structPackedFieldBitOffset(packed_struct, field_index);
39413980 const backing_ty = Type.fromInterned(packed_struct.backingIntType(ip).*);
39423981 const wasm_bits = toWasmBits(backing_ty.intInfo(mod).bits) orelse {
39433982 return func.fail("TODO: airStructFieldVal for packed structs larger than 128 bits", .{});
......@@ -3956,7 +3995,7 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39563995 try func.binOp(operand, const_wvalue, backing_ty, .shr);
39573996
39583997 if (field_ty.zigTypeTag(mod) == .Float) {
3959 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
3998 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39603999 const truncated = try func.trunc(shifted_value, int_type, backing_ty);
39614000 const bitcasted = try func.bitcast(field_ty, int_type, truncated);
39624001 break :result try bitcasted.toLocal(func, field_ty);
......@@ -3965,7 +4004,7 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39654004 // we can simply reuse the operand.
39664005 break :result func.reuseOperand(struct_field.struct_operand, operand);
39674006 } else if (field_ty.isPtrAtRuntime(mod)) {
3968 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4007 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39694008 const truncated = try func.trunc(shifted_value, int_type, backing_ty);
39704009 break :result try truncated.toLocal(func, field_ty);
39714010 }
......@@ -3973,8 +4012,8 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39734012 break :result try truncated.toLocal(func, field_ty);
39744013 },
39754014 .Union => result: {
3976 if (isByRef(struct_ty, mod)) {
3977 if (!isByRef(field_ty, mod)) {
4015 if (isByRef(struct_ty, pt)) {
4016 if (!isByRef(field_ty, pt)) {
39784017 const val = try func.load(operand, field_ty, 0);
39794018 break :result try val.toLocal(func, field_ty);
39804019 } else {
......@@ -3984,14 +4023,14 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39844023 }
39854024 }
39864025
3987 const union_int_type = try mod.intType(.unsigned, @as(u16, @intCast(struct_ty.bitSize(mod))));
4026 const union_int_type = try pt.intType(.unsigned, @as(u16, @intCast(struct_ty.bitSize(pt))));
39884027 if (field_ty.zigTypeTag(mod) == .Float) {
3989 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4028 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39904029 const truncated = try func.trunc(operand, int_type, union_int_type);
39914030 const bitcasted = try func.bitcast(field_ty, int_type, truncated);
39924031 break :result try bitcasted.toLocal(func, field_ty);
39934032 } else if (field_ty.isPtrAtRuntime(mod)) {
3994 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4033 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39954034 const truncated = try func.trunc(operand, int_type, union_int_type);
39964035 break :result try truncated.toLocal(func, field_ty);
39974036 }
......@@ -4001,10 +4040,10 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40014040 else => unreachable,
40024041 },
40034042 else => result: {
4004 const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, mod)) orelse {
4005 return func.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(mod)});
4043 const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, pt)) orelse {
4044 return func.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(pt)});
40064045 };
4007 if (isByRef(field_ty, mod)) {
4046 if (isByRef(field_ty, pt)) {
40084047 switch (operand) {
40094048 .stack_offset => |stack_offset| {
40104049 break :result WValue{ .stack_offset = .{ .value = stack_offset.value + offset, .references = 1 } };
......@@ -4021,7 +4060,8 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40214060}
40224061
40234062fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4024 const mod = func.bin_file.base.comp.module.?;
4063 const pt = func.pt;
4064 const mod = pt.zcu;
40254065 // result type is always 'noreturn'
40264066 const blocktype = wasm.block_empty;
40274067 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -4055,7 +4095,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40554095 errdefer func.gpa.free(values);
40564096
40574097 for (items, 0..) |ref, i| {
4058 const item_val = (try func.air.value(ref, mod)).?;
4098 const item_val = (try func.air.value(ref, pt)).?;
40594099 const int_val = func.valueAsI32(item_val, target_ty);
40604100 if (lowest_maybe == null or int_val < lowest_maybe.?) {
40614101 lowest_maybe = int_val;
......@@ -4078,7 +4118,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40784118 // When the target is an integer size larger than u32, we have no way to use the value
40794119 // as an index, therefore we also use an if/else-chain for those cases.
40804120 // TODO: Benchmark this to find a proper value, LLVM seems to draw the line at '40~45'.
4081 const is_sparse = highest - lowest > 50 or target_ty.bitSize(mod) > 32;
4121 const is_sparse = highest - lowest > 50 or target_ty.bitSize(pt) > 32;
40824122
40834123 const else_body: []const Air.Inst.Index = @ptrCast(func.air.extra[extra_index..][0..switch_br.data.else_body_len]);
40844124 const has_else_body = else_body.len != 0;
......@@ -4150,7 +4190,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
41504190 const val = try func.lowerConstant(case.values[0].value, target_ty);
41514191 try func.emitWValue(val);
41524192 const opcode = buildOpcode(.{
4153 .valtype1 = typeToValtype(target_ty, mod),
4193 .valtype1 = typeToValtype(target_ty, pt),
41544194 .op = .ne, // not equal, because we want to jump out of this block if it does not match the condition.
41554195 .signedness = signedness,
41564196 });
......@@ -4164,7 +4204,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
41644204 const val = try func.lowerConstant(value.value, target_ty);
41654205 try func.emitWValue(val);
41664206 const opcode = buildOpcode(.{
4167 .valtype1 = typeToValtype(target_ty, mod),
4207 .valtype1 = typeToValtype(target_ty, pt),
41684208 .op = .eq,
41694209 .signedness = signedness,
41704210 });
......@@ -4201,7 +4241,8 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
42014241}
42024242
42034243fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerError!void {
4204 const mod = func.bin_file.base.comp.module.?;
4244 const pt = func.pt;
4245 const mod = pt.zcu;
42054246 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
42064247 const operand = try func.resolveInst(un_op);
42074248 const err_union_ty = func.typeOf(un_op);
......@@ -4217,10 +4258,10 @@ fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerErro
42174258 }
42184259
42194260 try func.emitWValue(operand);
4220 if (pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4261 if (pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42214262 try func.addMemArg(.i32_load16_u, .{
4222 .offset = operand.offset() + @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod))),
4223 .alignment = @intCast(Type.anyerror.abiAlignment(mod).toByteUnits().?),
4263 .offset = operand.offset() + @as(u32, @intCast(errUnionErrorOffset(pl_ty, pt))),
4264 .alignment = @intCast(Type.anyerror.abiAlignment(pt).toByteUnits().?),
42244265 });
42254266 }
42264267
......@@ -4236,7 +4277,8 @@ fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerErro
42364277}
42374278
42384279fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool) InnerError!void {
4239 const mod = func.bin_file.base.comp.module.?;
4280 const pt = func.pt;
4281 const mod = pt.zcu;
42404282 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42414283
42424284 const operand = try func.resolveInst(ty_op.operand);
......@@ -4245,15 +4287,15 @@ fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: boo
42454287 const payload_ty = err_ty.errorUnionPayload(mod);
42464288
42474289 const result = result: {
4248 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4290 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42494291 if (op_is_ptr) {
42504292 break :result func.reuseOperand(ty_op.operand, operand);
42514293 }
42524294 break :result WValue{ .none = {} };
42534295 }
42544296
4255 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
4256 if (op_is_ptr or isByRef(payload_ty, mod)) {
4297 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
4298 if (op_is_ptr or isByRef(payload_ty, pt)) {
42574299 break :result try func.buildPointerOffset(operand, pl_offset, .new);
42584300 }
42594301
......@@ -4264,7 +4306,8 @@ fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: boo
42644306}
42654307
42664308fn airUnwrapErrUnionError(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool) InnerError!void {
4267 const mod = func.bin_file.base.comp.module.?;
4309 const pt = func.pt;
4310 const mod = pt.zcu;
42684311 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42694312
42704313 const operand = try func.resolveInst(ty_op.operand);
......@@ -4277,18 +4320,18 @@ fn airUnwrapErrUnionError(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool)
42774320 break :result WValue{ .imm32 = 0 };
42784321 }
42794322
4280 if (op_is_ptr or !payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4323 if (op_is_ptr or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42814324 break :result func.reuseOperand(ty_op.operand, operand);
42824325 }
42834326
4284 const error_val = try func.load(operand, Type.anyerror, @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod))));
4327 const error_val = try func.load(operand, Type.anyerror, @intCast(errUnionErrorOffset(payload_ty, pt)));
42854328 break :result try error_val.toLocal(func, Type.anyerror);
42864329 };
42874330 func.finishAir(inst, result, &.{ty_op.operand});
42884331}
42894332
42904333fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4291 const mod = func.bin_file.base.comp.module.?;
4334 const pt = func.pt;
42924335 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42934336
42944337 const operand = try func.resolveInst(ty_op.operand);
......@@ -4296,18 +4339,18 @@ fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void
42964339
42974340 const pl_ty = func.typeOf(ty_op.operand);
42984341 const result = result: {
4299 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4342 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43004343 break :result func.reuseOperand(ty_op.operand, operand);
43014344 }
43024345
43034346 const err_union = try func.allocStack(err_ty);
4304 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod))), .new);
4347 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, pt))), .new);
43054348 try func.store(payload_ptr, operand, pl_ty, 0);
43064349
43074350 // ensure we also write '0' to the error part, so any present stack value gets overwritten by it.
43084351 try func.emitWValue(err_union);
43094352 try func.addImm32(0);
4310 const err_val_offset = @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod)));
4353 const err_val_offset: u32 = @intCast(errUnionErrorOffset(pl_ty, pt));
43114354 try func.addMemArg(.i32_store16, .{
43124355 .offset = err_union.offset() + err_val_offset,
43134356 .alignment = 2,
......@@ -4318,7 +4361,8 @@ fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void
43184361}
43194362
43204363fn airWrapErrUnionErr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4321 const mod = func.bin_file.base.comp.module.?;
4364 const pt = func.pt;
4365 const mod = pt.zcu;
43224366 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
43234367
43244368 const operand = try func.resolveInst(ty_op.operand);
......@@ -4326,17 +4370,17 @@ fn airWrapErrUnionErr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43264370 const pl_ty = err_ty.errorUnionPayload(mod);
43274371
43284372 const result = result: {
4329 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4373 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43304374 break :result func.reuseOperand(ty_op.operand, operand);
43314375 }
43324376
43334377 const err_union = try func.allocStack(err_ty);
43344378 // store error value
4335 try func.store(err_union, operand, Type.anyerror, @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod))));
4379 try func.store(err_union, operand, Type.anyerror, @intCast(errUnionErrorOffset(pl_ty, pt)));
43364380
43374381 // write 'undefined' to the payload
4338 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod))), .new);
4339 const len = @as(u32, @intCast(err_ty.errorUnionPayload(mod).abiSize(mod)));
4382 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, pt))), .new);
4383 const len = @as(u32, @intCast(err_ty.errorUnionPayload(mod).abiSize(pt)));
43404384 try func.memset(Type.u8, payload_ptr, .{ .imm32 = len }, .{ .imm32 = 0xaa });
43414385
43424386 break :result err_union;
......@@ -4350,16 +4394,17 @@ fn airIntcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43504394 const ty = ty_op.ty.toType();
43514395 const operand = try func.resolveInst(ty_op.operand);
43524396 const operand_ty = func.typeOf(ty_op.operand);
4353 const mod = func.bin_file.base.comp.module.?;
4397 const pt = func.pt;
4398 const mod = pt.zcu;
43544399 if (ty.zigTypeTag(mod) == .Vector or operand_ty.zigTypeTag(mod) == .Vector) {
43554400 return func.fail("todo Wasm intcast for vectors", .{});
43564401 }
4357 if (ty.abiSize(mod) > 16 or operand_ty.abiSize(mod) > 16) {
4402 if (ty.abiSize(pt) > 16 or operand_ty.abiSize(pt) > 16) {
43584403 return func.fail("todo Wasm intcast for bitsize > 128", .{});
43594404 }
43604405
4361 const op_bits = toWasmBits(@as(u16, @intCast(operand_ty.bitSize(mod)))).?;
4362 const wanted_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
4406 const op_bits = toWasmBits(@intCast(operand_ty.bitSize(pt))).?;
4407 const wanted_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
43634408 const result = if (op_bits == wanted_bits)
43644409 func.reuseOperand(ty_op.operand, operand)
43654410 else
......@@ -4373,9 +4418,10 @@ fn airIntcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43734418/// Asserts type's bitsize <= 128
43744419/// NOTE: May leave the result on the top of the stack.
43754420fn intcast(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerError!WValue {
4376 const mod = func.bin_file.base.comp.module.?;
4377 const given_bitsize = @as(u16, @intCast(given.bitSize(mod)));
4378 const wanted_bitsize = @as(u16, @intCast(wanted.bitSize(mod)));
4421 const pt = func.pt;
4422 const mod = pt.zcu;
4423 const given_bitsize = @as(u16, @intCast(given.bitSize(pt)));
4424 const wanted_bitsize = @as(u16, @intCast(wanted.bitSize(pt)));
43794425 assert(given_bitsize <= 128);
43804426 assert(wanted_bitsize <= 128);
43814427
......@@ -4422,7 +4468,8 @@ fn intcast(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerErro
44224468}
44234469
44244470fn airIsNull(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind: enum { value, ptr }) InnerError!void {
4425 const mod = func.bin_file.base.comp.module.?;
4471 const pt = func.pt;
4472 const mod = pt.zcu;
44264473 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44274474 const operand = try func.resolveInst(un_op);
44284475
......@@ -4436,15 +4483,16 @@ fn airIsNull(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind:
44364483/// For a given type and operand, checks if it's considered `null`.
44374484/// NOTE: Leaves the result on the stack
44384485fn isNull(func: *CodeGen, operand: WValue, optional_ty: Type, opcode: wasm.Opcode) InnerError!WValue {
4439 const mod = func.bin_file.base.comp.module.?;
4486 const pt = func.pt;
4487 const mod = pt.zcu;
44404488 try func.emitWValue(operand);
44414489 const payload_ty = optional_ty.optionalChild(mod);
44424490 if (!optional_ty.optionalReprIsPayload(mod)) {
44434491 // When payload is zero-bits, we can treat operand as a value, rather than
44444492 // a pointer to the stack value
4445 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4446 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4447 return func.fail("Optional type {} too big to fit into stack frame", .{optional_ty.fmt(mod)});
4493 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
4494 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4495 return func.fail("Optional type {} too big to fit into stack frame", .{optional_ty.fmt(pt)});
44484496 };
44494497 try func.addMemArg(.i32_load8_u, .{ .offset = operand.offset() + offset, .alignment = 1 });
44504498 }
......@@ -4464,11 +4512,12 @@ fn isNull(func: *CodeGen, operand: WValue, optional_ty: Type, opcode: wasm.Opcod
44644512}
44654513
44664514fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4467 const mod = func.bin_file.base.comp.module.?;
4515 const pt = func.pt;
4516 const mod = pt.zcu;
44684517 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
44694518 const opt_ty = func.typeOf(ty_op.operand);
44704519 const payload_ty = func.typeOfIndex(inst);
4471 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4520 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44724521 return func.finishAir(inst, .none, &.{ty_op.operand});
44734522 }
44744523
......@@ -4476,7 +4525,7 @@ fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
44764525 const operand = try func.resolveInst(ty_op.operand);
44774526 if (opt_ty.optionalReprIsPayload(mod)) break :result func.reuseOperand(ty_op.operand, operand);
44784527
4479 if (isByRef(payload_ty, mod)) {
4528 if (isByRef(payload_ty, pt)) {
44804529 break :result try func.buildPointerOffset(operand, 0, .new);
44814530 }
44824531
......@@ -4487,14 +4536,15 @@ fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
44874536}
44884537
44894538fn airOptionalPayloadPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4490 const mod = func.bin_file.base.comp.module.?;
4539 const pt = func.pt;
4540 const mod = pt.zcu;
44914541 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
44924542 const operand = try func.resolveInst(ty_op.operand);
44934543 const opt_ty = func.typeOf(ty_op.operand).childType(mod);
44944544
44954545 const result = result: {
44964546 const payload_ty = opt_ty.optionalChild(mod);
4497 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod) or opt_ty.optionalReprIsPayload(mod)) {
4547 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt) or opt_ty.optionalReprIsPayload(mod)) {
44984548 break :result func.reuseOperand(ty_op.operand, operand);
44994549 }
45004550
......@@ -4504,12 +4554,13 @@ fn airOptionalPayloadPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45044554}
45054555
45064556fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4507 const mod = func.bin_file.base.comp.module.?;
4557 const pt = func.pt;
4558 const mod = pt.zcu;
45084559 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
45094560 const operand = try func.resolveInst(ty_op.operand);
45104561 const opt_ty = func.typeOf(ty_op.operand).childType(mod);
45114562 const payload_ty = opt_ty.optionalChild(mod);
4512 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4563 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45134564 return func.fail("TODO: Implement OptionalPayloadPtrSet for optional with zero-sized type {}", .{payload_ty.fmtDebug()});
45144565 }
45154566
......@@ -4517,8 +4568,8 @@ fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
45174568 return func.finishAir(inst, operand, &.{ty_op.operand});
45184569 }
45194570
4520 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4521 return func.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(mod)});
4571 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4572 return func.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(pt)});
45224573 };
45234574
45244575 try func.emitWValue(operand);
......@@ -4532,10 +4583,11 @@ fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
45324583fn airWrapOptional(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45334584 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
45344585 const payload_ty = func.typeOf(ty_op.operand);
4535 const mod = func.bin_file.base.comp.module.?;
4586 const pt = func.pt;
4587 const mod = pt.zcu;
45364588
45374589 const result = result: {
4538 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4590 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45394591 const non_null_bit = try func.allocStack(Type.u1);
45404592 try func.emitWValue(non_null_bit);
45414593 try func.addImm32(1);
......@@ -4548,8 +4600,8 @@ fn airWrapOptional(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45484600 if (op_ty.optionalReprIsPayload(mod)) {
45494601 break :result func.reuseOperand(ty_op.operand, operand);
45504602 }
4551 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4552 return func.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(mod)});
4603 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4604 return func.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(pt)});
45534605 };
45544606
45554607 // Create optional type, set the non-null bit, and store the operand inside the optional type
......@@ -4589,14 +4641,15 @@ fn airSliceLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45894641}
45904642
45914643fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4592 const mod = func.bin_file.base.comp.module.?;
4644 const pt = func.pt;
4645 const mod = pt.zcu;
45934646 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
45944647
45954648 const slice_ty = func.typeOf(bin_op.lhs);
45964649 const slice = try func.resolveInst(bin_op.lhs);
45974650 const index = try func.resolveInst(bin_op.rhs);
45984651 const elem_ty = slice_ty.childType(mod);
4599 const elem_size = elem_ty.abiSize(mod);
4652 const elem_size = elem_ty.abiSize(pt);
46004653
46014654 // load pointer onto stack
46024655 _ = try func.load(slice, Type.usize, 0);
......@@ -4610,7 +4663,7 @@ fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46104663 const result_ptr = try func.allocLocal(Type.usize);
46114664 try func.addLabel(.local_set, result_ptr.local.value);
46124665
4613 const result = if (!isByRef(elem_ty, mod)) result: {
4666 const result = if (!isByRef(elem_ty, pt)) result: {
46144667 const elem_val = try func.load(result_ptr, elem_ty, 0);
46154668 break :result try elem_val.toLocal(func, elem_ty);
46164669 } else result_ptr;
......@@ -4619,12 +4672,13 @@ fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46194672}
46204673
46214674fn airSliceElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4622 const mod = func.bin_file.base.comp.module.?;
4675 const pt = func.pt;
4676 const mod = pt.zcu;
46234677 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46244678 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
46254679
46264680 const elem_ty = ty_pl.ty.toType().childType(mod);
4627 const elem_size = elem_ty.abiSize(mod);
4681 const elem_size = elem_ty.abiSize(pt);
46284682
46294683 const slice = try func.resolveInst(bin_op.lhs);
46304684 const index = try func.resolveInst(bin_op.rhs);
......@@ -4672,14 +4726,14 @@ fn airTrunc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46724726/// Truncates a given operand to a given type, discarding any overflown bits.
46734727/// NOTE: Resulting value is left on the stack.
46744728fn trunc(func: *CodeGen, operand: WValue, wanted_ty: Type, given_ty: Type) InnerError!WValue {
4675 const mod = func.bin_file.base.comp.module.?;
4676 const given_bits = @as(u16, @intCast(given_ty.bitSize(mod)));
4729 const pt = func.pt;
4730 const given_bits = @as(u16, @intCast(given_ty.bitSize(pt)));
46774731 if (toWasmBits(given_bits) == null) {
46784732 return func.fail("TODO: Implement wasm integer truncation for integer bitsize: {d}", .{given_bits});
46794733 }
46804734
46814735 var result = try func.intcast(operand, given_ty, wanted_ty);
4682 const wanted_bits = @as(u16, @intCast(wanted_ty.bitSize(mod)));
4736 const wanted_bits = @as(u16, @intCast(wanted_ty.bitSize(pt)));
46834737 const wasm_bits = toWasmBits(wanted_bits).?;
46844738 if (wasm_bits != wanted_bits) {
46854739 result = try func.wrapOperand(result, wanted_ty);
......@@ -4696,7 +4750,8 @@ fn airIntFromBool(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46964750}
46974751
46984752fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4699 const mod = func.bin_file.base.comp.module.?;
4753 const pt = func.pt;
4754 const mod = pt.zcu;
47004755 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
47014756
47024757 const operand = try func.resolveInst(ty_op.operand);
......@@ -4707,7 +4762,7 @@ fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47074762 const slice_local = try func.allocStack(slice_ty);
47084763
47094764 // store the array ptr in the slice
4710 if (array_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4765 if (array_ty.hasRuntimeBitsIgnoreComptime(pt)) {
47114766 try func.store(slice_local, operand, Type.usize, 0);
47124767 }
47134768
......@@ -4719,7 +4774,8 @@ fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47194774}
47204775
47214776fn airIntFromPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4722 const mod = func.bin_file.base.comp.module.?;
4777 const pt = func.pt;
4778 const mod = pt.zcu;
47234779 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
47244780 const operand = try func.resolveInst(un_op);
47254781 const ptr_ty = func.typeOf(un_op);
......@@ -4734,14 +4790,15 @@ fn airIntFromPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47344790}
47354791
47364792fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4737 const mod = func.bin_file.base.comp.module.?;
4793 const pt = func.pt;
4794 const mod = pt.zcu;
47384795 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
47394796
47404797 const ptr_ty = func.typeOf(bin_op.lhs);
47414798 const ptr = try func.resolveInst(bin_op.lhs);
47424799 const index = try func.resolveInst(bin_op.rhs);
47434800 const elem_ty = ptr_ty.childType(mod);
4744 const elem_size = elem_ty.abiSize(mod);
4801 const elem_size = elem_ty.abiSize(pt);
47454802
47464803 // load pointer onto the stack
47474804 if (ptr_ty.isSlice(mod)) {
......@@ -4759,7 +4816,7 @@ fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47594816 const elem_result = val: {
47604817 var result = try func.allocLocal(Type.usize);
47614818 try func.addLabel(.local_set, result.local.value);
4762 if (isByRef(elem_ty, mod)) {
4819 if (isByRef(elem_ty, pt)) {
47634820 break :val result;
47644821 }
47654822 defer result.free(func); // only free if it's not returned like above
......@@ -4771,13 +4828,14 @@ fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47714828}
47724829
47734830fn airPtrElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4774 const mod = func.bin_file.base.comp.module.?;
4831 const pt = func.pt;
4832 const mod = pt.zcu;
47754833 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
47764834 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
47774835
47784836 const ptr_ty = func.typeOf(bin_op.lhs);
47794837 const elem_ty = ty_pl.ty.toType().childType(mod);
4780 const elem_size = elem_ty.abiSize(mod);
4838 const elem_size = elem_ty.abiSize(pt);
47814839
47824840 const ptr = try func.resolveInst(bin_op.lhs);
47834841 const index = try func.resolveInst(bin_op.rhs);
......@@ -4801,7 +4859,8 @@ fn airPtrElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
48014859}
48024860
48034861fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
4804 const mod = func.bin_file.base.comp.module.?;
4862 const pt = func.pt;
4863 const mod = pt.zcu;
48054864 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
48064865 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
48074866
......@@ -4813,13 +4872,13 @@ fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
48134872 else => ptr_ty.childType(mod),
48144873 };
48154874
4816 const valtype = typeToValtype(Type.usize, mod);
4875 const valtype = typeToValtype(Type.usize, pt);
48174876 const mul_opcode = buildOpcode(.{ .valtype1 = valtype, .op = .mul });
48184877 const bin_opcode = buildOpcode(.{ .valtype1 = valtype, .op = op });
48194878
48204879 try func.lowerToStack(ptr);
48214880 try func.emitWValue(offset);
4822 try func.addImm32(@intCast(pointee_ty.abiSize(mod)));
4881 try func.addImm32(@intCast(pointee_ty.abiSize(pt)));
48234882 try func.addTag(Mir.Inst.Tag.fromOpcode(mul_opcode));
48244883 try func.addTag(Mir.Inst.Tag.fromOpcode(bin_opcode));
48254884
......@@ -4829,7 +4888,8 @@ fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
48294888}
48304889
48314890fn airMemset(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void {
4832 const mod = func.bin_file.base.comp.module.?;
4891 const pt = func.pt;
4892 const mod = pt.zcu;
48334893 if (safety) {
48344894 // TODO if the value is undef, write 0xaa bytes to dest
48354895 } else {
......@@ -4862,8 +4922,8 @@ fn airMemset(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
48624922/// this to wasm's memset instruction. When the feature is not present,
48634923/// we implement it manually.
48644924fn memset(func: *CodeGen, elem_ty: Type, ptr: WValue, len: WValue, value: WValue) InnerError!void {
4865 const mod = func.bin_file.base.comp.module.?;
4866 const abi_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
4925 const pt = func.pt;
4926 const abi_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
48674927
48684928 // When bulk_memory is enabled, we lower it to wasm's memset instruction.
48694929 // If not, we lower it ourselves.
......@@ -4951,16 +5011,17 @@ fn memset(func: *CodeGen, elem_ty: Type, ptr: WValue, len: WValue, value: WValue
49515011}
49525012
49535013fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4954 const mod = func.bin_file.base.comp.module.?;
5014 const pt = func.pt;
5015 const mod = pt.zcu;
49555016 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49565017
49575018 const array_ty = func.typeOf(bin_op.lhs);
49585019 const array = try func.resolveInst(bin_op.lhs);
49595020 const index = try func.resolveInst(bin_op.rhs);
49605021 const elem_ty = array_ty.childType(mod);
4961 const elem_size = elem_ty.abiSize(mod);
5022 const elem_size = elem_ty.abiSize(pt);
49625023
4963 if (isByRef(array_ty, mod)) {
5024 if (isByRef(array_ty, pt)) {
49645025 try func.lowerToStack(array);
49655026 try func.emitWValue(index);
49665027 try func.addImm32(@intCast(elem_size));
......@@ -4971,7 +5032,7 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
49715032
49725033 switch (index) {
49735034 inline .imm32, .imm64 => |lane| {
4974 const opcode: wasm.SimdOpcode = switch (elem_ty.bitSize(mod)) {
5035 const opcode: wasm.SimdOpcode = switch (elem_ty.bitSize(pt)) {
49755036 8 => if (elem_ty.isSignedInt(mod)) .i8x16_extract_lane_s else .i8x16_extract_lane_u,
49765037 16 => if (elem_ty.isSignedInt(mod)) .i16x8_extract_lane_s else .i16x8_extract_lane_u,
49775038 32 => if (elem_ty.isInt(mod)) .i32x4_extract_lane else .f32x4_extract_lane,
......@@ -5007,7 +5068,7 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50075068 var result = try func.allocLocal(Type.usize);
50085069 try func.addLabel(.local_set, result.local.value);
50095070
5010 if (isByRef(elem_ty, mod)) {
5071 if (isByRef(elem_ty, pt)) {
50115072 break :val result;
50125073 }
50135074 defer result.free(func); // only free if no longer needed and not returned like above
......@@ -5020,7 +5081,8 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50205081}
50215082
50225083fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5023 const mod = func.bin_file.base.comp.module.?;
5084 const pt = func.pt;
5085 const mod = pt.zcu;
50245086 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50255087
50265088 const operand = try func.resolveInst(ty_op.operand);
......@@ -5054,8 +5116,8 @@ fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50545116 try func.emitWValue(operand);
50555117 const op = buildOpcode(.{
50565118 .op = .trunc,
5057 .valtype1 = typeToValtype(dest_ty, mod),
5058 .valtype2 = typeToValtype(op_ty, mod),
5119 .valtype1 = typeToValtype(dest_ty, pt),
5120 .valtype2 = typeToValtype(op_ty, pt),
50595121 .signedness = dest_info.signedness,
50605122 });
50615123 try func.addTag(Mir.Inst.Tag.fromOpcode(op));
......@@ -5065,7 +5127,8 @@ fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50655127}
50665128
50675129fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5068 const mod = func.bin_file.base.comp.module.?;
5130 const pt = func.pt;
5131 const mod = pt.zcu;
50695132 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50705133
50715134 const operand = try func.resolveInst(ty_op.operand);
......@@ -5099,8 +5162,8 @@ fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50995162 try func.emitWValue(operand);
51005163 const op = buildOpcode(.{
51015164 .op = .convert,
5102 .valtype1 = typeToValtype(dest_ty, mod),
5103 .valtype2 = typeToValtype(op_ty, mod),
5165 .valtype1 = typeToValtype(dest_ty, pt),
5166 .valtype2 = typeToValtype(op_ty, pt),
51045167 .signedness = op_info.signedness,
51055168 });
51065169 try func.addTag(Mir.Inst.Tag.fromOpcode(op));
......@@ -5111,19 +5174,20 @@ fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51115174}
51125175
51135176fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5114 const mod = func.bin_file.base.comp.module.?;
5177 const pt = func.pt;
5178 const mod = pt.zcu;
51155179 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51165180 const operand = try func.resolveInst(ty_op.operand);
51175181 const ty = func.typeOfIndex(inst);
51185182 const elem_ty = ty.childType(mod);
51195183
5120 if (determineSimdStoreStrategy(ty, mod) == .direct) blk: {
5184 if (determineSimdStoreStrategy(ty, pt) == .direct) blk: {
51215185 switch (operand) {
51225186 // when the operand lives in the linear memory section, we can directly
51235187 // load and splat the value at once. Meaning we do not first have to load
51245188 // the scalar value onto the stack.
51255189 .stack_offset, .memory, .memory_offset => {
5126 const opcode = switch (elem_ty.bitSize(mod)) {
5190 const opcode = switch (elem_ty.bitSize(pt)) {
51275191 8 => std.wasm.simdOpcode(.v128_load8_splat),
51285192 16 => std.wasm.simdOpcode(.v128_load16_splat),
51295193 32 => std.wasm.simdOpcode(.v128_load32_splat),
......@@ -5138,14 +5202,14 @@ fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51385202 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
51395203 opcode,
51405204 operand.offset(),
5141 @intCast(elem_ty.abiAlignment(mod).toByteUnits().?),
5205 @intCast(elem_ty.abiAlignment(pt).toByteUnits().?),
51425206 });
51435207 try func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
51445208 try func.addLabel(.local_set, result.local.value);
51455209 return func.finishAir(inst, result, &.{ty_op.operand});
51465210 },
51475211 .local => {
5148 const opcode = switch (elem_ty.bitSize(mod)) {
5212 const opcode = switch (elem_ty.bitSize(pt)) {
51495213 8 => std.wasm.simdOpcode(.i8x16_splat),
51505214 16 => std.wasm.simdOpcode(.i16x8_splat),
51515215 32 => if (elem_ty.isInt(mod)) std.wasm.simdOpcode(.i32x4_splat) else std.wasm.simdOpcode(.f32x4_splat),
......@@ -5163,14 +5227,14 @@ fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51635227 else => unreachable,
51645228 }
51655229 }
5166 const elem_size = elem_ty.bitSize(mod);
5230 const elem_size = elem_ty.bitSize(pt);
51675231 const vector_len = @as(usize, @intCast(ty.vectorLen(mod)));
51685232 if ((!std.math.isPowerOfTwo(elem_size) or elem_size % 8 != 0) and vector_len > 1) {
51695233 return func.fail("TODO: WebAssembly `@splat` for arbitrary element bitsize {d}", .{elem_size});
51705234 }
51715235
51725236 const result = try func.allocStack(ty);
5173 const elem_byte_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
5237 const elem_byte_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
51745238 var index: usize = 0;
51755239 var offset: u32 = 0;
51765240 while (index < vector_len) : (index += 1) {
......@@ -5190,7 +5254,8 @@ fn airSelect(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51905254}
51915255
51925256fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5193 const mod = func.bin_file.base.comp.module.?;
5257 const pt = func.pt;
5258 const mod = pt.zcu;
51945259 const inst_ty = func.typeOfIndex(inst);
51955260 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51965261 const extra = func.air.extraData(Air.Shuffle, ty_pl.payload).data;
......@@ -5201,14 +5266,14 @@ fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52015266 const mask_len = extra.mask_len;
52025267
52035268 const child_ty = inst_ty.childType(mod);
5204 const elem_size = child_ty.abiSize(mod);
5269 const elem_size = child_ty.abiSize(pt);
52055270
52065271 // TODO: One of them could be by ref; handle in loop
5207 if (isByRef(func.typeOf(extra.a), mod) or isByRef(inst_ty, mod)) {
5272 if (isByRef(func.typeOf(extra.a), pt) or isByRef(inst_ty, pt)) {
52085273 const result = try func.allocStack(inst_ty);
52095274
52105275 for (0..mask_len) |index| {
5211 const value = (try mask.elemValue(mod, index)).toSignedInt(mod);
5276 const value = (try mask.elemValue(pt, index)).toSignedInt(pt);
52125277
52135278 try func.emitWValue(result);
52145279
......@@ -5228,7 +5293,7 @@ fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52285293
52295294 var lanes = mem.asBytes(operands[1..]);
52305295 for (0..@as(usize, @intCast(mask_len))) |index| {
5231 const mask_elem = (try mask.elemValue(mod, index)).toSignedInt(mod);
5296 const mask_elem = (try mask.elemValue(pt, index)).toSignedInt(pt);
52325297 const base_index = if (mask_elem >= 0)
52335298 @as(u8, @intCast(@as(i64, @intCast(elem_size)) * mask_elem))
52345299 else
......@@ -5259,7 +5324,8 @@ fn airReduce(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52595324}
52605325
52615326fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5262 const mod = func.bin_file.base.comp.module.?;
5327 const pt = func.pt;
5328 const mod = pt.zcu;
52635329 const ip = &mod.intern_pool;
52645330 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
52655331 const result_ty = func.typeOfIndex(inst);
......@@ -5271,7 +5337,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52715337 .Array => {
52725338 const result = try func.allocStack(result_ty);
52735339 const elem_ty = result_ty.childType(mod);
5274 const elem_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
5340 const elem_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
52755341 const sentinel = if (result_ty.sentinel(mod)) |sent| blk: {
52765342 break :blk try func.lowerConstant(sent, elem_ty);
52775343 } else null;
......@@ -5279,7 +5345,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52795345 // When the element type is by reference, we must copy the entire
52805346 // value. It is therefore safer to move the offset pointer and store
52815347 // each value individually, instead of using store offsets.
5282 if (isByRef(elem_ty, mod)) {
5348 if (isByRef(elem_ty, pt)) {
52835349 // copy stack pointer into a temporary local, which is
52845350 // moved for each element to store each value in the right position.
52855351 const offset = try func.buildPointerOffset(result, 0, .new);
......@@ -5309,7 +5375,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53095375 },
53105376 .Struct => switch (result_ty.containerLayout(mod)) {
53115377 .@"packed" => {
5312 if (isByRef(result_ty, mod)) {
5378 if (isByRef(result_ty, pt)) {
53135379 return func.fail("TODO: airAggregateInit for packed structs larger than 64 bits", .{});
53145380 }
53155381 const packed_struct = mod.typeToPackedStruct(result_ty).?;
......@@ -5318,7 +5384,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53185384
53195385 // ensure the result is zero'd
53205386 const result = try func.allocLocal(backing_type);
5321 if (backing_type.bitSize(mod) <= 32)
5387 if (backing_type.bitSize(pt) <= 32)
53225388 try func.addImm32(0)
53235389 else
53245390 try func.addImm64(0);
......@@ -5327,16 +5393,16 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53275393 var current_bit: u16 = 0;
53285394 for (elements, 0..) |elem, elem_index| {
53295395 const field_ty = Type.fromInterned(field_types.get(ip)[elem_index]);
5330 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
5396 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
53315397
5332 const shift_val = if (backing_type.bitSize(mod) <= 32)
5398 const shift_val = if (backing_type.bitSize(pt) <= 32)
53335399 WValue{ .imm32 = current_bit }
53345400 else
53355401 WValue{ .imm64 = current_bit };
53365402
53375403 const value = try func.resolveInst(elem);
5338 const value_bit_size: u16 = @intCast(field_ty.bitSize(mod));
5339 const int_ty = try mod.intType(.unsigned, value_bit_size);
5404 const value_bit_size: u16 = @intCast(field_ty.bitSize(pt));
5405 const int_ty = try pt.intType(.unsigned, value_bit_size);
53405406
53415407 // load our current result on stack so we can perform all transformations
53425408 // using only stack values. Saving the cost of loads and stores.
......@@ -5359,10 +5425,10 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53595425 const offset = try func.buildPointerOffset(result, 0, .new); // pointer to offset
53605426 var prev_field_offset: u64 = 0;
53615427 for (elements, 0..) |elem, elem_index| {
5362 if ((try result_ty.structFieldValueComptime(mod, elem_index)) != null) continue;
5428 if (try result_ty.structFieldValueComptime(pt, elem_index) != null) continue;
53635429
53645430 const elem_ty = result_ty.structFieldType(elem_index, mod);
5365 const field_offset = result_ty.structFieldOffset(elem_index, mod);
5431 const field_offset = result_ty.structFieldOffset(elem_index, pt);
53665432 _ = try func.buildPointerOffset(offset, @intCast(field_offset - prev_field_offset), .modify);
53675433 prev_field_offset = field_offset;
53685434
......@@ -5389,14 +5455,15 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53895455}
53905456
53915457fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5392 const mod = func.bin_file.base.comp.module.?;
5458 const pt = func.pt;
5459 const mod = pt.zcu;
53935460 const ip = &mod.intern_pool;
53945461 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
53955462 const extra = func.air.extraData(Air.UnionInit, ty_pl.payload).data;
53965463
53975464 const result = result: {
53985465 const union_ty = func.typeOfIndex(inst);
5399 const layout = union_ty.unionGetLayout(mod);
5466 const layout = union_ty.unionGetLayout(pt);
54005467 const union_obj = mod.typeToUnion(union_ty).?;
54015468 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
54025469 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
......@@ -5404,22 +5471,22 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
54045471 const tag_int = blk: {
54055472 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
54065473 const enum_field_index = tag_ty.enumFieldIndex(field_name, mod).?;
5407 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
5474 const tag_val = try pt.enumValueFieldIndex(tag_ty, enum_field_index);
54085475 break :blk try func.lowerConstant(tag_val, tag_ty);
54095476 };
54105477 if (layout.payload_size == 0) {
54115478 if (layout.tag_size == 0) {
54125479 break :result WValue{ .none = {} };
54135480 }
5414 assert(!isByRef(union_ty, mod));
5481 assert(!isByRef(union_ty, pt));
54155482 break :result tag_int;
54165483 }
54175484
5418 if (isByRef(union_ty, mod)) {
5485 if (isByRef(union_ty, pt)) {
54195486 const result_ptr = try func.allocStack(union_ty);
54205487 const payload = try func.resolveInst(extra.init);
54215488 if (layout.tag_align.compare(.gte, layout.payload_align)) {
5422 if (isByRef(field_ty, mod)) {
5489 if (isByRef(field_ty, pt)) {
54235490 const payload_ptr = try func.buildPointerOffset(result_ptr, layout.tag_size, .new);
54245491 try func.store(payload_ptr, payload, field_ty, 0);
54255492 } else {
......@@ -5443,14 +5510,14 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
54435510 break :result result_ptr;
54445511 } else {
54455512 const operand = try func.resolveInst(extra.init);
5446 const union_int_type = try mod.intType(.unsigned, @as(u16, @intCast(union_ty.bitSize(mod))));
5513 const union_int_type = try pt.intType(.unsigned, @as(u16, @intCast(union_ty.bitSize(pt))));
54475514 if (field_ty.zigTypeTag(mod) == .Float) {
5448 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
5515 const int_type = try pt.intType(.unsigned, @intCast(field_ty.bitSize(pt)));
54495516 const bitcasted = try func.bitcast(field_ty, int_type, operand);
54505517 const casted = try func.trunc(bitcasted, int_type, union_int_type);
54515518 break :result try casted.toLocal(func, field_ty);
54525519 } else if (field_ty.isPtrAtRuntime(mod)) {
5453 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
5520 const int_type = try pt.intType(.unsigned, @intCast(field_ty.bitSize(pt)));
54545521 const casted = try func.intcast(operand, int_type, union_int_type);
54555522 break :result try casted.toLocal(func, field_ty);
54565523 }
......@@ -5488,8 +5555,9 @@ fn airWasmMemoryGrow(func: *CodeGen, inst: Air.Inst.Index) !void {
54885555}
54895556
54905557fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue {
5491 const mod = func.bin_file.base.comp.module.?;
5492 assert(operand_ty.hasRuntimeBitsIgnoreComptime(mod));
5558 const pt = func.pt;
5559 const mod = pt.zcu;
5560 assert(operand_ty.hasRuntimeBitsIgnoreComptime(pt));
54935561 assert(op == .eq or op == .neq);
54945562 const payload_ty = operand_ty.optionalChild(mod);
54955563
......@@ -5506,7 +5574,7 @@ fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op:
55065574
55075575 _ = try func.load(lhs, payload_ty, 0);
55085576 _ = try func.load(rhs, payload_ty, 0);
5509 const opcode = buildOpcode(.{ .op = .ne, .valtype1 = typeToValtype(payload_ty, mod) });
5577 const opcode = buildOpcode(.{ .op = .ne, .valtype1 = typeToValtype(payload_ty, pt) });
55105578 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
55115579 try func.addLabel(.br_if, 0);
55125580
......@@ -5524,11 +5592,12 @@ fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op:
55245592/// NOTE: Leaves the result of the comparison on top of the stack.
55255593/// TODO: Lower this to compiler_rt call when bitsize > 128
55265594fn cmpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue {
5527 const mod = func.bin_file.base.comp.module.?;
5528 assert(operand_ty.abiSize(mod) >= 16);
5595 const pt = func.pt;
5596 const mod = pt.zcu;
5597 assert(operand_ty.abiSize(pt) >= 16);
55295598 assert(!(lhs != .stack and rhs == .stack));
5530 if (operand_ty.bitSize(mod) > 128) {
5531 return func.fail("TODO: Support cmpBigInt for integer bitsize: '{d}'", .{operand_ty.bitSize(mod)});
5599 if (operand_ty.bitSize(pt) > 128) {
5600 return func.fail("TODO: Support cmpBigInt for integer bitsize: '{d}'", .{operand_ty.bitSize(pt)});
55325601 }
55335602
55345603 var lhs_high_bit = try (try func.load(lhs, Type.u64, 0)).toLocal(func, Type.u64);
......@@ -5566,11 +5635,12 @@ fn cmpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std
55665635}
55675636
55685637fn airSetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5569 const mod = func.bin_file.base.comp.module.?;
5638 const pt = func.pt;
5639 const mod = pt.zcu;
55705640 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
55715641 const un_ty = func.typeOf(bin_op.lhs).childType(mod);
55725642 const tag_ty = func.typeOf(bin_op.rhs);
5573 const layout = un_ty.unionGetLayout(mod);
5643 const layout = un_ty.unionGetLayout(pt);
55745644 if (layout.tag_size == 0) return func.finishAir(inst, .none, &.{ bin_op.lhs, bin_op.rhs });
55755645
55765646 const union_ptr = try func.resolveInst(bin_op.lhs);
......@@ -5590,12 +5660,12 @@ fn airSetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
55905660}
55915661
55925662fn airGetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5593 const mod = func.bin_file.base.comp.module.?;
5663 const pt = func.pt;
55945664 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
55955665
55965666 const un_ty = func.typeOf(ty_op.operand);
55975667 const tag_ty = func.typeOfIndex(inst);
5598 const layout = un_ty.unionGetLayout(mod);
5668 const layout = un_ty.unionGetLayout(pt);
55995669 if (layout.tag_size == 0) return func.finishAir(inst, .none, &.{ty_op.operand});
56005670
56015671 const operand = try func.resolveInst(ty_op.operand);
......@@ -5695,7 +5765,8 @@ fn fptrunc(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerErro
56955765}
56965766
56975767fn airErrUnionPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5698 const mod = func.bin_file.base.comp.module.?;
5768 const pt = func.pt;
5769 const mod = pt.zcu;
56995770 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57005771
57015772 const err_set_ty = func.typeOf(ty_op.operand).childType(mod);
......@@ -5707,27 +5778,28 @@ fn airErrUnionPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
57075778 operand,
57085779 .{ .imm32 = 0 },
57095780 Type.anyerror,
5710 @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod))),
5781 @intCast(errUnionErrorOffset(payload_ty, pt)),
57115782 );
57125783
57135784 const result = result: {
5714 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5785 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
57155786 break :result func.reuseOperand(ty_op.operand, operand);
57165787 }
57175788
5718 break :result try func.buildPointerOffset(operand, @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod))), .new);
5789 break :result try func.buildPointerOffset(operand, @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt))), .new);
57195790 };
57205791 func.finishAir(inst, result, &.{ty_op.operand});
57215792}
57225793
57235794fn airFieldParentPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5724 const mod = func.bin_file.base.comp.module.?;
5795 const pt = func.pt;
5796 const mod = pt.zcu;
57255797 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
57265798 const extra = func.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
57275799
57285800 const field_ptr = try func.resolveInst(extra.field_ptr);
57295801 const parent_ty = ty_pl.ty.toType().childType(mod);
5730 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
5802 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
57315803
57325804 const result = if (field_offset != 0) result: {
57335805 const base = try func.buildPointerOffset(field_ptr, 0, .new);
......@@ -5742,7 +5814,8 @@ fn airFieldParentPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57425814}
57435815
57445816fn sliceOrArrayPtr(func: *CodeGen, ptr: WValue, ptr_ty: Type) InnerError!WValue {
5745 const mod = func.bin_file.base.comp.module.?;
5817 const pt = func.pt;
5818 const mod = pt.zcu;
57465819 if (ptr_ty.isSlice(mod)) {
57475820 return func.slicePtr(ptr);
57485821 } else {
......@@ -5751,7 +5824,8 @@ fn sliceOrArrayPtr(func: *CodeGen, ptr: WValue, ptr_ty: Type) InnerError!WValue
57515824}
57525825
57535826fn airMemcpy(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5754 const mod = func.bin_file.base.comp.module.?;
5827 const pt = func.pt;
5828 const mod = pt.zcu;
57555829 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57565830 const dst = try func.resolveInst(bin_op.lhs);
57575831 const dst_ty = func.typeOf(bin_op.lhs);
......@@ -5761,16 +5835,16 @@ fn airMemcpy(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57615835 const len = switch (dst_ty.ptrSize(mod)) {
57625836 .Slice => blk: {
57635837 const slice_len = try func.sliceLen(dst);
5764 if (ptr_elem_ty.abiSize(mod) != 1) {
5838 if (ptr_elem_ty.abiSize(pt) != 1) {
57655839 try func.emitWValue(slice_len);
5766 try func.emitWValue(.{ .imm32 = @as(u32, @intCast(ptr_elem_ty.abiSize(mod))) });
5840 try func.emitWValue(.{ .imm32 = @as(u32, @intCast(ptr_elem_ty.abiSize(pt))) });
57675841 try func.addTag(.i32_mul);
57685842 try func.addLabel(.local_set, slice_len.local.value);
57695843 }
57705844 break :blk slice_len;
57715845 },
57725846 .One => @as(WValue, .{
5773 .imm32 = @as(u32, @intCast(ptr_elem_ty.arrayLen(mod) * ptr_elem_ty.childType(mod).abiSize(mod))),
5847 .imm32 = @as(u32, @intCast(ptr_elem_ty.arrayLen(mod) * ptr_elem_ty.childType(mod).abiSize(pt))),
57745848 }),
57755849 .C, .Many => unreachable,
57765850 };
......@@ -5791,7 +5865,8 @@ fn airRetAddr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57915865}
57925866
57935867fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5794 const mod = func.bin_file.base.comp.module.?;
5868 const pt = func.pt;
5869 const mod = pt.zcu;
57955870 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57965871
57975872 const operand = try func.resolveInst(ty_op.operand);
......@@ -5812,14 +5887,14 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58125887 32 => {
58135888 try func.emitWValue(operand);
58145889 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5815 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits));
5890 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits));
58165891 }
58175892 try func.addTag(.i32_popcnt);
58185893 },
58195894 64 => {
58205895 try func.emitWValue(operand);
58215896 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5822 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits));
5897 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits));
58235898 }
58245899 try func.addTag(.i64_popcnt);
58255900 try func.addTag(.i32_wrap_i64);
......@@ -5830,7 +5905,7 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58305905 try func.addTag(.i64_popcnt);
58315906 _ = try func.load(operand, Type.u64, 8);
58325907 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5833 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits - 64));
5908 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits - 64));
58345909 }
58355910 try func.addTag(.i64_popcnt);
58365911 try func.addTag(.i64_add);
......@@ -5845,7 +5920,8 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58455920}
58465921
58475922fn airBitReverse(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5848 const mod = func.bin_file.base.comp.module.?;
5923 const pt = func.pt;
5924 const mod = pt.zcu;
58495925 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58505926
58515927 const operand = try func.resolveInst(ty_op.operand);
......@@ -5956,10 +6032,10 @@ fn airErrorName(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
59566032 //
59576033 // As the names are global and the slice elements are constant, we do not have
59586034 // to make a copy of the ptr+value but can point towards them directly.
5959 const error_table_symbol = try func.bin_file.getErrorTableSymbol();
6035 const pt = func.pt;
6036 const error_table_symbol = try func.bin_file.getErrorTableSymbol(pt);
59606037 const name_ty = Type.slice_const_u8_sentinel_0;
5961 const mod = func.bin_file.base.comp.module.?;
5962 const abi_size = name_ty.abiSize(mod);
6038 const abi_size = name_ty.abiSize(pt);
59636039
59646040 const error_name_value: WValue = .{ .memory = error_table_symbol }; // emitting this will create a relocation
59656041 try func.emitWValue(error_name_value);
......@@ -5998,7 +6074,8 @@ fn airAddSubWithOverflow(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerErro
59986074 const lhs = try func.resolveInst(extra.lhs);
59996075 const rhs = try func.resolveInst(extra.rhs);
60006076 const lhs_ty = func.typeOf(extra.lhs);
6001 const mod = func.bin_file.base.comp.module.?;
6077 const pt = func.pt;
6078 const mod = pt.zcu;
60026079
60036080 if (lhs_ty.zigTypeTag(mod) == .Vector) {
60046081 return func.fail("TODO: Implement overflow arithmetic for vectors", .{});
......@@ -6044,14 +6121,15 @@ fn airAddSubWithOverflow(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerErro
60446121
60456122 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
60466123 try func.store(result_ptr, result, lhs_ty, 0);
6047 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6124 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
60486125 try func.store(result_ptr, overflow_local, Type.u1, offset);
60496126
60506127 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
60516128}
60526129
60536130fn addSubWithOverflowBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, result_ty: Type, op: Op) InnerError!WValue {
6054 const mod = func.bin_file.base.comp.module.?;
6131 const pt = func.pt;
6132 const mod = pt.zcu;
60556133 assert(op == .add or op == .sub);
60566134 const int_info = ty.intInfo(mod);
60576135 const is_signed = int_info.signedness == .signed;
......@@ -6116,7 +6194,8 @@ fn addSubWithOverflowBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type,
61166194}
61176195
61186196fn airShlWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6119 const mod = func.bin_file.base.comp.module.?;
6197 const pt = func.pt;
6198 const mod = pt.zcu;
61206199 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
61216200 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
61226201
......@@ -6159,7 +6238,7 @@ fn airShlWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
61596238
61606239 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
61616240 try func.store(result_ptr, result, lhs_ty, 0);
6162 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6241 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
61636242 try func.store(result_ptr, overflow_local, Type.u1, offset);
61646243
61656244 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
......@@ -6172,7 +6251,8 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
61726251 const lhs = try func.resolveInst(extra.lhs);
61736252 const rhs = try func.resolveInst(extra.rhs);
61746253 const lhs_ty = func.typeOf(extra.lhs);
6175 const mod = func.bin_file.base.comp.module.?;
6254 const pt = func.pt;
6255 const mod = pt.zcu;
61766256
61776257 if (lhs_ty.zigTypeTag(mod) == .Vector) {
61786258 return func.fail("TODO: Implement overflow arithmetic for vectors", .{});
......@@ -6332,7 +6412,7 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
63326412
63336413 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
63346414 try func.store(result_ptr, bin_op_local, lhs_ty, 0);
6335 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6415 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
63366416 try func.store(result_ptr, overflow_bit, Type.u1, offset);
63376417
63386418 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
......@@ -6340,7 +6420,8 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
63406420
63416421fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63426422 assert(op == .max or op == .min);
6343 const mod = func.bin_file.base.comp.module.?;
6423 const pt = func.pt;
6424 const mod = pt.zcu;
63446425 const target = mod.getTarget();
63456426 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
63466427
......@@ -6349,7 +6430,7 @@ fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63496430 return func.fail("TODO: `@maximum` and `@minimum` for vectors", .{});
63506431 }
63516432
6352 if (ty.abiSize(mod) > 16) {
6433 if (ty.abiSize(pt) > 16) {
63536434 return func.fail("TODO: `@maximum` and `@minimum` for types larger than 16 bytes", .{});
63546435 }
63556436
......@@ -6377,14 +6458,15 @@ fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63776458 }
63786459
63796460 // store result in local
6380 const result_ty = if (isByRef(ty, mod)) Type.u32 else ty;
6461 const result_ty = if (isByRef(ty, pt)) Type.u32 else ty;
63816462 const result = try func.allocLocal(result_ty);
63826463 try func.addLabel(.local_set, result.local.value);
63836464 func.finishAir(inst, result, &.{ bin_op.lhs, bin_op.rhs });
63846465}
63856466
63866467fn airMulAdd(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6387 const mod = func.bin_file.base.comp.module.?;
6468 const pt = func.pt;
6469 const mod = pt.zcu;
63886470 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
63896471 const bin_op = func.air.extraData(Air.Bin, pl_op.payload).data;
63906472
......@@ -6418,7 +6500,8 @@ fn airMulAdd(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
64186500}
64196501
64206502fn airClz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6421 const mod = func.bin_file.base.comp.module.?;
6503 const pt = func.pt;
6504 const mod = pt.zcu;
64226505 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
64236506
64246507 const ty = func.typeOf(ty_op.operand);
......@@ -6471,7 +6554,8 @@ fn airClz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
64716554}
64726555
64736556fn airCtz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6474 const mod = func.bin_file.base.comp.module.?;
6557 const pt = func.pt;
6558 const mod = pt.zcu;
64756559 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
64766560
64776561 const ty = func.typeOf(ty_op.operand);
......@@ -6558,7 +6642,8 @@ fn airDbgInlineBlock(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
65586642fn airDbgVar(func: *CodeGen, inst: Air.Inst.Index, is_ptr: bool) InnerError!void {
65596643 if (func.debug_output != .dwarf) return func.finishAir(inst, .none, &.{});
65606644
6561 const mod = func.bin_file.base.comp.module.?;
6645 const pt = func.pt;
6646 const mod = pt.zcu;
65626647 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
65636648 const ty = func.typeOf(pl_op.operand);
65646649 const operand = try func.resolveInst(pl_op.operand);
......@@ -6591,7 +6676,8 @@ fn airTry(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
65916676}
65926677
65936678fn airTryPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6594 const mod = func.bin_file.base.comp.module.?;
6679 const pt = func.pt;
6680 const mod = pt.zcu;
65956681 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
65966682 const extra = func.air.extraData(Air.TryPtr, ty_pl.payload);
65976683 const err_union_ptr = try func.resolveInst(extra.data.ptr);
......@@ -6609,13 +6695,14 @@ fn lowerTry(
66096695 err_union_ty: Type,
66106696 operand_is_ptr: bool,
66116697) InnerError!WValue {
6612 const mod = func.bin_file.base.comp.module.?;
6698 const pt = func.pt;
6699 const mod = pt.zcu;
66136700 if (operand_is_ptr) {
66146701 return func.fail("TODO: lowerTry for pointers", .{});
66156702 }
66166703
66176704 const pl_ty = err_union_ty.errorUnionPayload(mod);
6618 const pl_has_bits = pl_ty.hasRuntimeBitsIgnoreComptime(mod);
6705 const pl_has_bits = pl_ty.hasRuntimeBitsIgnoreComptime(pt);
66196706
66206707 if (!err_union_ty.errorUnionSet(mod).errorSetIsEmpty(mod)) {
66216708 // Block we can jump out of when error is not set
......@@ -6624,10 +6711,10 @@ fn lowerTry(
66246711 // check if the error tag is set for the error union.
66256712 try func.emitWValue(err_union);
66266713 if (pl_has_bits) {
6627 const err_offset = @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod)));
6714 const err_offset: u32 = @intCast(errUnionErrorOffset(pl_ty, pt));
66286715 try func.addMemArg(.i32_load16_u, .{
66296716 .offset = err_union.offset() + err_offset,
6630 .alignment = @intCast(Type.anyerror.abiAlignment(mod).toByteUnits().?),
6717 .alignment = @intCast(Type.anyerror.abiAlignment(pt).toByteUnits().?),
66316718 });
66326719 }
66336720 try func.addTag(.i32_eqz);
......@@ -6649,8 +6736,8 @@ fn lowerTry(
66496736 return WValue{ .none = {} };
66506737 }
66516738
6652 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod)));
6653 if (isByRef(pl_ty, mod)) {
6739 const pl_offset: u32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
6740 if (isByRef(pl_ty, pt)) {
66546741 return buildPointerOffset(func, err_union, pl_offset, .new);
66556742 }
66566743 const payload = try func.load(err_union, pl_ty, pl_offset);
......@@ -6658,7 +6745,8 @@ fn lowerTry(
66586745}
66596746
66606747fn airByteSwap(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6661 const mod = func.bin_file.base.comp.module.?;
6748 const pt = func.pt;
6749 const mod = pt.zcu;
66626750 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66636751
66646752 const ty = func.typeOfIndex(inst);
......@@ -6744,7 +6832,8 @@ fn airDivTrunc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
67446832fn airDivFloor(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
67456833 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67466834
6747 const mod = func.bin_file.base.comp.module.?;
6835 const pt = func.pt;
6836 const mod = pt.zcu;
67486837 const ty = func.typeOfIndex(inst);
67496838 const lhs = try func.resolveInst(bin_op.lhs);
67506839 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6864,7 +6953,8 @@ fn airRem(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
68646953fn airMod(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
68656954 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
68666955
6867 const mod = func.bin_file.base.comp.module.?;
6956 const pt = func.pt;
6957 const mod = pt.zcu;
68686958 const ty = func.typeOfIndex(inst);
68696959 const lhs = try func.resolveInst(bin_op.lhs);
68706960 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6901,7 +6991,8 @@ fn airSatBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
69016991 assert(op == .add or op == .sub);
69026992 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
69036993
6904 const mod = func.bin_file.base.comp.module.?;
6994 const pt = func.pt;
6995 const mod = pt.zcu;
69056996 const ty = func.typeOfIndex(inst);
69066997 const lhs = try func.resolveInst(bin_op.lhs);
69076998 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6949,11 +7040,12 @@ fn airSatBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
69497040}
69507041
69517042fn signedSat(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
6952 const mod = func.bin_file.base.comp.module.?;
7043 const pt = func.pt;
7044 const mod = pt.zcu;
69537045 const int_info = ty.intInfo(mod);
69547046 const wasm_bits = toWasmBits(int_info.bits).?;
69557047 const is_wasm_bits = wasm_bits == int_info.bits;
6956 const ext_ty = if (!is_wasm_bits) try mod.intType(int_info.signedness, wasm_bits) else ty;
7048 const ext_ty = if (!is_wasm_bits) try pt.intType(int_info.signedness, wasm_bits) else ty;
69577049
69587050 const max_val: u64 = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(int_info.bits - 1))) - 1));
69597051 const min_val: i64 = (-@as(i64, @intCast(@as(u63, @intCast(max_val))))) - 1;
......@@ -7007,7 +7099,8 @@ fn signedSat(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerEr
70077099fn airShlSat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
70087100 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
70097101
7010 const mod = func.bin_file.base.comp.module.?;
7102 const pt = func.pt;
7103 const mod = pt.zcu;
70117104 const ty = func.typeOfIndex(inst);
70127105 const int_info = ty.intInfo(mod);
70137106 const is_signed = int_info.signedness == .signed;
......@@ -7061,7 +7154,7 @@ fn airShlSat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
70617154 64 => WValue{ .imm64 = shift_size },
70627155 else => unreachable,
70637156 };
7064 const ext_ty = try mod.intType(int_info.signedness, wasm_bits);
7157 const ext_ty = try pt.intType(int_info.signedness, wasm_bits);
70657158
70667159 var shl_res = try (try func.binOp(lhs, shift_value, ext_ty, .shl)).toLocal(func, ext_ty);
70677160 defer shl_res.free(func);
......@@ -7128,13 +7221,14 @@ fn callIntrinsic(
71287221 };
71297222
71307223 // Always pass over C-ABI
7131 const mod = func.bin_file.base.comp.module.?;
7132 var func_type = try genFunctype(func.gpa, .C, param_types, return_type, mod);
7224 const pt = func.pt;
7225 const mod = pt.zcu;
7226 var func_type = try genFunctype(func.gpa, .C, param_types, return_type, pt);
71337227 defer func_type.deinit(func.gpa);
71347228 const func_type_index = try func.bin_file.zigObjectPtr().?.putOrGetFuncType(func.gpa, func_type);
71357229 try func.bin_file.addOrUpdateImport(name, symbol_index, null, func_type_index);
71367230
7137 const want_sret_param = firstParamSRet(.C, return_type, mod);
7231 const want_sret_param = firstParamSRet(.C, return_type, pt);
71387232 // if we want return as first param, we allocate a pointer to stack,
71397233 // and emit it as our first argument
71407234 const sret = if (want_sret_param) blk: {
......@@ -7146,14 +7240,14 @@ fn callIntrinsic(
71467240 // Lower all arguments to the stack before we call our function
71477241 for (args, 0..) |arg, arg_i| {
71487242 assert(!(want_sret_param and arg == .stack));
7149 assert(Type.fromInterned(param_types[arg_i]).hasRuntimeBitsIgnoreComptime(mod));
7243 assert(Type.fromInterned(param_types[arg_i]).hasRuntimeBitsIgnoreComptime(pt));
71507244 try func.lowerArg(.C, Type.fromInterned(param_types[arg_i]), arg);
71517245 }
71527246
71537247 // Actually call our intrinsic
71547248 try func.addLabel(.call, @intFromEnum(symbol_index));
71557249
7156 if (!return_type.hasRuntimeBitsIgnoreComptime(mod)) {
7250 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) {
71577251 return WValue.none;
71587252 } else if (return_type.isNoReturn(mod)) {
71597253 try func.addTag(.@"unreachable");
......@@ -7181,7 +7275,8 @@ fn airTagName(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
71817275}
71827276
71837277fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
7184 const mod = func.bin_file.base.comp.module.?;
7278 const pt = func.pt;
7279 const mod = pt.zcu;
71857280 const ip = &mod.intern_pool;
71867281 const enum_decl_index = enum_ty.getOwnerDecl(mod);
71877282
......@@ -7199,7 +7294,7 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
71997294
72007295 const int_tag_ty = enum_ty.intTagType(mod);
72017296
7202 if (int_tag_ty.bitSize(mod) > 64) {
7297 if (int_tag_ty.bitSize(pt) > 64) {
72037298 return func.fail("TODO: Implement @tagName for enums with tag size larger than 64 bits", .{});
72047299 }
72057300
......@@ -7225,16 +7320,17 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
72257320 const tag_name_len = tag_name.length(ip);
72267321 // for each tag name, create an unnamed const,
72277322 // and then get a pointer to its value.
7228 const name_ty = try mod.arrayType(.{
7323 const name_ty = try pt.arrayType(.{
72297324 .len = tag_name_len,
72307325 .child = .u8_type,
72317326 .sentinel = .zero_u8,
72327327 });
7233 const name_val = try mod.intern(.{ .aggregate = .{
7328 const name_val = try pt.intern(.{ .aggregate = .{
72347329 .ty = name_ty.toIntern(),
72357330 .storage = .{ .bytes = tag_name.toString() },
72367331 } });
72377332 const tag_sym_index = try func.bin_file.lowerUnnamedConst(
7333 pt,
72387334 Value.fromInterned(name_val),
72397335 enum_decl_index,
72407336 );
......@@ -7247,7 +7343,7 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
72477343 try writer.writeByte(std.wasm.opcode(.local_get));
72487344 try leb.writeUleb128(writer, @as(u32, 1));
72497345
7250 const tag_val = try mod.enumValueFieldIndex(enum_ty, @intCast(tag_index));
7346 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
72517347 const tag_value = try func.lowerConstant(tag_val, enum_ty);
72527348
72537349 switch (tag_value) {
......@@ -7334,13 +7430,14 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
73347430 try writer.writeByte(std.wasm.opcode(.end));
73357431
73367432 const slice_ty = Type.slice_const_u8_sentinel_0;
7337 const func_type = try genFunctype(arena, .Unspecified, &.{int_tag_ty.ip_index}, slice_ty, mod);
7433 const func_type = try genFunctype(arena, .Unspecified, &.{int_tag_ty.ip_index}, slice_ty, pt);
73387434 const sym_index = try func.bin_file.createFunction(func_name, func_type, &body_list, &relocs);
73397435 return @intFromEnum(sym_index);
73407436}
73417437
73427438fn airErrorSetHasValue(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7343 const mod = func.bin_file.base.comp.module.?;
7439 const pt = func.pt;
7440 const mod = pt.zcu;
73447441 const ip = &mod.intern_pool;
73457442 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73467443
......@@ -7426,7 +7523,8 @@ inline fn useAtomicFeature(func: *const CodeGen) bool {
74267523}
74277524
74287525fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7429 const mod = func.bin_file.base.comp.module.?;
7526 const pt = func.pt;
7527 const mod = pt.zcu;
74307528 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
74317529 const extra = func.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
74327530
......@@ -7445,7 +7543,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74457543 try func.emitWValue(ptr_operand);
74467544 try func.lowerToStack(expected_val);
74477545 try func.lowerToStack(new_val);
7448 try func.addAtomicMemArg(switch (ty.abiSize(mod)) {
7546 try func.addAtomicMemArg(switch (ty.abiSize(pt)) {
74497547 1 => .i32_atomic_rmw8_cmpxchg_u,
74507548 2 => .i32_atomic_rmw16_cmpxchg_u,
74517549 4 => .i32_atomic_rmw_cmpxchg,
......@@ -7453,14 +7551,14 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74537551 else => |size| return func.fail("TODO: implement `@cmpxchg` for types with abi size '{d}'", .{size}),
74547552 }, .{
74557553 .offset = ptr_operand.offset(),
7456 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7554 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
74577555 });
74587556 try func.addLabel(.local_tee, val_local.local.value);
74597557 _ = try func.cmp(.stack, expected_val, ty, .eq);
74607558 try func.addLabel(.local_set, cmp_result.local.value);
74617559 break :val val_local;
74627560 } else val: {
7463 if (ty.abiSize(mod) > 8) {
7561 if (ty.abiSize(pt) > 8) {
74647562 return func.fail("TODO: Implement `@cmpxchg` for types larger than abi size of 8 bytes", .{});
74657563 }
74667564 const ptr_val = try WValue.toLocal(try func.load(ptr_operand, ty, 0), func, ty);
......@@ -7476,7 +7574,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74767574 break :val ptr_val;
74777575 };
74787576
7479 const result_ptr = if (isByRef(result_ty, mod)) val: {
7577 const result_ptr = if (isByRef(result_ty, pt)) val: {
74807578 try func.emitWValue(cmp_result);
74817579 try func.addImm32(~@as(u32, 0));
74827580 try func.addTag(.i32_xor);
......@@ -7484,7 +7582,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74847582 try func.addTag(.i32_and);
74857583 const and_result = try WValue.toLocal(.stack, func, Type.bool);
74867584 const result_ptr = try func.allocStack(result_ty);
7487 try func.store(result_ptr, and_result, Type.bool, @as(u32, @intCast(ty.abiSize(mod))));
7585 try func.store(result_ptr, and_result, Type.bool, @as(u32, @intCast(ty.abiSize(pt))));
74887586 try func.store(result_ptr, ptr_val, ty, 0);
74897587 break :val result_ptr;
74907588 } else val: {
......@@ -7499,13 +7597,13 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74997597}
75007598
75017599fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7502 const mod = func.bin_file.base.comp.module.?;
7600 const pt = func.pt;
75037601 const atomic_load = func.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
75047602 const ptr = try func.resolveInst(atomic_load.ptr);
75057603 const ty = func.typeOfIndex(inst);
75067604
75077605 if (func.useAtomicFeature()) {
7508 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7606 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
75097607 1 => .i32_atomic_load8_u,
75107608 2 => .i32_atomic_load16_u,
75117609 4 => .i32_atomic_load,
......@@ -7515,7 +7613,7 @@ fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75157613 try func.emitWValue(ptr);
75167614 try func.addAtomicMemArg(tag, .{
75177615 .offset = ptr.offset(),
7518 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7616 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
75197617 });
75207618 } else {
75217619 _ = try func.load(ptr, ty, 0);
......@@ -7526,7 +7624,8 @@ fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75267624}
75277625
75287626fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7529 const mod = func.bin_file.base.comp.module.?;
7627 const pt = func.pt;
7628 const mod = pt.zcu;
75307629 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
75317630 const extra = func.air.extraData(Air.AtomicRmw, pl_op.payload).data;
75327631
......@@ -7550,7 +7649,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75507649 try func.emitWValue(ptr);
75517650 try func.emitWValue(value);
75527651 if (op == .Nand) {
7553 const wasm_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
7652 const wasm_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
75547653
75557654 const and_res = try func.binOp(value, operand, ty, .@"and");
75567655 if (wasm_bits == 32)
......@@ -7567,7 +7666,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75677666 try func.addTag(.select);
75687667 }
75697668 try func.addAtomicMemArg(
7570 switch (ty.abiSize(mod)) {
7669 switch (ty.abiSize(pt)) {
75717670 1 => .i32_atomic_rmw8_cmpxchg_u,
75727671 2 => .i32_atomic_rmw16_cmpxchg_u,
75737672 4 => .i32_atomic_rmw_cmpxchg,
......@@ -7576,7 +7675,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75767675 },
75777676 .{
75787677 .offset = ptr.offset(),
7579 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7678 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
75807679 },
75817680 );
75827681 const select_res = try func.allocLocal(ty);
......@@ -7595,7 +7694,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75957694 else => {
75967695 try func.emitWValue(ptr);
75977696 try func.emitWValue(operand);
7598 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7697 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
75997698 1 => switch (op) {
76007699 .Xchg => .i32_atomic_rmw8_xchg_u,
76017700 .Add => .i32_atomic_rmw8_add_u,
......@@ -7636,7 +7735,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
76367735 };
76377736 try func.addAtomicMemArg(tag, .{
76387737 .offset = ptr.offset(),
7639 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7738 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
76407739 });
76417740 const result = try WValue.toLocal(.stack, func, ty);
76427741 return func.finishAir(inst, result, &.{ pl_op.operand, extra.operand });
......@@ -7681,7 +7780,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
76817780 try func.store(.stack, .stack, ty, ptr.offset());
76827781 },
76837782 .Nand => {
7684 const wasm_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
7783 const wasm_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
76857784
76867785 try func.emitWValue(ptr);
76877786 const and_res = try func.binOp(result, operand, ty, .@"and");
......@@ -7701,7 +7800,8 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77017800}
77027801
77037802fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7704 const zcu = func.bin_file.base.comp.module.?;
7803 const pt = func.pt;
7804 const zcu = pt.zcu;
77057805 // Only when the atomic feature is enabled, and we're not building
77067806 // for a single-threaded build, can we emit the `fence` instruction.
77077807 // In all other cases, we emit no instructions for a fence.
......@@ -7715,7 +7815,8 @@ fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77157815}
77167816
77177817fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7718 const mod = func.bin_file.base.comp.module.?;
7818 const pt = func.pt;
7819 const mod = pt.zcu;
77197820 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77207821
77217822 const ptr = try func.resolveInst(bin_op.lhs);
......@@ -7724,7 +7825,7 @@ fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77247825 const ty = ptr_ty.childType(mod);
77257826
77267827 if (func.useAtomicFeature()) {
7727 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7828 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
77287829 1 => .i32_atomic_store8,
77297830 2 => .i32_atomic_store16,
77307831 4 => .i32_atomic_store,
......@@ -7735,7 +7836,7 @@ fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77357836 try func.lowerToStack(operand);
77367837 try func.addAtomicMemArg(tag, .{
77377838 .offset = ptr.offset(),
7738 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7839 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
77397840 });
77407841 } else {
77417842 try func.store(ptr, operand, ty, 0);
......@@ -7754,11 +7855,13 @@ fn airFrameAddress(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77547855}
77557856
77567857fn typeOf(func: *CodeGen, inst: Air.Inst.Ref) Type {
7757 const mod = func.bin_file.base.comp.module.?;
7858 const pt = func.pt;
7859 const mod = pt.zcu;
77587860 return func.air.typeOf(inst, &mod.intern_pool);
77597861}
77607862
77617863fn typeOfIndex(func: *CodeGen, inst: Air.Inst.Index) Type {
7762 const mod = func.bin_file.base.comp.module.?;
7864 const pt = func.pt;
7865 const mod = pt.zcu;
77637866 return func.air.typeOfIndex(inst, &mod.intern_pool);
77647867}
src/arch/wasm/abi.zig+21-19
......@@ -22,15 +22,16 @@ const direct: [2]Class = .{ .direct, .none };
2222/// Classifies a given Zig type to determine how they must be passed
2323/// or returned as value within a wasm function.
2424/// When all elements result in `.none`, no value must be passed in or returned.
25pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
25pub fn classifyType(ty: Type, pt: Zcu.PerThread) [2]Class {
26 const mod = pt.zcu;
2627 const ip = &mod.intern_pool;
2728 const target = mod.getTarget();
28 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return none;
29 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return none;
2930 switch (ty.zigTypeTag(mod)) {
3031 .Struct => {
31 const struct_type = mod.typeToStruct(ty).?;
32 const struct_type = pt.zcu.typeToStruct(ty).?;
3233 if (struct_type.layout == .@"packed") {
33 if (ty.bitSize(mod) <= 64) return direct;
34 if (ty.bitSize(pt) <= 64) return direct;
3435 return .{ .direct, .direct };
3536 }
3637 if (struct_type.field_types.len > 1) {
......@@ -40,13 +41,13 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
4041 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[0]);
4142 const explicit_align = struct_type.fieldAlign(ip, 0);
4243 if (explicit_align != .none) {
43 if (explicit_align.compareStrict(.gt, field_ty.abiAlignment(mod)))
44 if (explicit_align.compareStrict(.gt, field_ty.abiAlignment(pt)))
4445 return memory;
4546 }
46 return classifyType(field_ty, mod);
47 return classifyType(field_ty, pt);
4748 },
4849 .Int, .Enum, .ErrorSet => {
49 const int_bits = ty.intInfo(mod).bits;
50 const int_bits = ty.intInfo(pt.zcu).bits;
5051 if (int_bits <= 64) return direct;
5152 if (int_bits <= 128) return .{ .direct, .direct };
5253 return memory;
......@@ -61,24 +62,24 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
6162 .Vector => return direct,
6263 .Array => return memory,
6364 .Optional => {
64 assert(ty.isPtrLikeOptional(mod));
65 assert(ty.isPtrLikeOptional(pt.zcu));
6566 return direct;
6667 },
6768 .Pointer => {
68 assert(!ty.isSlice(mod));
69 assert(!ty.isSlice(pt.zcu));
6970 return direct;
7071 },
7172 .Union => {
72 const union_obj = mod.typeToUnion(ty).?;
73 const union_obj = pt.zcu.typeToUnion(ty).?;
7374 if (union_obj.getLayout(ip) == .@"packed") {
74 if (ty.bitSize(mod) <= 64) return direct;
75 if (ty.bitSize(pt) <= 64) return direct;
7576 return .{ .direct, .direct };
7677 }
77 const layout = ty.unionGetLayout(mod);
78 const layout = ty.unionGetLayout(pt);
7879 assert(layout.tag_size == 0);
7980 if (union_obj.field_types.len > 1) return memory;
8081 const first_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
81 return classifyType(first_field_ty, mod);
82 return classifyType(first_field_ty, pt);
8283 },
8384 .ErrorUnion,
8485 .Frame,
......@@ -100,28 +101,29 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
100101/// Returns the scalar type a given type can represent.
101102/// Asserts given type can be represented as scalar, such as
102103/// a struct with a single scalar field.
103pub fn scalarType(ty: Type, mod: *Zcu) Type {
104pub fn scalarType(ty: Type, pt: Zcu.PerThread) Type {
105 const mod = pt.zcu;
104106 const ip = &mod.intern_pool;
105107 switch (ty.zigTypeTag(mod)) {
106108 .Struct => {
107109 if (mod.typeToPackedStruct(ty)) |packed_struct| {
108 return scalarType(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
110 return scalarType(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
109111 } else {
110112 assert(ty.structFieldCount(mod) == 1);
111 return scalarType(ty.structFieldType(0, mod), mod);
113 return scalarType(ty.structFieldType(0, mod), pt);
112114 }
113115 },
114116 .Union => {
115117 const union_obj = mod.typeToUnion(ty).?;
116118 if (union_obj.getLayout(ip) != .@"packed") {
117 const layout = mod.getUnionLayout(union_obj);
119 const layout = pt.getUnionLayout(union_obj);
118120 if (layout.payload_size == 0 and layout.tag_size != 0) {
119 return scalarType(ty.unionTagTypeSafety(mod).?, mod);
121 return scalarType(ty.unionTagTypeSafety(mod).?, pt);
120122 }
121123 assert(union_obj.field_types.len == 1);
122124 }
123125 const first_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
124 return scalarType(first_field_ty, mod);
126 return scalarType(first_field_ty, pt);
125127 },
126128 else => return ty,
127129 }
src/arch/x86_64/CodeGen.zig+655-551
......@@ -19,7 +19,7 @@ const CodeGenError = codegen.CodeGenError;
1919const Compilation = @import("../../Compilation.zig");
2020const DebugInfoOutput = codegen.DebugInfoOutput;
2121const DW = std.dwarf;
22const ErrorMsg = Module.ErrorMsg;
22const ErrorMsg = Zcu.ErrorMsg;
2323const Result = codegen.Result;
2424const Emit = @import("Emit.zig");
2525const Liveness = @import("../../Liveness.zig");
......@@ -27,8 +27,6 @@ const Lower = @import("Lower.zig");
2727const Mir = @import("Mir.zig");
2828const Package = @import("../../Package.zig");
2929const Zcu = @import("../../Zcu.zig");
30/// Deprecated.
31const Module = Zcu;
3230const InternPool = @import("../../InternPool.zig");
3331const Alignment = InternPool.Alignment;
3432const Target = std.Target;
......@@ -52,6 +50,7 @@ const FrameIndex = bits.FrameIndex;
5250const InnerError = CodeGenError || error{OutOfRegisters};
5351
5452gpa: Allocator,
53pt: Zcu.PerThread,
5554air: Air,
5655liveness: Liveness,
5756bin_file: *link.File,
......@@ -74,7 +73,7 @@ va_info: union {
7473ret_mcv: InstTracking,
7574fn_type: Type,
7675arg_index: u32,
77src_loc: Module.LazySrcLoc,
76src_loc: Zcu.LazySrcLoc,
7877
7978eflags_inst: ?Air.Inst.Index = null,
8079
......@@ -120,18 +119,18 @@ const Owner = union(enum) {
120119 func_index: InternPool.Index,
121120 lazy_sym: link.File.LazySymbol,
122121
123 fn getDecl(owner: Owner, mod: *Module) InternPool.DeclIndex {
122 fn getDecl(owner: Owner, zcu: *Zcu) InternPool.DeclIndex {
124123 return switch (owner) {
125 .func_index => |func_index| mod.funcOwnerDeclIndex(func_index),
126 .lazy_sym => |lazy_sym| lazy_sym.ty.getOwnerDecl(mod),
124 .func_index => |func_index| zcu.funcOwnerDeclIndex(func_index),
125 .lazy_sym => |lazy_sym| lazy_sym.ty.getOwnerDecl(zcu),
127126 };
128127 }
129128
130129 fn getSymbolIndex(owner: Owner, ctx: *Self) !u32 {
130 const pt = ctx.pt;
131131 switch (owner) {
132132 .func_index => |func_index| {
133 const mod = ctx.bin_file.comp.module.?;
134 const decl_index = mod.funcOwnerDeclIndex(func_index);
133 const decl_index = ctx.pt.zcu.funcOwnerDeclIndex(func_index);
135134 if (ctx.bin_file.cast(link.File.Elf)) |elf_file| {
136135 return elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, decl_index);
137136 } else if (ctx.bin_file.cast(link.File.MachO)) |macho_file| {
......@@ -145,17 +144,17 @@ const Owner = union(enum) {
145144 },
146145 .lazy_sym => |lazy_sym| {
147146 if (ctx.bin_file.cast(link.File.Elf)) |elf_file| {
148 return elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
147 return elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
149148 ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
150149 } else if (ctx.bin_file.cast(link.File.MachO)) |macho_file| {
151 return macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, lazy_sym) catch |err|
150 return macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, pt, lazy_sym) catch |err|
152151 ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
153152 } else if (ctx.bin_file.cast(link.File.Coff)) |coff_file| {
154 const atom = coff_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
153 const atom = coff_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
155154 return ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
156155 return coff_file.getAtom(atom).getSymbolIndex().?;
157156 } else if (ctx.bin_file.cast(link.File.Plan9)) |p9_file| {
158 return p9_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
157 return p9_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
159158 return ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
160159 } else unreachable;
161160 },
......@@ -753,14 +752,14 @@ const FrameAlloc = struct {
753752 .ref_count = 0,
754753 };
755754 }
756 fn initType(ty: Type, mod: *Module) FrameAlloc {
755 fn initType(ty: Type, pt: Zcu.PerThread) FrameAlloc {
757756 return init(.{
758 .size = ty.abiSize(mod),
759 .alignment = ty.abiAlignment(mod),
757 .size = ty.abiSize(pt),
758 .alignment = ty.abiAlignment(pt),
760759 });
761760 }
762 fn initSpill(ty: Type, mod: *Module) FrameAlloc {
763 const abi_size = ty.abiSize(mod);
761 fn initSpill(ty: Type, pt: Zcu.PerThread) FrameAlloc {
762 const abi_size = ty.abiSize(pt);
764763 const spill_size = if (abi_size < 8)
765764 math.ceilPowerOfTwoAssert(u64, abi_size)
766765 else
......@@ -768,7 +767,7 @@ const FrameAlloc = struct {
768767 return init(.{
769768 .size = spill_size,
770769 .pad = @intCast(spill_size - abi_size),
771 .alignment = ty.abiAlignment(mod).maxStrict(
770 .alignment = ty.abiAlignment(pt).maxStrict(
772771 Alignment.fromNonzeroByteUnits(@min(spill_size, 8)),
773772 ),
774773 });
......@@ -777,7 +776,7 @@ const FrameAlloc = struct {
777776
778777const StackAllocation = struct {
779778 inst: ?Air.Inst.Index,
780 /// TODO do we need size? should be determined by inst.ty.abiSize(mod)
779 /// TODO do we need size? should be determined by inst.ty.abiSize(pt)
781780 size: u32,
782781};
783782
......@@ -795,16 +794,17 @@ const Self = @This();
795794
796795pub fn generate(
797796 bin_file: *link.File,
798 src_loc: Module.LazySrcLoc,
797 pt: Zcu.PerThread,
798 src_loc: Zcu.LazySrcLoc,
799799 func_index: InternPool.Index,
800800 air: Air,
801801 liveness: Liveness,
802802 code: *std.ArrayList(u8),
803803 debug_output: DebugInfoOutput,
804804) CodeGenError!Result {
805 const comp = bin_file.comp;
806 const gpa = comp.gpa;
807 const zcu = comp.module.?;
805 const zcu = pt.zcu;
806 const gpa = zcu.gpa;
807 const comp = zcu.comp;
808808 const func = zcu.funcInfo(func_index);
809809 const fn_owner_decl = zcu.declPtr(func.owner_decl);
810810 assert(fn_owner_decl.has_tv);
......@@ -812,8 +812,9 @@ pub fn generate(
812812 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
813813 const mod = namespace.fileScope(zcu).mod;
814814
815 var function = Self{
815 var function: Self = .{
816816 .gpa = gpa,
817 .pt = pt,
817818 .air = air,
818819 .liveness = liveness,
819820 .target = &mod.resolved_target.result,
......@@ -882,11 +883,11 @@ pub fn generate(
882883 function.args = call_info.args;
883884 function.ret_mcv = call_info.return_value;
884885 function.frame_allocs.set(@intFromEnum(FrameIndex.ret_addr), FrameAlloc.init(.{
885 .size = Type.usize.abiSize(zcu),
886 .alignment = Type.usize.abiAlignment(zcu).min(call_info.stack_align),
886 .size = Type.usize.abiSize(pt),
887 .alignment = Type.usize.abiAlignment(pt).min(call_info.stack_align),
887888 }));
888889 function.frame_allocs.set(@intFromEnum(FrameIndex.base_ptr), FrameAlloc.init(.{
889 .size = Type.usize.abiSize(zcu),
890 .size = Type.usize.abiSize(pt),
890891 .alignment = Alignment.min(
891892 call_info.stack_align,
892893 Alignment.fromNonzeroByteUnits(function.target.stackAlignment()),
......@@ -971,7 +972,8 @@ pub fn generate(
971972
972973pub fn generateLazy(
973974 bin_file: *link.File,
974 src_loc: Module.LazySrcLoc,
975 pt: Zcu.PerThread,
976 src_loc: Zcu.LazySrcLoc,
975977 lazy_sym: link.File.LazySymbol,
976978 code: *std.ArrayList(u8),
977979 debug_output: DebugInfoOutput,
......@@ -980,8 +982,9 @@ pub fn generateLazy(
980982 const gpa = comp.gpa;
981983 // This function is for generating global code, so we use the root module.
982984 const mod = comp.root_mod;
983 var function = Self{
985 var function: Self = .{
984986 .gpa = gpa,
987 .pt = pt,
985988 .air = undefined,
986989 .liveness = undefined,
987990 .target = &mod.resolved_target.result,
......@@ -1065,7 +1068,7 @@ pub fn generateLazy(
10651068}
10661069
10671070const FormatDeclData = struct {
1068 mod: *Module,
1071 zcu: *Zcu,
10691072 decl_index: InternPool.DeclIndex,
10701073};
10711074fn formatDecl(
......@@ -1074,11 +1077,11 @@ fn formatDecl(
10741077 _: std.fmt.FormatOptions,
10751078 writer: anytype,
10761079) @TypeOf(writer).Error!void {
1077 try data.mod.declPtr(data.decl_index).renderFullyQualifiedName(data.mod, writer);
1080 try data.zcu.declPtr(data.decl_index).renderFullyQualifiedName(data.zcu, writer);
10781081}
10791082fn fmtDecl(self: *Self, decl_index: InternPool.DeclIndex) std.fmt.Formatter(formatDecl) {
10801083 return .{ .data = .{
1081 .mod = self.bin_file.comp.module.?,
1084 .zcu = self.pt.zcu,
10821085 .decl_index = decl_index,
10831086 } };
10841087}
......@@ -1095,7 +1098,7 @@ fn formatAir(
10951098) @TypeOf(writer).Error!void {
10961099 @import("../../print_air.zig").dumpInst(
10971100 data.inst,
1098 data.self.bin_file.comp.module.?,
1101 data.self.pt,
10991102 data.self.air,
11001103 data.self.liveness,
11011104 );
......@@ -1746,7 +1749,8 @@ fn asmMemoryRegisterImmediate(
17461749}
17471750
17481751fn gen(self: *Self) InnerError!void {
1749 const mod = self.bin_file.comp.module.?;
1752 const pt = self.pt;
1753 const mod = pt.zcu;
17501754 const fn_info = mod.typeToFunc(self.fn_type).?;
17511755 const cc = abi.resolveCallingConvention(fn_info.cc, self.target.*);
17521756 if (cc != .Naked) {
......@@ -1764,7 +1768,7 @@ fn gen(self: *Self) InnerError!void {
17641768 // The address where to store the return value for the caller is in a
17651769 // register which the callee is free to clobber. Therefore, we purposely
17661770 // spill it to stack immediately.
1767 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(Type.usize, mod));
1771 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(Type.usize, pt));
17681772 try self.genSetMem(
17691773 .{ .frame = frame_index },
17701774 0,
......@@ -1800,7 +1804,7 @@ fn gen(self: *Self) InnerError!void {
18001804 try self.asmRegisterImmediate(.{ ._, .cmp }, .al, Immediate.u(info.fp_count));
18011805 const skip_sse_reloc = try self.asmJccReloc(.na, undefined);
18021806
1803 const vec_2_f64 = try mod.vectorType(.{ .len = 2, .child = .f64_type });
1807 const vec_2_f64 = try pt.vectorType(.{ .len = 2, .child = .f64_type });
18041808 for (abi.SysV.c_abi_sse_param_regs[info.fp_count..], info.fp_count..) |reg, reg_i|
18051809 try self.genSetMem(
18061810 .{ .frame = reg_save_area_fi },
......@@ -1951,7 +1955,8 @@ fn gen(self: *Self) InnerError!void {
19511955}
19521956
19531957fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
1954 const mod = self.bin_file.comp.module.?;
1958 const pt = self.pt;
1959 const mod = pt.zcu;
19551960 const ip = &mod.intern_pool;
19561961 const air_tags = self.air.instructions.items(.tag);
19571962
......@@ -2222,12 +2227,13 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
22222227}
22232228
22242229fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
2225 const mod = self.bin_file.comp.module.?;
2230 const pt = self.pt;
2231 const mod = pt.zcu;
22262232 const ip = &mod.intern_pool;
22272233 switch (lazy_sym.ty.zigTypeTag(mod)) {
22282234 .Enum => {
22292235 const enum_ty = lazy_sym.ty;
2230 wip_mir_log.debug("{}.@tagName:", .{enum_ty.fmt(mod)});
2236 wip_mir_log.debug("{}.@tagName:", .{enum_ty.fmt(pt)});
22312237
22322238 const resolved_cc = abi.resolveCallingConvention(.Unspecified, self.target.*);
22332239 const param_regs = abi.getCAbiIntParamRegs(resolved_cc);
......@@ -2249,7 +2255,7 @@ fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
22492255 const tag_names = enum_ty.enumFields(mod);
22502256 for (exitlude_jump_relocs, 0..) |*exitlude_jump_reloc, tag_index| {
22512257 const tag_name_len = tag_names.get(ip)[tag_index].length(ip);
2252 const tag_val = try mod.enumValueFieldIndex(enum_ty, @intCast(tag_index));
2258 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
22532259 const tag_mcv = try self.genTypedValue(tag_val);
22542260 try self.genBinOpMir(.{ ._, .cmp }, enum_ty, enum_mcv, tag_mcv);
22552261 const skip_reloc = try self.asmJccReloc(.ne, undefined);
......@@ -2282,7 +2288,7 @@ fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
22822288 },
22832289 else => return self.fail(
22842290 "TODO implement {s} for {}",
2285 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(mod) },
2291 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(pt) },
22862292 ),
22872293 }
22882294}
......@@ -2481,14 +2487,15 @@ fn allocFrameIndex(self: *Self, alloc: FrameAlloc) !FrameIndex {
24812487
24822488/// Use a pointer instruction as the basis for allocating stack memory.
24832489fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !FrameIndex {
2484 const mod = self.bin_file.comp.module.?;
2490 const pt = self.pt;
2491 const mod = pt.zcu;
24852492 const ptr_ty = self.typeOfIndex(inst);
24862493 const val_ty = ptr_ty.childType(mod);
24872494 return self.allocFrameIndex(FrameAlloc.init(.{
2488 .size = math.cast(u32, val_ty.abiSize(mod)) orelse {
2489 return self.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(mod)});
2495 .size = math.cast(u32, val_ty.abiSize(pt)) orelse {
2496 return self.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(pt)});
24902497 },
2491 .alignment = ptr_ty.ptrAlignment(mod).max(.@"1"),
2498 .alignment = ptr_ty.ptrAlignment(pt).max(.@"1"),
24922499 }));
24932500}
24942501
......@@ -2501,9 +2508,10 @@ fn allocTempRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool) !MCValue {
25012508}
25022509
25032510fn allocRegOrMemAdvanced(self: *Self, ty: Type, inst: ?Air.Inst.Index, reg_ok: bool) !MCValue {
2504 const mod = self.bin_file.comp.module.?;
2505 const abi_size = math.cast(u32, ty.abiSize(mod)) orelse {
2506 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(mod)});
2511 const pt = self.pt;
2512 const mod = pt.zcu;
2513 const abi_size = math.cast(u32, ty.abiSize(pt)) orelse {
2514 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(pt)});
25072515 };
25082516
25092517 if (reg_ok) need_mem: {
......@@ -2529,12 +2537,13 @@ fn allocRegOrMemAdvanced(self: *Self, ty: Type, inst: ?Air.Inst.Index, reg_ok: b
25292537 }
25302538 }
25312539
2532 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ty, mod));
2540 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ty, pt));
25332541 return .{ .load_frame = .{ .index = frame_index } };
25342542}
25352543
25362544fn regClassForType(self: *Self, ty: Type) RegisterManager.RegisterBitSet {
2537 const mod = self.bin_file.comp.module.?;
2545 const pt = self.pt;
2546 const mod = pt.zcu;
25382547 return switch (ty.zigTypeTag(mod)) {
25392548 .Float => switch (ty.floatBits(self.target.*)) {
25402549 80 => abi.RegisterClass.x87,
......@@ -2849,7 +2858,8 @@ fn airFptrunc(self: *Self, inst: Air.Inst.Index) !void {
28492858}
28502859
28512860fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
2852 const mod = self.bin_file.comp.module.?;
2861 const pt = self.pt;
2862 const mod = pt.zcu;
28532863 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
28542864 const dst_ty = self.typeOfIndex(inst);
28552865 const dst_scalar_ty = dst_ty.scalarType(mod);
......@@ -2892,14 +2902,14 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
28922902 } }, &.{src_scalar_ty}, &.{.{ .air_ref = ty_op.operand }});
28932903 }
28942904
2895 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
2905 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
28962906 const src_mcv = try self.resolveInst(ty_op.operand);
28972907 const dst_mcv = if (src_mcv.isRegister() and self.reuseOperand(inst, ty_op.operand, 0, src_mcv))
28982908 src_mcv
28992909 else
29002910 try self.copyToRegisterWithInstTracking(inst, dst_ty, src_mcv);
29012911 const dst_reg = dst_mcv.getReg().?;
2902 const dst_alias = registerAlias(dst_reg, @intCast(@max(dst_ty.abiSize(mod), 16)));
2912 const dst_alias = registerAlias(dst_reg, @intCast(@max(dst_ty.abiSize(pt), 16)));
29032913 const dst_lock = self.register_manager.lockReg(dst_reg);
29042914 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
29052915
......@@ -2978,19 +2988,20 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
29782988 }
29792989 break :result dst_mcv;
29802990 } orelse return self.fail("TODO implement airFpext from {} to {}", .{
2981 src_ty.fmt(mod), dst_ty.fmt(mod),
2991 src_ty.fmt(pt), dst_ty.fmt(pt),
29822992 });
29832993 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
29842994}
29852995
29862996fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
2987 const mod = self.bin_file.comp.module.?;
2997 const pt = self.pt;
2998 const mod = pt.zcu;
29882999 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
29893000 const src_ty = self.typeOf(ty_op.operand);
29903001 const dst_ty = self.typeOfIndex(inst);
29913002
29923003 const result = @as(?MCValue, result: {
2993 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3004 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
29943005
29953006 const src_int_info = src_ty.intInfo(mod);
29963007 const dst_int_info = dst_ty.intInfo(mod);
......@@ -3001,13 +3012,13 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
30013012
30023013 const src_mcv = try self.resolveInst(ty_op.operand);
30033014 if (dst_ty.isVector(mod)) {
3004 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3015 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
30053016 const max_abi_size = @max(dst_abi_size, src_abi_size);
30063017 if (max_abi_size > @as(u32, if (self.hasFeature(.avx2)) 32 else 16)) break :result null;
30073018 const has_avx = self.hasFeature(.avx);
30083019
3009 const dst_elem_abi_size = dst_ty.childType(mod).abiSize(mod);
3010 const src_elem_abi_size = src_ty.childType(mod).abiSize(mod);
3020 const dst_elem_abi_size = dst_ty.childType(mod).abiSize(pt);
3021 const src_elem_abi_size = src_ty.childType(mod).abiSize(pt);
30113022 switch (math.order(dst_elem_abi_size, src_elem_abi_size)) {
30123023 .lt => {
30133024 const mir_tag: Mir.Inst.FixedTag = switch (dst_elem_abi_size) {
......@@ -3236,19 +3247,20 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
32363247
32373248 break :result dst_mcv;
32383249 }) orelse return self.fail("TODO implement airIntCast from {} to {}", .{
3239 src_ty.fmt(mod), dst_ty.fmt(mod),
3250 src_ty.fmt(pt), dst_ty.fmt(pt),
32403251 });
32413252 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
32423253}
32433254
32443255fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
3245 const mod = self.bin_file.comp.module.?;
3256 const pt = self.pt;
3257 const mod = pt.zcu;
32463258 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32473259
32483260 const dst_ty = self.typeOfIndex(inst);
3249 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3261 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
32503262 const src_ty = self.typeOf(ty_op.operand);
3251 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3263 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
32523264
32533265 const result = result: {
32543266 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -3278,9 +3290,9 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
32783290 if (dst_ty.zigTypeTag(mod) == .Vector) {
32793291 assert(src_ty.zigTypeTag(mod) == .Vector and dst_ty.vectorLen(mod) == src_ty.vectorLen(mod));
32803292 const dst_elem_ty = dst_ty.childType(mod);
3281 const dst_elem_abi_size: u32 = @intCast(dst_elem_ty.abiSize(mod));
3293 const dst_elem_abi_size: u32 = @intCast(dst_elem_ty.abiSize(pt));
32823294 const src_elem_ty = src_ty.childType(mod);
3283 const src_elem_abi_size: u32 = @intCast(src_elem_ty.abiSize(mod));
3295 const src_elem_abi_size: u32 = @intCast(src_elem_ty.abiSize(pt));
32843296
32853297 const mir_tag = @as(?Mir.Inst.FixedTag, switch (dst_elem_abi_size) {
32863298 1 => switch (src_elem_abi_size) {
......@@ -3305,20 +3317,20 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
33053317 else => null,
33063318 },
33073319 else => null,
3308 }) orelse return self.fail("TODO implement airTrunc for {}", .{dst_ty.fmt(mod)});
3320 }) orelse return self.fail("TODO implement airTrunc for {}", .{dst_ty.fmt(pt)});
33093321
33103322 const dst_info = dst_elem_ty.intInfo(mod);
33113323 const src_info = src_elem_ty.intInfo(mod);
33123324
3313 const mask_val = try mod.intValue(src_elem_ty, @as(u64, math.maxInt(u64)) >> @intCast(64 - dst_info.bits));
3325 const mask_val = try pt.intValue(src_elem_ty, @as(u64, math.maxInt(u64)) >> @intCast(64 - dst_info.bits));
33143326
3315 const splat_ty = try mod.vectorType(.{
3327 const splat_ty = try pt.vectorType(.{
33163328 .len = @intCast(@divExact(@as(u64, if (src_abi_size > 16) 256 else 128), src_info.bits)),
33173329 .child = src_elem_ty.ip_index,
33183330 });
3319 const splat_abi_size: u32 = @intCast(splat_ty.abiSize(mod));
3331 const splat_abi_size: u32 = @intCast(splat_ty.abiSize(pt));
33203332
3321 const splat_val = try mod.intern(.{ .aggregate = .{
3333 const splat_val = try pt.intern(.{ .aggregate = .{
33223334 .ty = splat_ty.ip_index,
33233335 .storage = .{ .repeated_elem = mask_val.ip_index },
33243336 } });
......@@ -3375,7 +3387,7 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
33753387 }
33763388 } else if (dst_abi_size <= 16) {
33773389 const dst_info = dst_ty.intInfo(mod);
3378 const high_ty = try mod.intType(dst_info.signedness, dst_info.bits - 64);
3390 const high_ty = try pt.intType(dst_info.signedness, dst_info.bits - 64);
33793391 if (self.regExtraBits(high_ty) > 0) {
33803392 try self.truncateRegister(high_ty, dst_mcv.register_pair[1].to64());
33813393 }
......@@ -3400,12 +3412,12 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
34003412}
34013413
34023414fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
3403 const mod = self.bin_file.comp.module.?;
3415 const pt = self.pt;
34043416 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34053417 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
34063418
34073419 const slice_ty = self.typeOfIndex(inst);
3408 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, mod));
3420 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
34093421
34103422 const ptr_ty = self.typeOf(bin_op.lhs);
34113423 try self.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, .{ .air_ref = bin_op.lhs }, .{});
......@@ -3413,7 +3425,7 @@ fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
34133425 const len_ty = self.typeOf(bin_op.rhs);
34143426 try self.genSetMem(
34153427 .{ .frame = frame_index },
3416 @intCast(ptr_ty.abiSize(mod)),
3428 @intCast(ptr_ty.abiSize(pt)),
34173429 len_ty,
34183430 .{ .air_ref = bin_op.rhs },
34193431 .{},
......@@ -3430,14 +3442,15 @@ fn airUnOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
34303442}
34313443
34323444fn airBinOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
3433 const mod = self.bin_file.comp.module.?;
3445 const pt = self.pt;
3446 const mod = pt.zcu;
34343447 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34353448 const dst_mcv = try self.genBinOp(inst, tag, bin_op.lhs, bin_op.rhs);
34363449
34373450 const dst_ty = self.typeOfIndex(inst);
34383451 if (dst_ty.isAbiInt(mod)) {
3439 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3440 const bit_size: u32 = @intCast(dst_ty.bitSize(mod));
3452 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
3453 const bit_size: u32 = @intCast(dst_ty.bitSize(pt));
34413454 if (abi_size * 8 > bit_size) {
34423455 const dst_lock = switch (dst_mcv) {
34433456 .register => |dst_reg| self.register_manager.lockRegAssumeUnused(dst_reg),
......@@ -3452,7 +3465,7 @@ fn airBinOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
34523465 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
34533466 defer self.register_manager.unlockReg(tmp_lock);
34543467
3455 const hi_ty = try mod.intType(.unsigned, @intCast((dst_ty.bitSize(mod) - 1) % 64 + 1));
3468 const hi_ty = try pt.intType(.unsigned, @intCast((dst_ty.bitSize(pt) - 1) % 64 + 1));
34563469 const hi_mcv = dst_mcv.address().offset(@intCast(bit_size / 64 * 8)).deref();
34573470 try self.genSetReg(tmp_reg, hi_ty, hi_mcv, .{});
34583471 try self.truncateRegister(dst_ty, tmp_reg);
......@@ -3471,7 +3484,8 @@ fn airPtrArithmetic(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void
34713484}
34723485
34733486fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
3474 const mod = self.bin_file.comp.module.?;
3487 const pt = self.pt;
3488 const mod = pt.zcu;
34753489 const air_tag = self.air.instructions.items(.tag);
34763490 const air_data = self.air.instructions.items(.data);
34773491
......@@ -3497,7 +3511,7 @@ fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
34973511 }
34983512 } else if (dst_air.toInterned()) |ip_index| {
34993513 var space: Value.BigIntSpace = undefined;
3500 const src_int = Value.fromInterned(ip_index).toBigInt(&space, mod);
3514 const src_int = Value.fromInterned(ip_index).toBigInt(&space, pt);
35013515 return @as(u16, @intCast(src_int.bitCountTwosComp())) +
35023516 @intFromBool(src_int.positive and dst_info.signedness == .signed);
35033517 }
......@@ -3505,7 +3519,8 @@ fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
35053519}
35063520
35073521fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
3508 const mod = self.bin_file.comp.module.?;
3522 const pt = self.pt;
3523 const mod = pt.zcu;
35093524 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
35103525 const result = result: {
35113526 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
......@@ -3514,10 +3529,10 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35143529 .Float, .Vector => break :result try self.genBinOp(inst, tag, bin_op.lhs, bin_op.rhs),
35153530 else => {},
35163531 }
3517 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3532 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
35183533
35193534 const dst_info = dst_ty.intInfo(mod);
3520 const src_ty = try mod.intType(dst_info.signedness, switch (tag) {
3535 const src_ty = try pt.intType(dst_info.signedness, switch (tag) {
35213536 else => unreachable,
35223537 .mul, .mul_wrap => @max(
35233538 self.activeIntBits(bin_op.lhs),
......@@ -3526,7 +3541,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35263541 ),
35273542 .div_trunc, .div_floor, .div_exact, .rem, .mod => dst_info.bits,
35283543 });
3529 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3544 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
35303545
35313546 if (dst_abi_size == 16 and src_abi_size == 16) switch (tag) {
35323547 else => unreachable,
......@@ -3539,7 +3554,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35393554 state: State,
35403555 reloc: Mir.Inst.Index,
35413556 } = if (signed and tag == .div_floor) state: {
3542 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(Type.usize, mod));
3557 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(Type.usize, pt));
35433558 try self.asmMemoryImmediate(
35443559 .{ ._, .mov },
35453560 .{ .base = .{ .frame = frame_index }, .mod = .{ .rm = .{ .size = .qword } } },
......@@ -3614,7 +3629,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
36143629 .rem, .mod => "mod",
36153630 else => unreachable,
36163631 },
3617 intCompilerRtAbiName(@intCast(dst_ty.bitSize(mod))),
3632 intCompilerRtAbiName(@intCast(dst_ty.bitSize(pt))),
36183633 }) catch unreachable,
36193634 } },
36203635 &.{ src_ty, src_ty },
......@@ -3643,7 +3658,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
36433658 .return_type = dst_ty.toIntern(),
36443659 .param_types = &.{ src_ty.toIntern(), src_ty.toIntern() },
36453660 .callee = std.fmt.bufPrint(&callee_buf, "__div{c}i3", .{
3646 intCompilerRtAbiName(@intCast(dst_ty.bitSize(mod))),
3661 intCompilerRtAbiName(@intCast(dst_ty.bitSize(pt))),
36473662 }) catch unreachable,
36483663 } },
36493664 &.{ src_ty, src_ty },
......@@ -3734,12 +3749,13 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
37343749}
37353750
37363751fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
3737 const mod = self.bin_file.comp.module.?;
3752 const pt = self.pt;
3753 const mod = pt.zcu;
37383754 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
37393755 const ty = self.typeOf(bin_op.lhs);
3740 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
3756 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
37413757 "TODO implement airAddSat for {}",
3742 .{ty.fmt(mod)},
3758 .{ty.fmt(pt)},
37433759 );
37443760
37453761 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -3804,7 +3820,7 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38043820 break :cc .o;
38053821 } else cc: {
38063822 try self.genSetReg(limit_reg, ty, .{
3807 .immediate = @as(u64, math.maxInt(u64)) >> @intCast(64 - ty.bitSize(mod)),
3823 .immediate = @as(u64, math.maxInt(u64)) >> @intCast(64 - ty.bitSize(pt)),
38083824 }, .{});
38093825
38103826 try self.genBinOpMir(.{ ._, .add }, ty, dst_mcv, rhs_mcv);
......@@ -3815,7 +3831,7 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38153831 break :cc .c;
38163832 };
38173833
3818 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
3834 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
38193835 try self.asmCmovccRegisterRegister(
38203836 cc,
38213837 registerAlias(dst_reg, cmov_abi_size),
......@@ -3834,12 +3850,13 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38343850}
38353851
38363852fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
3837 const mod = self.bin_file.comp.module.?;
3853 const pt = self.pt;
3854 const mod = pt.zcu;
38383855 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38393856 const ty = self.typeOf(bin_op.lhs);
3840 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
3857 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
38413858 "TODO implement airSubSat for {}",
3842 .{ty.fmt(mod)},
3859 .{ty.fmt(pt)},
38433860 );
38443861
38453862 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -3908,7 +3925,7 @@ fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
39083925 break :cc .c;
39093926 };
39103927
3911 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
3928 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
39123929 try self.asmCmovccRegisterRegister(
39133930 cc,
39143931 registerAlias(dst_reg, cmov_abi_size),
......@@ -3927,13 +3944,14 @@ fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
39273944}
39283945
39293946fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
3930 const mod = self.bin_file.comp.module.?;
3947 const pt = self.pt;
3948 const mod = pt.zcu;
39313949 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
39323950 const ty = self.typeOf(bin_op.lhs);
39333951
39343952 const result = result: {
39353953 if (ty.toIntern() == .i128_type) {
3936 const ptr_c_int = try mod.singleMutPtrType(Type.c_int);
3954 const ptr_c_int = try pt.singleMutPtrType(Type.c_int);
39373955 const overflow = try self.allocTempRegOrMem(Type.c_int, false);
39383956
39393957 const dst_mcv = try self.genCall(.{ .lib = .{
......@@ -4010,9 +4028,9 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40104028 break :result dst_mcv;
40114029 }
40124030
4013 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
4031 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
40144032 "TODO implement airMulSat for {}",
4015 .{ty.fmt(mod)},
4033 .{ty.fmt(pt)},
40164034 );
40174035
40184036 try self.spillRegisters(&.{ .rax, .rcx, .rdx });
......@@ -4061,7 +4079,7 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40614079 };
40624080
40634081 const dst_mcv = try self.genMulDivBinOp(.mul, inst, ty, ty, lhs_mcv, rhs_mcv);
4064 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
4082 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
40654083 try self.asmCmovccRegisterRegister(
40664084 cc,
40674085 registerAlias(dst_mcv.register, cmov_abi_size),
......@@ -4073,7 +4091,8 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40734091}
40744092
40754093fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4076 const mod = self.bin_file.comp.module.?;
4094 const pt = self.pt;
4095 const mod = pt.zcu;
40774096 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40784097 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
40794098 const result: MCValue = result: {
......@@ -4109,17 +4128,17 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41094128 }
41104129
41114130 const frame_index =
4112 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4131 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41134132 try self.genSetMem(
41144133 .{ .frame = frame_index },
4115 @intCast(tuple_ty.structFieldOffset(1, mod)),
4134 @intCast(tuple_ty.structFieldOffset(1, pt)),
41164135 Type.u1,
41174136 .{ .eflags = cc },
41184137 .{},
41194138 );
41204139 try self.genSetMem(
41214140 .{ .frame = frame_index },
4122 @intCast(tuple_ty.structFieldOffset(0, mod)),
4141 @intCast(tuple_ty.structFieldOffset(0, pt)),
41234142 ty,
41244143 partial_mcv,
41254144 .{},
......@@ -4128,7 +4147,7 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41284147 }
41294148
41304149 const frame_index =
4131 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4150 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41324151 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
41334152 break :result .{ .load_frame = .{ .index = frame_index } };
41344153 },
......@@ -4139,7 +4158,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41394158}
41404159
41414160fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4142 const mod = self.bin_file.comp.module.?;
4161 const pt = self.pt;
4162 const mod = pt.zcu;
41434163 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
41444164 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
41454165 const result: MCValue = result: {
......@@ -4186,17 +4206,17 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41864206 }
41874207
41884208 const frame_index =
4189 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4209 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41904210 try self.genSetMem(
41914211 .{ .frame = frame_index },
4192 @intCast(tuple_ty.structFieldOffset(1, mod)),
4212 @intCast(tuple_ty.structFieldOffset(1, pt)),
41934213 tuple_ty.structFieldType(1, mod),
41944214 .{ .eflags = cc },
41954215 .{},
41964216 );
41974217 try self.genSetMem(
41984218 .{ .frame = frame_index },
4199 @intCast(tuple_ty.structFieldOffset(0, mod)),
4219 @intCast(tuple_ty.structFieldOffset(0, pt)),
42004220 tuple_ty.structFieldType(0, mod),
42014221 partial_mcv,
42024222 .{},
......@@ -4205,7 +4225,7 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
42054225 }
42064226
42074227 const frame_index =
4208 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4228 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
42094229 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
42104230 break :result .{ .load_frame = .{ .index = frame_index } };
42114231 },
......@@ -4222,7 +4242,8 @@ fn genSetFrameTruncatedOverflowCompare(
42224242 src_mcv: MCValue,
42234243 overflow_cc: ?Condition,
42244244) !void {
4225 const mod = self.bin_file.comp.module.?;
4245 const pt = self.pt;
4246 const mod = pt.zcu;
42264247 const src_lock = switch (src_mcv) {
42274248 .register => |reg| self.register_manager.lockReg(reg),
42284249 else => null,
......@@ -4233,12 +4254,12 @@ fn genSetFrameTruncatedOverflowCompare(
42334254 const int_info = ty.intInfo(mod);
42344255
42354256 const hi_bits = (int_info.bits - 1) % 64 + 1;
4236 const hi_ty = try mod.intType(int_info.signedness, hi_bits);
4257 const hi_ty = try pt.intType(int_info.signedness, hi_bits);
42374258
42384259 const limb_bits: u16 = @intCast(if (int_info.bits <= 64) self.regBitSize(ty) else 64);
4239 const limb_ty = try mod.intType(int_info.signedness, limb_bits);
4260 const limb_ty = try pt.intType(int_info.signedness, limb_bits);
42404261
4241 const rest_ty = try mod.intType(.unsigned, int_info.bits - hi_bits);
4262 const rest_ty = try pt.intType(.unsigned, int_info.bits - hi_bits);
42424263
42434264 const temp_regs =
42444265 try self.register_manager.allocRegs(3, .{null} ** 3, abi.RegisterClass.gp);
......@@ -4269,7 +4290,7 @@ fn genSetFrameTruncatedOverflowCompare(
42694290 );
42704291 }
42714292
4272 const payload_off: i32 = @intCast(tuple_ty.structFieldOffset(0, mod));
4293 const payload_off: i32 = @intCast(tuple_ty.structFieldOffset(0, pt));
42734294 if (hi_limb_off > 0) try self.genSetMem(
42744295 .{ .frame = frame_index },
42754296 payload_off,
......@@ -4286,7 +4307,7 @@ fn genSetFrameTruncatedOverflowCompare(
42864307 );
42874308 try self.genSetMem(
42884309 .{ .frame = frame_index },
4289 @intCast(tuple_ty.structFieldOffset(1, mod)),
4310 @intCast(tuple_ty.structFieldOffset(1, pt)),
42904311 tuple_ty.structFieldType(1, mod),
42914312 if (overflow_cc) |_| .{ .register = overflow_reg.to8() } else .{ .eflags = .ne },
42924313 .{},
......@@ -4294,18 +4315,19 @@ fn genSetFrameTruncatedOverflowCompare(
42944315}
42954316
42964317fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4297 const mod = self.bin_file.comp.module.?;
4318 const pt = self.pt;
4319 const mod = pt.zcu;
42984320 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
42994321 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
43004322 const tuple_ty = self.typeOfIndex(inst);
43014323 const dst_ty = self.typeOf(bin_op.lhs);
43024324 const result: MCValue = switch (dst_ty.zigTypeTag(mod)) {
4303 .Vector => return self.fail("TODO implement airMulWithOverflow for {}", .{dst_ty.fmt(mod)}),
4325 .Vector => return self.fail("TODO implement airMulWithOverflow for {}", .{dst_ty.fmt(pt)}),
43044326 .Int => result: {
43054327 const dst_info = dst_ty.intInfo(mod);
43064328 if (dst_info.bits > 128 and dst_info.signedness == .unsigned) {
43074329 const slow_inc = self.hasFeature(.slow_incdec);
4308 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
4330 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
43094331 const limb_len = math.divCeil(u32, abi_size, 8) catch unreachable;
43104332
43114333 try self.spillRegisters(&.{ .rax, .rcx, .rdx });
......@@ -4316,7 +4338,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43164338 try self.genInlineMemset(
43174339 dst_mcv.address(),
43184340 .{ .immediate = 0 },
4319 .{ .immediate = tuple_ty.abiSize(mod) },
4341 .{ .immediate = tuple_ty.abiSize(pt) },
43204342 .{},
43214343 );
43224344 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -4356,7 +4378,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43564378 .index = temp_regs[3].to64(),
43574379 .scale = .@"8",
43584380 .disp = dst_mcv.load_frame.off +
4359 @as(i32, @intCast(tuple_ty.structFieldOffset(0, mod))),
4381 @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
43604382 } },
43614383 }, .rdx);
43624384 try self.asmSetccRegister(.c, .cl);
......@@ -4380,7 +4402,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43804402 .index = temp_regs[3].to64(),
43814403 .scale = .@"8",
43824404 .disp = dst_mcv.load_frame.off +
4383 @as(i32, @intCast(tuple_ty.structFieldOffset(0, mod))),
4405 @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
43844406 } },
43854407 }, .rax);
43864408 try self.asmSetccRegister(.c, .ch);
......@@ -4429,7 +4451,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44294451 .mod = .{ .rm = .{
44304452 .size = .byte,
44314453 .disp = dst_mcv.load_frame.off +
4432 @as(i32, @intCast(tuple_ty.structFieldOffset(1, mod))),
4454 @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
44334455 } },
44344456 }, Immediate.u(1));
44354457 self.performReloc(no_overflow);
......@@ -4453,11 +4475,11 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44534475 const lhs_active_bits = self.activeIntBits(bin_op.lhs);
44544476 const rhs_active_bits = self.activeIntBits(bin_op.rhs);
44554477 const src_bits = @max(lhs_active_bits, rhs_active_bits, dst_info.bits / 2);
4456 const src_ty = try mod.intType(dst_info.signedness, src_bits);
4478 const src_ty = try pt.intType(dst_info.signedness, src_bits);
44574479 if (src_bits > 64 and src_bits <= 128 and
44584480 dst_info.bits > 64 and dst_info.bits <= 128) switch (dst_info.signedness) {
44594481 .signed => {
4460 const ptr_c_int = try mod.singleMutPtrType(Type.c_int);
4482 const ptr_c_int = try pt.singleMutPtrType(Type.c_int);
44614483 const overflow = try self.allocTempRegOrMem(Type.c_int, false);
44624484 const result = try self.genCall(.{ .lib = .{
44634485 .return_type = .i128_type,
......@@ -4472,7 +4494,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44724494 const dst_mcv = try self.allocRegOrMem(inst, false);
44734495 try self.genSetMem(
44744496 .{ .frame = dst_mcv.load_frame.index },
4475 @intCast(tuple_ty.structFieldOffset(0, mod)),
4497 @intCast(tuple_ty.structFieldOffset(0, pt)),
44764498 tuple_ty.structFieldType(0, mod),
44774499 result,
44784500 .{},
......@@ -4484,7 +4506,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44844506 );
44854507 try self.genSetMem(
44864508 .{ .frame = dst_mcv.load_frame.index },
4487 @intCast(tuple_ty.structFieldOffset(1, mod)),
4509 @intCast(tuple_ty.structFieldOffset(1, pt)),
44884510 tuple_ty.structFieldType(1, mod),
44894511 .{ .eflags = .ne },
44904512 .{},
......@@ -4596,14 +4618,14 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
45964618 const dst_mcv = try self.allocRegOrMem(inst, false);
45974619 try self.genSetMem(
45984620 .{ .frame = dst_mcv.load_frame.index },
4599 @intCast(tuple_ty.structFieldOffset(0, mod)),
4621 @intCast(tuple_ty.structFieldOffset(0, pt)),
46004622 tuple_ty.structFieldType(0, mod),
46014623 .{ .register_pair = .{ .rax, .rdx } },
46024624 .{},
46034625 );
46044626 try self.genSetMem(
46054627 .{ .frame = dst_mcv.load_frame.index },
4606 @intCast(tuple_ty.structFieldOffset(1, mod)),
4628 @intCast(tuple_ty.structFieldOffset(1, pt)),
46074629 tuple_ty.structFieldType(1, mod),
46084630 .{ .register = tmp_regs[1] },
46094631 .{},
......@@ -4636,7 +4658,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46364658 self.eflags_inst = inst;
46374659 break :result .{ .register_overflow = .{ .reg = reg, .eflags = cc } };
46384660 } else {
4639 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4661 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
46404662 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
46414663 break :result .{ .load_frame = .{ .index = frame_index } };
46424664 },
......@@ -4644,21 +4666,21 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46444666 // For now, this is the only supported multiply that doesn't fit in a register.
46454667 if (dst_info.bits > 128 or src_bits != 64)
46464668 return self.fail("TODO implement airWithOverflow from {} to {}", .{
4647 src_ty.fmt(mod), dst_ty.fmt(mod),
4669 src_ty.fmt(pt), dst_ty.fmt(pt),
46484670 });
46494671
4650 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4672 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
46514673 if (dst_info.bits >= lhs_active_bits + rhs_active_bits) {
46524674 try self.genSetMem(
46534675 .{ .frame = frame_index },
4654 @intCast(tuple_ty.structFieldOffset(0, mod)),
4676 @intCast(tuple_ty.structFieldOffset(0, pt)),
46554677 tuple_ty.structFieldType(0, mod),
46564678 partial_mcv,
46574679 .{},
46584680 );
46594681 try self.genSetMem(
46604682 .{ .frame = frame_index },
4661 @intCast(tuple_ty.structFieldOffset(1, mod)),
4683 @intCast(tuple_ty.structFieldOffset(1, pt)),
46624684 tuple_ty.structFieldType(1, mod),
46634685 .{ .immediate = 0 }, // cc being set is impossible
46644686 .{},
......@@ -4682,8 +4704,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46824704/// Clobbers .rax and .rdx registers.
46834705/// Quotient is saved in .rax and remainder in .rdx.
46844706fn genIntMulDivOpMir(self: *Self, tag: Mir.Inst.FixedTag, ty: Type, lhs: MCValue, rhs: MCValue) !void {
4685 const mod = self.bin_file.comp.module.?;
4686 const abi_size: u32 = @intCast(ty.abiSize(mod));
4707 const pt = self.pt;
4708 const abi_size: u32 = @intCast(ty.abiSize(pt));
46874709 const bit_size: u32 = @intCast(self.regBitSize(ty));
46884710 if (abi_size > 8) {
46894711 return self.fail("TODO implement genIntMulDivOpMir for ABI size larger than 8", .{});
......@@ -4732,8 +4754,9 @@ fn genIntMulDivOpMir(self: *Self, tag: Mir.Inst.FixedTag, ty: Type, lhs: MCValue
47324754/// Always returns a register.
47334755/// Clobbers .rax and .rdx registers.
47344756fn genInlineIntDivFloor(self: *Self, ty: Type, lhs: MCValue, rhs: MCValue) !MCValue {
4735 const mod = self.bin_file.comp.module.?;
4736 const abi_size: u32 = @intCast(ty.abiSize(mod));
4757 const pt = self.pt;
4758 const mod = pt.zcu;
4759 const abi_size: u32 = @intCast(ty.abiSize(pt));
47374760 const int_info = ty.intInfo(mod);
47384761 const dividend = switch (lhs) {
47394762 .register => |reg| reg,
......@@ -4784,7 +4807,8 @@ fn genInlineIntDivFloor(self: *Self, ty: Type, lhs: MCValue, rhs: MCValue) !MCVa
47844807}
47854808
47864809fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
4787 const mod = self.bin_file.comp.module.?;
4810 const pt = self.pt;
4811 const mod = pt.zcu;
47884812 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
47894813
47904814 const air_tags = self.air.instructions.items(.tag);
......@@ -4811,7 +4835,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
48114835 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
48124836 defer self.register_manager.unlockReg(tmp_lock);
48134837
4814 const lhs_bits: u31 = @intCast(lhs_ty.bitSize(mod));
4838 const lhs_bits: u31 = @intCast(lhs_ty.bitSize(pt));
48154839 const tmp_ty = if (lhs_bits > 64) Type.usize else lhs_ty;
48164840 const off = frame_addr.off + (lhs_bits - 1) / 64 * 8;
48174841 try self.genSetReg(
......@@ -4922,11 +4946,11 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49224946 .shl, .shl_exact => if (self.hasFeature(.avx2)) .{ .vp_q, .sll } else null,
49234947 },
49244948 },
4925 })) |mir_tag| if (try self.air.value(bin_op.rhs, mod)) |rhs_val| {
4949 })) |mir_tag| if (try self.air.value(bin_op.rhs, pt)) |rhs_val| {
49264950 switch (mod.intern_pool.indexToKey(rhs_val.toIntern())) {
49274951 .aggregate => |rhs_aggregate| switch (rhs_aggregate.storage) {
49284952 .repeated_elem => |rhs_elem| {
4929 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
4953 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
49304954
49314955 const lhs_mcv = try self.resolveInst(bin_op.lhs);
49324956 const dst_reg, const lhs_reg = if (lhs_mcv.isRegister() and
......@@ -4946,7 +4970,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49464970 self.register_manager.unlockReg(lock);
49474971
49484972 const shift_imm =
4949 Immediate.u(@intCast(Value.fromInterned(rhs_elem).toUnsignedInt(mod)));
4973 Immediate.u(@intCast(Value.fromInterned(rhs_elem).toUnsignedInt(pt)));
49504974 if (self.hasFeature(.avx)) try self.asmRegisterRegisterImmediate(
49514975 mir_tag,
49524976 registerAlias(dst_reg, abi_size),
......@@ -4968,7 +4992,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49684992 }
49694993 } else if (bin_op.rhs.toIndex()) |rhs_inst| switch (air_tags[@intFromEnum(rhs_inst)]) {
49704994 .splat => {
4971 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
4995 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
49724996
49734997 const lhs_mcv = try self.resolveInst(bin_op.lhs);
49744998 const dst_reg, const lhs_reg = if (lhs_mcv.isRegister() and
......@@ -4991,13 +5015,13 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49915015 const shift_lock = self.register_manager.lockRegAssumeUnused(shift_reg);
49925016 defer self.register_manager.unlockReg(shift_lock);
49935017
4994 const mask_ty = try mod.vectorType(.{ .len = 16, .child = .u8_type });
4995 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
5018 const mask_ty = try pt.vectorType(.{ .len = 16, .child = .u8_type });
5019 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
49965020 .ty = mask_ty.toIntern(),
49975021 .storage = .{ .elems = &([1]InternPool.Index{
4998 (try rhs_ty.childType(mod).maxIntScalar(mod, Type.u8)).toIntern(),
5022 (try rhs_ty.childType(mod).maxIntScalar(pt, Type.u8)).toIntern(),
49995023 } ++ [1]InternPool.Index{
5000 (try mod.intValue(Type.u8, 0)).toIntern(),
5024 (try pt.intValue(Type.u8, 0)).toIntern(),
50015025 } ** 15) },
50025026 } })));
50035027 const mask_addr_reg =
......@@ -5045,7 +5069,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
50455069 },
50465070 else => {},
50475071 }
5048 return self.fail("TODO implement airShlShrBinOp for {}", .{lhs_ty.fmt(mod)});
5072 return self.fail("TODO implement airShlShrBinOp for {}", .{lhs_ty.fmt(pt)});
50495073 };
50505074 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
50515075}
......@@ -5058,11 +5082,11 @@ fn airShlSat(self: *Self, inst: Air.Inst.Index) !void {
50585082}
50595083
50605084fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
5061 const mod = self.bin_file.comp.module.?;
5085 const pt = self.pt;
50625086 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50635087 const result: MCValue = result: {
50645088 const pl_ty = self.typeOfIndex(inst);
5065 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5089 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
50665090
50675091 const opt_mcv = try self.resolveInst(ty_op.operand);
50685092 if (self.reuseOperand(inst, ty_op.operand, 0, opt_mcv)) {
......@@ -5104,7 +5128,8 @@ fn airOptionalPayloadPtr(self: *Self, inst: Air.Inst.Index) !void {
51045128}
51055129
51065130fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
5107 const mod = self.bin_file.comp.module.?;
5131 const pt = self.pt;
5132 const mod = pt.zcu;
51085133 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51095134 const result = result: {
51105135 const dst_ty = self.typeOfIndex(inst);
......@@ -5130,7 +5155,7 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
51305155 try self.copyToRegisterWithInstTracking(inst, dst_ty, src_mcv);
51315156
51325157 const pl_ty = dst_ty.childType(mod);
5133 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(mod));
5158 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
51345159 try self.genSetMem(
51355160 .{ .reg = dst_mcv.getReg().? },
51365161 pl_abi_size,
......@@ -5144,7 +5169,8 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
51445169}
51455170
51465171fn airUnwrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
5147 const mod = self.bin_file.comp.module.?;
5172 const pt = self.pt;
5173 const mod = pt.zcu;
51485174 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51495175 const err_union_ty = self.typeOf(ty_op.operand);
51505176 const err_ty = err_union_ty.errorUnionSet(mod);
......@@ -5156,11 +5182,11 @@ fn airUnwrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
51565182 break :result MCValue{ .immediate = 0 };
51575183 }
51585184
5159 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5185 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
51605186 break :result operand;
51615187 }
51625188
5163 const err_off = errUnionErrorOffset(payload_ty, mod);
5189 const err_off = errUnionErrorOffset(payload_ty, pt);
51645190 switch (operand) {
51655191 .register => |reg| {
51665192 // TODO reuse operand
......@@ -5197,7 +5223,8 @@ fn airUnwrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
51975223
51985224// *(E!T) -> E
51995225fn airUnwrapErrUnionErrPtr(self: *Self, inst: Air.Inst.Index) !void {
5200 const mod = self.bin_file.comp.module.?;
5226 const pt = self.pt;
5227 const mod = pt.zcu;
52015228 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
52025229
52035230 const src_ty = self.typeOf(ty_op.operand);
......@@ -5217,8 +5244,8 @@ fn airUnwrapErrUnionErrPtr(self: *Self, inst: Air.Inst.Index) !void {
52175244 const eu_ty = src_ty.childType(mod);
52185245 const pl_ty = eu_ty.errorUnionPayload(mod);
52195246 const err_ty = eu_ty.errorUnionSet(mod);
5220 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5221 const err_abi_size: u32 = @intCast(err_ty.abiSize(mod));
5247 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
5248 const err_abi_size: u32 = @intCast(err_ty.abiSize(pt));
52225249 try self.asmRegisterMemory(
52235250 .{ ._, .mov },
52245251 registerAlias(dst_reg, err_abi_size),
......@@ -5244,7 +5271,8 @@ fn airUnwrapErrUnionPayloadPtr(self: *Self, inst: Air.Inst.Index) !void {
52445271}
52455272
52465273fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
5247 const mod = self.bin_file.comp.module.?;
5274 const pt = self.pt;
5275 const mod = pt.zcu;
52485276 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
52495277 const result: MCValue = result: {
52505278 const src_ty = self.typeOf(ty_op.operand);
......@@ -5259,8 +5287,8 @@ fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
52595287 const eu_ty = src_ty.childType(mod);
52605288 const pl_ty = eu_ty.errorUnionPayload(mod);
52615289 const err_ty = eu_ty.errorUnionSet(mod);
5262 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5263 const err_abi_size: u32 = @intCast(err_ty.abiSize(mod));
5290 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
5291 const err_abi_size: u32 = @intCast(err_ty.abiSize(pt));
52645292 try self.asmMemoryImmediate(
52655293 .{ ._, .mov },
52665294 .{
......@@ -5283,8 +5311,8 @@ fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
52835311 const dst_lock = self.register_manager.lockReg(dst_reg);
52845312 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
52855313
5286 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5287 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
5314 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5315 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
52885316 try self.asmRegisterMemory(
52895317 .{ ._, .lea },
52905318 registerAlias(dst_reg, dst_abi_size),
......@@ -5304,13 +5332,14 @@ fn genUnwrapErrUnionPayloadMir(
53045332 err_union_ty: Type,
53055333 err_union: MCValue,
53065334) !MCValue {
5307 const mod = self.bin_file.comp.module.?;
5335 const pt = self.pt;
5336 const mod = pt.zcu;
53085337 const payload_ty = err_union_ty.errorUnionPayload(mod);
53095338
53105339 const result: MCValue = result: {
5311 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5340 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
53125341
5313 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, mod));
5342 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, pt));
53145343 switch (err_union) {
53155344 .load_frame => |frame_addr| break :result .{ .load_frame = .{
53165345 .index = frame_addr.index,
......@@ -5353,12 +5382,13 @@ fn genUnwrapErrUnionPayloadPtrMir(
53535382 ptr_ty: Type,
53545383 ptr_mcv: MCValue,
53555384) !MCValue {
5356 const mod = self.bin_file.comp.module.?;
5385 const pt = self.pt;
5386 const mod = pt.zcu;
53575387 const err_union_ty = ptr_ty.childType(mod);
53585388 const payload_ty = err_union_ty.errorUnionPayload(mod);
53595389
53605390 const result: MCValue = result: {
5361 const payload_off = errUnionPayloadOffset(payload_ty, mod);
5391 const payload_off = errUnionPayloadOffset(payload_ty, pt);
53625392 const result_mcv: MCValue = if (maybe_inst) |inst|
53635393 try self.copyToRegisterWithInstTracking(inst, ptr_ty, ptr_mcv)
53645394 else
......@@ -5387,11 +5417,12 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
53875417}
53885418
53895419fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
5390 const mod = self.bin_file.comp.module.?;
5420 const pt = self.pt;
5421 const mod = pt.zcu;
53915422 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53925423 const result: MCValue = result: {
53935424 const pl_ty = self.typeOf(ty_op.operand);
5394 if (!pl_ty.hasRuntimeBits(mod)) break :result .{ .immediate = 1 };
5425 if (!pl_ty.hasRuntimeBits(pt)) break :result .{ .immediate = 1 };
53955426
53965427 const opt_ty = self.typeOfIndex(inst);
53975428 const pl_mcv = try self.resolveInst(ty_op.operand);
......@@ -5408,7 +5439,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
54085439 try self.genCopy(pl_ty, opt_mcv, pl_mcv, .{});
54095440
54105441 if (!same_repr) {
5411 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(mod));
5442 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
54125443 switch (opt_mcv) {
54135444 else => unreachable,
54145445
......@@ -5441,7 +5472,8 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
54415472
54425473/// T to E!T
54435474fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
5444 const mod = self.bin_file.comp.module.?;
5475 const pt = self.pt;
5476 const mod = pt.zcu;
54455477 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54465478
54475479 const eu_ty = ty_op.ty.toType();
......@@ -5450,11 +5482,11 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
54505482 const operand = try self.resolveInst(ty_op.operand);
54515483
54525484 const result: MCValue = result: {
5453 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .{ .immediate = 0 };
5485 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .{ .immediate = 0 };
54545486
5455 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, mod));
5456 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5457 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5487 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
5488 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5489 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
54585490 try self.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, operand, .{});
54595491 try self.genSetMem(.{ .frame = frame_index }, err_off, err_ty, .{ .immediate = 0 }, .{});
54605492 break :result .{ .load_frame = .{ .index = frame_index } };
......@@ -5464,7 +5496,8 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
54645496
54655497/// E to E!T
54665498fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
5467 const mod = self.bin_file.comp.module.?;
5499 const pt = self.pt;
5500 const mod = pt.zcu;
54685501 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54695502
54705503 const eu_ty = ty_op.ty.toType();
......@@ -5472,11 +5505,11 @@ fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
54725505 const err_ty = eu_ty.errorUnionSet(mod);
54735506
54745507 const result: MCValue = result: {
5475 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result try self.resolveInst(ty_op.operand);
5508 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result try self.resolveInst(ty_op.operand);
54765509
5477 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, mod));
5478 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5479 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5510 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
5511 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5512 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
54805513 try self.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, .undef, .{});
54815514 const operand = try self.resolveInst(ty_op.operand);
54825515 try self.genSetMem(.{ .frame = frame_index }, err_off, err_ty, operand, .{});
......@@ -5523,7 +5556,7 @@ fn airSliceLen(self: *Self, inst: Air.Inst.Index) !void {
55235556}
55245557
55255558fn airPtrSliceLenPtr(self: *Self, inst: Air.Inst.Index) !void {
5526 const mod = self.bin_file.comp.module.?;
5559 const pt = self.pt;
55275560 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
55285561
55295562 const src_ty = self.typeOf(ty_op.operand);
......@@ -5544,7 +5577,7 @@ fn airPtrSliceLenPtr(self: *Self, inst: Air.Inst.Index) !void {
55445577 const dst_lock = self.register_manager.lockReg(dst_reg);
55455578 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
55465579
5547 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
5580 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
55485581 try self.asmRegisterMemory(
55495582 .{ ._, .lea },
55505583 registerAlias(dst_reg, dst_abi_size),
......@@ -5591,7 +5624,8 @@ fn elemOffset(self: *Self, index_ty: Type, index: MCValue, elem_size: u64) !Regi
55915624}
55925625
55935626fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
5594 const mod = self.bin_file.comp.module.?;
5627 const pt = self.pt;
5628 const mod = pt.zcu;
55955629 const slice_ty = self.typeOf(lhs);
55965630 const slice_mcv = try self.resolveInst(lhs);
55975631 const slice_mcv_lock: ?RegisterLock = switch (slice_mcv) {
......@@ -5601,7 +5635,7 @@ fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
56015635 defer if (slice_mcv_lock) |lock| self.register_manager.unlockReg(lock);
56025636
56035637 const elem_ty = slice_ty.childType(mod);
5604 const elem_size = elem_ty.abiSize(mod);
5638 const elem_size = elem_ty.abiSize(pt);
56055639 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
56065640
56075641 const index_ty = self.typeOf(rhs);
......@@ -5627,12 +5661,13 @@ fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
56275661}
56285662
56295663fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
5630 const mod = self.bin_file.comp.module.?;
5664 const pt = self.pt;
5665 const mod = pt.zcu;
56315666 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
56325667
56335668 const result: MCValue = result: {
56345669 const elem_ty = self.typeOfIndex(inst);
5635 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5670 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
56365671
56375672 const slice_ty = self.typeOf(bin_op.lhs);
56385673 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
......@@ -5652,7 +5687,8 @@ fn airSliceElemPtr(self: *Self, inst: Air.Inst.Index) !void {
56525687}
56535688
56545689fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
5655 const mod = self.bin_file.comp.module.?;
5690 const pt = self.pt;
5691 const mod = pt.zcu;
56565692 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
56575693
56585694 const result: MCValue = result: {
......@@ -5675,7 +5711,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
56755711 defer if (index_lock) |lock| self.register_manager.unlockReg(lock);
56765712
56775713 try self.spillEflagsIfOccupied();
5678 if (array_ty.isVector(mod) and elem_ty.bitSize(mod) == 1) {
5714 if (array_ty.isVector(mod) and elem_ty.bitSize(pt) == 1) {
56795715 const index_reg = switch (index_mcv) {
56805716 .register => |reg| reg,
56815717 else => try self.copyToTmpRegister(index_ty, index_mcv),
......@@ -5688,7 +5724,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
56885724 index_reg.to64(),
56895725 ),
56905726 .sse => {
5691 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, mod));
5727 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
56925728 try self.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv, .{});
56935729 try self.asmMemoryRegister(
56945730 .{ ._, .bt },
......@@ -5717,7 +5753,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57175753 index_reg.to64(),
57185754 ),
57195755 else => return self.fail("TODO airArrayElemVal for {s} of {}", .{
5720 @tagName(array_mcv), array_ty.fmt(mod),
5756 @tagName(array_mcv), array_ty.fmt(pt),
57215757 }),
57225758 }
57235759
......@@ -5726,14 +5762,14 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57265762 break :result .{ .register = dst_reg };
57275763 }
57285764
5729 const elem_abi_size = elem_ty.abiSize(mod);
5765 const elem_abi_size = elem_ty.abiSize(pt);
57305766 const addr_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
57315767 const addr_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
57325768 defer self.register_manager.unlockReg(addr_lock);
57335769
57345770 switch (array_mcv) {
57355771 .register => {
5736 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, mod));
5772 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
57375773 try self.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv, .{});
57385774 try self.asmRegisterMemory(
57395775 .{ ._, .lea },
......@@ -5757,7 +5793,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57575793 => try self.genSetReg(addr_reg, Type.usize, array_mcv.address(), .{}),
57585794 .lea_symbol, .lea_direct, .lea_tlv => unreachable,
57595795 else => return self.fail("TODO airArrayElemVal_val for {s} of {}", .{
5760 @tagName(array_mcv), array_ty.fmt(mod),
5796 @tagName(array_mcv), array_ty.fmt(pt),
57615797 }),
57625798 }
57635799
......@@ -5781,7 +5817,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57815817}
57825818
57835819fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
5784 const mod = self.bin_file.comp.module.?;
5820 const pt = self.pt;
5821 const mod = pt.zcu;
57855822 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57865823 const ptr_ty = self.typeOf(bin_op.lhs);
57875824
......@@ -5790,9 +5827,9 @@ fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
57905827
57915828 const result = result: {
57925829 const elem_ty = ptr_ty.elemType2(mod);
5793 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5830 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
57945831
5795 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
5832 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
57965833 const index_ty = self.typeOf(bin_op.rhs);
57975834 const index_mcv = try self.resolveInst(bin_op.rhs);
57985835 const index_lock = switch (index_mcv) {
......@@ -5831,7 +5868,8 @@ fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
58315868}
58325869
58335870fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
5834 const mod = self.bin_file.comp.module.?;
5871 const pt = self.pt;
5872 const mod = pt.zcu;
58355873 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
58365874 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
58375875
......@@ -5854,7 +5892,7 @@ fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
58545892 }
58555893
58565894 const elem_ty = base_ptr_ty.elemType2(mod);
5857 const elem_abi_size = elem_ty.abiSize(mod);
5895 const elem_abi_size = elem_ty.abiSize(pt);
58585896 const index_ty = self.typeOf(extra.rhs);
58595897 const index_mcv = try self.resolveInst(extra.rhs);
58605898 const index_lock: ?RegisterLock = switch (index_mcv) {
......@@ -5876,12 +5914,13 @@ fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
58765914}
58775915
58785916fn airSetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
5879 const mod = self.bin_file.comp.module.?;
5917 const pt = self.pt;
5918 const mod = pt.zcu;
58805919 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
58815920 const ptr_union_ty = self.typeOf(bin_op.lhs);
58825921 const union_ty = ptr_union_ty.childType(mod);
58835922 const tag_ty = self.typeOf(bin_op.rhs);
5884 const layout = union_ty.unionGetLayout(mod);
5923 const layout = union_ty.unionGetLayout(pt);
58855924
58865925 if (layout.tag_size == 0) {
58875926 return self.finishAir(inst, .none, .{ bin_op.lhs, bin_op.rhs, .none });
......@@ -5913,19 +5952,19 @@ fn airSetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59135952 break :blk MCValue{ .register = reg };
59145953 } else ptr;
59155954
5916 const ptr_tag_ty = try mod.adjustPtrTypeChild(ptr_union_ty, tag_ty);
5955 const ptr_tag_ty = try pt.adjustPtrTypeChild(ptr_union_ty, tag_ty);
59175956 try self.store(ptr_tag_ty, adjusted_ptr, tag, .{});
59185957
59195958 return self.finishAir(inst, .none, .{ bin_op.lhs, bin_op.rhs, .none });
59205959}
59215960
59225961fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
5923 const mod = self.bin_file.comp.module.?;
5962 const pt = self.pt;
59245963 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59255964
59265965 const tag_ty = self.typeOfIndex(inst);
59275966 const union_ty = self.typeOf(ty_op.operand);
5928 const layout = union_ty.unionGetLayout(mod);
5967 const layout = union_ty.unionGetLayout(pt);
59295968
59305969 if (layout.tag_size == 0) {
59315970 return self.finishAir(inst, .none, .{ ty_op.operand, .none, .none });
......@@ -5939,7 +5978,7 @@ fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59395978 };
59405979 defer if (operand_lock) |lock| self.register_manager.unlockReg(lock);
59415980
5942 const tag_abi_size = tag_ty.abiSize(mod);
5981 const tag_abi_size = tag_ty.abiSize(pt);
59435982 const dst_mcv: MCValue = blk: {
59445983 switch (operand) {
59455984 .load_frame => |frame_addr| {
......@@ -5983,7 +6022,8 @@ fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59836022}
59846023
59856024fn airClz(self: *Self, inst: Air.Inst.Index) !void {
5986 const mod = self.bin_file.comp.module.?;
6025 const pt = self.pt;
6026 const mod = pt.zcu;
59876027 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59886028 const result = result: {
59896029 try self.spillEflagsIfOccupied();
......@@ -5991,7 +6031,7 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
59916031 const dst_ty = self.typeOfIndex(inst);
59926032 const src_ty = self.typeOf(ty_op.operand);
59936033 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement airClz for {}", .{
5994 src_ty.fmt(mod),
6034 src_ty.fmt(pt),
59956035 });
59966036
59976037 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -6010,8 +6050,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
60106050 const dst_lock = self.register_manager.lockRegAssumeUnused(dst_reg);
60116051 defer self.register_manager.unlockReg(dst_lock);
60126052
6013 const abi_size: u31 = @intCast(src_ty.abiSize(mod));
6014 const src_bits: u31 = @intCast(src_ty.bitSize(mod));
6053 const abi_size: u31 = @intCast(src_ty.abiSize(pt));
6054 const src_bits: u31 = @intCast(src_ty.bitSize(pt));
60156055 const has_lzcnt = self.hasFeature(.lzcnt);
60166056 if (src_bits > @as(u32, if (has_lzcnt) 128 else 64)) {
60176057 const limbs_len = math.divCeil(u32, abi_size, 8) catch unreachable;
......@@ -6121,7 +6161,7 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
61216161 }
61226162
61236163 assert(src_bits <= 64);
6124 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(mod))), 2);
6164 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(pt))), 2);
61256165 if (math.isPowerOfTwo(src_bits)) {
61266166 const imm_reg = try self.copyToTmpRegister(dst_ty, .{
61276167 .immediate = src_bits ^ (src_bits - 1),
......@@ -6179,7 +6219,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
61796219}
61806220
61816221fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
6182 const mod = self.bin_file.comp.module.?;
6222 const pt = self.pt;
6223 const mod = pt.zcu;
61836224 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61846225 const result = result: {
61856226 try self.spillEflagsIfOccupied();
......@@ -6187,7 +6228,7 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
61876228 const dst_ty = self.typeOfIndex(inst);
61886229 const src_ty = self.typeOf(ty_op.operand);
61896230 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement airCtz for {}", .{
6190 src_ty.fmt(mod),
6231 src_ty.fmt(pt),
61916232 });
61926233
61936234 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -6206,8 +6247,8 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
62066247 const dst_lock = self.register_manager.lockReg(dst_reg);
62076248 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
62086249
6209 const abi_size: u31 = @intCast(src_ty.abiSize(mod));
6210 const src_bits: u31 = @intCast(src_ty.bitSize(mod));
6250 const abi_size: u31 = @intCast(src_ty.abiSize(pt));
6251 const src_bits: u31 = @intCast(src_ty.bitSize(pt));
62116252 const has_bmi = self.hasFeature(.bmi);
62126253 if (src_bits > @as(u32, if (has_bmi) 128 else 64)) {
62136254 const limbs_len = math.divCeil(u32, abi_size, 8) catch unreachable;
......@@ -6328,7 +6369,7 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
63286369 try self.genBinOpMir(.{ ._, .bsf }, wide_ty, dst_mcv, .{ .register = wide_reg });
63296370 } else try self.genBinOpMir(.{ ._, .bsf }, src_ty, dst_mcv, mat_src_mcv);
63306371
6331 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(mod))), 2);
6372 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(pt))), 2);
63326373 try self.asmCmovccRegisterRegister(
63336374 .z,
63346375 registerAlias(dst_reg, cmov_abi_size),
......@@ -6340,15 +6381,16 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
63406381}
63416382
63426383fn airPopCount(self: *Self, inst: Air.Inst.Index) !void {
6343 const mod = self.bin_file.comp.module.?;
6384 const pt = self.pt;
6385 const mod = pt.zcu;
63446386 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
63456387 const result: MCValue = result: {
63466388 try self.spillEflagsIfOccupied();
63476389
63486390 const src_ty = self.typeOf(ty_op.operand);
6349 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
6391 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
63506392 if (src_ty.zigTypeTag(mod) == .Vector or src_abi_size > 16)
6351 return self.fail("TODO implement airPopCount for {}", .{src_ty.fmt(mod)});
6393 return self.fail("TODO implement airPopCount for {}", .{src_ty.fmt(pt)});
63526394 const src_mcv = try self.resolveInst(ty_op.operand);
63536395
63546396 const mat_src_mcv = switch (src_mcv) {
......@@ -6385,7 +6427,7 @@ fn airPopCount(self: *Self, inst: Air.Inst.Index) !void {
63856427 else
63866428 .{ .register = mat_src_mcv.register_pair[0] }, false);
63876429 const src_info = src_ty.intInfo(mod);
6388 const hi_ty = try mod.intType(src_info.signedness, (src_info.bits - 1) % 64 + 1);
6430 const hi_ty = try pt.intType(src_info.signedness, (src_info.bits - 1) % 64 + 1);
63896431 try self.genPopCount(tmp_regs[1], hi_ty, if (mat_src_mcv.isMemory())
63906432 mat_src_mcv.address().offset(8).deref()
63916433 else
......@@ -6403,16 +6445,16 @@ fn genPopCount(
64036445 src_mcv: MCValue,
64046446 dst_contains_src: bool,
64056447) !void {
6406 const mod = self.bin_file.comp.module.?;
6448 const pt = self.pt;
64076449
6408 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
6450 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
64096451 if (self.hasFeature(.popcnt)) return self.genBinOpMir(
64106452 .{ ._, .popcnt },
64116453 if (src_abi_size > 1) src_ty else Type.u32,
64126454 .{ .register = dst_reg },
64136455 if (src_abi_size > 1) src_mcv else src: {
64146456 if (!dst_contains_src) try self.genSetReg(dst_reg, src_ty, src_mcv, .{});
6415 try self.truncateRegister(try src_ty.toUnsigned(mod), dst_reg);
6457 try self.truncateRegister(try src_ty.toUnsigned(pt), dst_reg);
64166458 break :src .{ .register = dst_reg };
64176459 },
64186460 );
......@@ -6495,13 +6537,14 @@ fn genByteSwap(
64956537 src_mcv: MCValue,
64966538 mem_ok: bool,
64976539) !MCValue {
6498 const mod = self.bin_file.comp.module.?;
6540 const pt = self.pt;
6541 const mod = pt.zcu;
64996542 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
65006543 const has_movbe = self.hasFeature(.movbe);
65016544
65026545 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail(
65036546 "TODO implement genByteSwap for {}",
6504 .{src_ty.fmt(mod)},
6547 .{src_ty.fmt(pt)},
65056548 );
65066549
65076550 const src_lock = switch (src_mcv) {
......@@ -6510,7 +6553,7 @@ fn genByteSwap(
65106553 };
65116554 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
65126555
6513 const abi_size: u32 = @intCast(src_ty.abiSize(mod));
6556 const abi_size: u32 = @intCast(src_ty.abiSize(pt));
65146557 switch (abi_size) {
65156558 0 => unreachable,
65166559 1 => return if ((mem_ok or src_mcv.isRegister()) and
......@@ -6658,11 +6701,12 @@ fn genByteSwap(
66586701}
66596702
66606703fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
6661 const mod = self.bin_file.comp.module.?;
6704 const pt = self.pt;
6705 const mod = pt.zcu;
66626706 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66636707
66646708 const src_ty = self.typeOf(ty_op.operand);
6665 const src_bits: u32 = @intCast(src_ty.bitSize(mod));
6709 const src_bits: u32 = @intCast(src_ty.bitSize(pt));
66666710 const src_mcv = try self.resolveInst(ty_op.operand);
66676711
66686712 const dst_mcv = try self.genByteSwap(inst, src_ty, src_mcv, true);
......@@ -6674,18 +6718,19 @@ fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
66746718 src_ty,
66756719 dst_mcv,
66766720 if (src_bits > 256) Type.u16 else Type.u8,
6677 .{ .immediate = src_ty.abiSize(mod) * 8 - src_bits },
6721 .{ .immediate = src_ty.abiSize(pt) * 8 - src_bits },
66786722 );
66796723 return self.finishAir(inst, dst_mcv, .{ ty_op.operand, .none, .none });
66806724}
66816725
66826726fn airBitReverse(self: *Self, inst: Air.Inst.Index) !void {
6683 const mod = self.bin_file.comp.module.?;
6727 const pt = self.pt;
6728 const mod = pt.zcu;
66846729 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66856730
66866731 const src_ty = self.typeOf(ty_op.operand);
6687 const abi_size: u32 = @intCast(src_ty.abiSize(mod));
6688 const bit_size: u32 = @intCast(src_ty.bitSize(mod));
6732 const abi_size: u32 = @intCast(src_ty.abiSize(pt));
6733 const bit_size: u32 = @intCast(src_ty.bitSize(pt));
66896734 const src_mcv = try self.resolveInst(ty_op.operand);
66906735
66916736 const dst_mcv = try self.genByteSwap(inst, src_ty, src_mcv, false);
......@@ -6802,14 +6847,15 @@ fn airBitReverse(self: *Self, inst: Air.Inst.Index) !void {
68026847}
68036848
68046849fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type) !void {
6805 const mod = self.bin_file.comp.module.?;
6850 const pt = self.pt;
6851 const mod = pt.zcu;
68066852 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
68076853
68086854 const result = result: {
68096855 const scalar_bits = ty.scalarType(mod).floatBits(self.target.*);
68106856 if (scalar_bits == 80) {
68116857 if (ty.zigTypeTag(mod) != .Float) return self.fail("TODO implement floatSign for {}", .{
6812 ty.fmt(mod),
6858 ty.fmt(pt),
68136859 });
68146860
68156861 const src_mcv = try self.resolveInst(operand);
......@@ -6829,11 +6875,11 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68296875 break :result dst_mcv;
68306876 }
68316877
6832 const abi_size: u32 = switch (ty.abiSize(mod)) {
6878 const abi_size: u32 = switch (ty.abiSize(pt)) {
68336879 1...16 => 16,
68346880 17...32 => 32,
68356881 else => return self.fail("TODO implement floatSign for {}", .{
6836 ty.fmt(mod),
6882 ty.fmt(pt),
68376883 }),
68386884 };
68396885
......@@ -6852,14 +6898,14 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68526898 const dst_lock = self.register_manager.lockReg(dst_reg);
68536899 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
68546900
6855 const vec_ty = try mod.vectorType(.{
6901 const vec_ty = try pt.vectorType(.{
68566902 .len = @divExact(abi_size * 8, scalar_bits),
6857 .child = (try mod.intType(.signed, scalar_bits)).ip_index,
6903 .child = (try pt.intType(.signed, scalar_bits)).ip_index,
68586904 });
68596905
68606906 const sign_mcv = try self.genTypedValue(switch (tag) {
6861 .neg => try vec_ty.minInt(mod, vec_ty),
6862 .abs => try vec_ty.maxInt(mod, vec_ty),
6907 .neg => try vec_ty.minInt(pt, vec_ty),
6908 .abs => try vec_ty.maxInt(pt, vec_ty),
68636909 else => unreachable,
68646910 });
68656911 const sign_mem: Memory = if (sign_mcv.isMemory())
......@@ -6891,7 +6937,7 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68916937 .abs => .{ .v_pd, .@"and" },
68926938 else => unreachable,
68936939 },
6894 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(mod)}),
6940 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(pt)}),
68956941 else => unreachable,
68966942 },
68976943 registerAlias(dst_reg, abi_size),
......@@ -6917,7 +6963,7 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
69176963 .abs => .{ ._pd, .@"and" },
69186964 else => unreachable,
69196965 },
6920 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(mod)}),
6966 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(pt)}),
69216967 else => unreachable,
69226968 },
69236969 registerAlias(dst_reg, abi_size),
......@@ -6978,7 +7024,8 @@ fn airRound(self: *Self, inst: Air.Inst.Index, mode: RoundMode) !void {
69787024}
69797025
69807026fn getRoundTag(self: *Self, ty: Type) ?Mir.Inst.FixedTag {
6981 const mod = self.bin_file.comp.module.?;
7027 const pt = self.pt;
7028 const mod = pt.zcu;
69827029 return if (self.hasFeature(.sse4_1)) switch (ty.zigTypeTag(mod)) {
69837030 .Float => switch (ty.floatBits(self.target.*)) {
69847031 32 => if (self.hasFeature(.avx)) .{ .v_ss, .round } else .{ ._ss, .round },
......@@ -7010,11 +7057,12 @@ fn getRoundTag(self: *Self, ty: Type) ?Mir.Inst.FixedTag {
70107057}
70117058
70127059fn genRoundLibcall(self: *Self, ty: Type, src_mcv: MCValue, mode: RoundMode) !MCValue {
7013 const mod = self.bin_file.comp.module.?;
7060 const pt = self.pt;
7061 const mod = pt.zcu;
70147062 if (self.getRoundTag(ty)) |_| return .none;
70157063
70167064 if (ty.zigTypeTag(mod) != .Float)
7017 return self.fail("TODO implement genRound for {}", .{ty.fmt(mod)});
7065 return self.fail("TODO implement genRound for {}", .{ty.fmt(pt)});
70187066
70197067 var callee_buf: ["__trunc?".len]u8 = undefined;
70207068 return try self.genCall(.{ .lib = .{
......@@ -7034,12 +7082,12 @@ fn genRoundLibcall(self: *Self, ty: Type, src_mcv: MCValue, mode: RoundMode) !MC
70347082}
70357083
70367084fn genRound(self: *Self, ty: Type, dst_reg: Register, src_mcv: MCValue, mode: RoundMode) !void {
7037 const mod = self.bin_file.comp.module.?;
7085 const pt = self.pt;
70387086 const mir_tag = self.getRoundTag(ty) orelse {
70397087 const result = try self.genRoundLibcall(ty, src_mcv, mode);
70407088 return self.genSetReg(dst_reg, ty, result, .{});
70417089 };
7042 const abi_size: u32 = @intCast(ty.abiSize(mod));
7090 const abi_size: u32 = @intCast(ty.abiSize(pt));
70437091 const dst_alias = registerAlias(dst_reg, abi_size);
70447092 switch (mir_tag[0]) {
70457093 .v_ss, .v_sd => if (src_mcv.isMemory()) try self.asmRegisterRegisterMemoryImmediate(
......@@ -7076,14 +7124,15 @@ fn genRound(self: *Self, ty: Type, dst_reg: Register, src_mcv: MCValue, mode: Ro
70767124}
70777125
70787126fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
7079 const mod = self.bin_file.comp.module.?;
7127 const pt = self.pt;
7128 const mod = pt.zcu;
70807129 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
70817130 const ty = self.typeOf(ty_op.operand);
70827131
70837132 const result: MCValue = result: {
70847133 const mir_tag = @as(?Mir.Inst.FixedTag, switch (ty.zigTypeTag(mod)) {
70857134 else => null,
7086 .Int => switch (ty.abiSize(mod)) {
7135 .Int => switch (ty.abiSize(pt)) {
70877136 0 => unreachable,
70887137 1...8 => {
70897138 try self.spillEflagsIfOccupied();
......@@ -7092,7 +7141,7 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
70927141
70937142 try self.genUnOpMir(.{ ._, .neg }, ty, dst_mcv);
70947143
7095 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
7144 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
70967145 switch (src_mcv) {
70977146 .register => |val_reg| try self.asmCmovccRegisterRegister(
70987147 .l,
......@@ -7151,7 +7200,7 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
71517200 break :result dst_mcv;
71527201 },
71537202 else => {
7154 const abi_size: u31 = @intCast(ty.abiSize(mod));
7203 const abi_size: u31 = @intCast(ty.abiSize(pt));
71557204 const limb_len = math.divCeil(u31, abi_size, 8) catch unreachable;
71567205
71577206 const tmp_regs =
......@@ -7249,9 +7298,9 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
72497298 },
72507299 .Float => return self.floatSign(inst, ty_op.operand, ty),
72517300 },
7252 }) orelse return self.fail("TODO implement airAbs for {}", .{ty.fmt(mod)});
7301 }) orelse return self.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
72537302
7254 const abi_size: u32 = @intCast(ty.abiSize(mod));
7303 const abi_size: u32 = @intCast(ty.abiSize(pt));
72557304 const src_mcv = try self.resolveInst(ty_op.operand);
72567305 const dst_reg = if (src_mcv.isRegister() and self.reuseOperand(inst, ty_op.operand, 0, src_mcv))
72577306 src_mcv.getReg().?
......@@ -7276,10 +7325,11 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
72767325}
72777326
72787327fn airSqrt(self: *Self, inst: Air.Inst.Index) !void {
7279 const mod = self.bin_file.comp.module.?;
7328 const pt = self.pt;
7329 const mod = pt.zcu;
72807330 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72817331 const ty = self.typeOf(un_op);
7282 const abi_size: u32 = @intCast(ty.abiSize(mod));
7332 const abi_size: u32 = @intCast(ty.abiSize(pt));
72837333
72847334 const result: MCValue = result: {
72857335 switch (ty.zigTypeTag(mod)) {
......@@ -7408,7 +7458,7 @@ fn airSqrt(self: *Self, inst: Air.Inst.Index) !void {
74087458 },
74097459 else => unreachable,
74107460 }) orelse return self.fail("TODO implement airSqrt for {}", .{
7411 ty.fmt(mod),
7461 ty.fmt(pt),
74127462 });
74137463 switch (mir_tag[0]) {
74147464 .v_ss, .v_sd => if (src_mcv.isMemory()) try self.asmRegisterRegisterMemory(
......@@ -7521,14 +7571,15 @@ fn reuseOperandAdvanced(
75217571}
75227572
75237573fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerError!void {
7524 const mod = self.bin_file.comp.module.?;
7574 const pt = self.pt;
7575 const mod = pt.zcu;
75257576
75267577 const ptr_info = ptr_ty.ptrInfo(mod);
75277578 const val_ty = Type.fromInterned(ptr_info.child);
7528 if (!val_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7529 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
7579 if (!val_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
7580 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
75307581
7531 const val_bit_size: u32 = @intCast(val_ty.bitSize(mod));
7582 const val_bit_size: u32 = @intCast(val_ty.bitSize(pt));
75327583 const ptr_bit_off = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
75337584 .none => 0,
75347585 .runtime => unreachable,
......@@ -7566,7 +7617,7 @@ fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) Inn
75667617 return;
75677618 }
75687619
7569 if (val_abi_size > 8) return self.fail("TODO implement packed load of {}", .{val_ty.fmt(mod)});
7620 if (val_abi_size > 8) return self.fail("TODO implement packed load of {}", .{val_ty.fmt(pt)});
75707621
75717622 const limb_abi_size: u31 = @min(val_abi_size, 8);
75727623 const limb_abi_bits = limb_abi_size * 8;
......@@ -7633,9 +7684,10 @@ fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) Inn
76337684}
76347685
76357686fn load(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerError!void {
7636 const mod = self.bin_file.comp.module.?;
7687 const pt = self.pt;
7688 const mod = pt.zcu;
76377689 const dst_ty = ptr_ty.childType(mod);
7638 if (!dst_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7690 if (!dst_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
76397691 switch (ptr_mcv) {
76407692 .none,
76417693 .unreach,
......@@ -7675,18 +7727,19 @@ fn load(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerErro
76757727}
76767728
76777729fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
7678 const mod = self.bin_file.comp.module.?;
7730 const pt = self.pt;
7731 const mod = pt.zcu;
76797732 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
76807733 const elem_ty = self.typeOfIndex(inst);
76817734 const result: MCValue = result: {
7682 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
7735 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
76837736
76847737 try self.spillRegisters(&.{ .rdi, .rsi, .rcx });
76857738 const reg_locks = self.register_manager.lockRegsAssumeUnused(3, .{ .rdi, .rsi, .rcx });
76867739 defer for (reg_locks) |lock| self.register_manager.unlockReg(lock);
76877740
76887741 const ptr_ty = self.typeOf(ty_op.operand);
7689 const elem_size = elem_ty.abiSize(mod);
7742 const elem_size = elem_ty.abiSize(pt);
76907743
76917744 const elem_rc = self.regClassForType(elem_ty);
76927745 const ptr_rc = self.regClassForType(ptr_ty);
......@@ -7706,7 +7759,7 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
77067759 try self.load(dst_mcv, ptr_ty, ptr_mcv);
77077760 }
77087761
7709 if (elem_ty.isAbiInt(mod) and elem_size * 8 > elem_ty.bitSize(mod)) {
7762 if (elem_ty.isAbiInt(mod) and elem_size * 8 > elem_ty.bitSize(pt)) {
77107763 const high_mcv: MCValue = switch (dst_mcv) {
77117764 .register => |dst_reg| .{ .register = dst_reg },
77127765 .register_pair => |dst_regs| .{ .register = dst_regs[1] },
......@@ -7733,16 +7786,17 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
77337786}
77347787
77357788fn packedStore(self: *Self, ptr_ty: Type, ptr_mcv: MCValue, src_mcv: MCValue) InnerError!void {
7736 const mod = self.bin_file.comp.module.?;
7789 const pt = self.pt;
7790 const mod = pt.zcu;
77377791 const ptr_info = ptr_ty.ptrInfo(mod);
77387792 const src_ty = Type.fromInterned(ptr_info.child);
7739 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7793 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
77407794
77417795 const limb_abi_size: u16 = @min(ptr_info.packed_offset.host_size, 8);
77427796 const limb_abi_bits = limb_abi_size * 8;
7743 const limb_ty = try mod.intType(.unsigned, limb_abi_bits);
7797 const limb_ty = try pt.intType(.unsigned, limb_abi_bits);
77447798
7745 const src_bit_size = src_ty.bitSize(mod);
7799 const src_bit_size = src_ty.bitSize(pt);
77467800 const ptr_bit_off = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
77477801 .none => 0,
77487802 .runtime => unreachable,
......@@ -7827,7 +7881,7 @@ fn packedStore(self: *Self, ptr_ty: Type, ptr_mcv: MCValue, src_mcv: MCValue) In
78277881 limb_mem,
78287882 registerAlias(tmp_reg, limb_abi_size),
78297883 );
7830 } else return self.fail("TODO: implement packed store of {}", .{src_ty.fmt(mod)});
7884 } else return self.fail("TODO: implement packed store of {}", .{src_ty.fmt(pt)});
78317885 }
78327886}
78337887
......@@ -7838,9 +7892,10 @@ fn store(
78387892 src_mcv: MCValue,
78397893 opts: CopyOptions,
78407894) InnerError!void {
7841 const mod = self.bin_file.comp.module.?;
7895 const pt = self.pt;
7896 const mod = pt.zcu;
78427897 const src_ty = ptr_ty.childType(mod);
7843 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7898 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
78447899 switch (ptr_mcv) {
78457900 .none,
78467901 .unreach,
......@@ -7880,7 +7935,8 @@ fn store(
78807935}
78817936
78827937fn airStore(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
7883 const mod = self.bin_file.comp.module.?;
7938 const pt = self.pt;
7939 const mod = pt.zcu;
78847940 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78857941
78867942 result: {
......@@ -7918,15 +7974,16 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
79187974}
79197975
79207976fn fieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
7921 const mod = self.bin_file.comp.module.?;
7977 const pt = self.pt;
7978 const mod = pt.zcu;
79227979 const ptr_field_ty = self.typeOfIndex(inst);
79237980 const ptr_container_ty = self.typeOf(operand);
79247981 const container_ty = ptr_container_ty.childType(mod);
79257982
79267983 const field_off: i32 = switch (container_ty.containerLayout(mod)) {
7927 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(index, mod)),
7984 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(index, pt)),
79287985 .@"packed" => @divExact(@as(i32, ptr_container_ty.ptrInfo(mod).packed_offset.bit_offset) +
7929 (if (mod.typeToStruct(container_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, index) else 0) -
7986 (if (mod.typeToStruct(container_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, index) else 0) -
79307987 ptr_field_ty.ptrInfo(mod).packed_offset.bit_offset, 8),
79317988 };
79327989
......@@ -7940,7 +7997,8 @@ fn fieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32
79407997}
79417998
79427999fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
7943 const mod = self.bin_file.comp.module.?;
8000 const pt = self.pt;
8001 const mod = pt.zcu;
79448002 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
79458003 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;
79468004 const result: MCValue = result: {
......@@ -7950,14 +8008,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
79508008 const container_ty = self.typeOf(operand);
79518009 const container_rc = self.regClassForType(container_ty);
79528010 const field_ty = container_ty.structFieldType(index, mod);
7953 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
8011 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
79548012 const field_rc = self.regClassForType(field_ty);
79558013 const field_is_gp = field_rc.supersetOf(abi.RegisterClass.gp);
79568014
79578015 const src_mcv = try self.resolveInst(operand);
79588016 const field_off: u32 = switch (container_ty.containerLayout(mod)) {
7959 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(extra.field_index, mod) * 8),
7960 .@"packed" => if (mod.typeToStruct(container_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0,
8017 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(extra.field_index, pt) * 8),
8018 .@"packed" => if (mod.typeToStruct(container_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0,
79618019 };
79628020
79638021 switch (src_mcv) {
......@@ -7988,7 +8046,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
79888046 );
79898047 }
79908048 if (abi.RegisterClass.gp.isSet(RegisterManager.indexOfRegIntoTracked(dst_reg).?) and
7991 container_ty.abiSize(mod) * 8 > field_ty.bitSize(mod))
8049 container_ty.abiSize(pt) * 8 > field_ty.bitSize(pt))
79928050 try self.truncateRegister(field_ty, dst_reg);
79938051
79948052 break :result if (field_off == 0 or field_rc.supersetOf(abi.RegisterClass.gp))
......@@ -8000,7 +8058,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80008058 const src_regs_lock = self.register_manager.lockRegsAssumeUnused(2, src_regs);
80018059 defer for (src_regs_lock) |lock| self.register_manager.unlockReg(lock);
80028060
8003 const field_bit_size: u32 = @intCast(field_ty.bitSize(mod));
8061 const field_bit_size: u32 = @intCast(field_ty.bitSize(pt));
80048062 const src_reg = if (field_off + field_bit_size <= 64)
80058063 src_regs[0]
80068064 else if (field_off >= 64)
......@@ -8044,7 +8102,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80448102 }
80458103
80468104 if (field_bit_size < 128) try self.truncateRegister(
8047 try mod.intType(.unsigned, @intCast(field_bit_size - 64)),
8105 try pt.intType(.unsigned, @intCast(field_bit_size - 64)),
80488106 dst_regs[1],
80498107 );
80508108 break :result if (field_rc.supersetOf(abi.RegisterClass.gp))
......@@ -8099,14 +8157,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80998157 }
81008158 },
81018159 .load_frame => |frame_addr| {
8102 const field_abi_size: u32 = @intCast(field_ty.abiSize(mod));
8160 const field_abi_size: u32 = @intCast(field_ty.abiSize(pt));
81038161 if (field_off % 8 == 0) {
81048162 const field_byte_off = @divExact(field_off, 8);
81058163 const off_mcv = src_mcv.address().offset(@intCast(field_byte_off)).deref();
8106 const field_bit_size = field_ty.bitSize(mod);
8164 const field_bit_size = field_ty.bitSize(pt);
81078165
81088166 if (field_abi_size <= 8) {
8109 const int_ty = try mod.intType(
8167 const int_ty = try pt.intType(
81108168 if (field_ty.isAbiInt(mod)) field_ty.intInfo(mod).signedness else .unsigned,
81118169 @intCast(field_bit_size),
81128170 );
......@@ -8127,7 +8185,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
81278185 try self.copyToRegisterWithInstTracking(inst, field_ty, dst_mcv);
81288186 }
81298187
8130 const container_abi_size: u32 = @intCast(container_ty.abiSize(mod));
8188 const container_abi_size: u32 = @intCast(container_ty.abiSize(pt));
81318189 const dst_mcv = if (field_byte_off + field_abi_size <= container_abi_size and
81328190 self.reuseOperand(inst, operand, 0, src_mcv))
81338191 off_mcv
......@@ -8228,16 +8286,17 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
82288286}
82298287
82308288fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
8231 const mod = self.bin_file.comp.module.?;
8289 const pt = self.pt;
8290 const mod = pt.zcu;
82328291 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
82338292 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
82348293
82358294 const inst_ty = self.typeOfIndex(inst);
82368295 const parent_ty = inst_ty.childType(mod);
82378296 const field_off: i32 = switch (parent_ty.containerLayout(mod)) {
8238 .auto, .@"extern" => @intCast(parent_ty.structFieldOffset(extra.field_index, mod)),
8297 .auto, .@"extern" => @intCast(parent_ty.structFieldOffset(extra.field_index, pt)),
82398298 .@"packed" => @divExact(@as(i32, inst_ty.ptrInfo(mod).packed_offset.bit_offset) +
8240 (if (mod.typeToStruct(parent_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0) -
8299 (if (mod.typeToStruct(parent_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0) -
82418300 self.typeOf(extra.field_ptr).ptrInfo(mod).packed_offset.bit_offset, 8),
82428301 };
82438302
......@@ -8252,10 +8311,11 @@ fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
82528311}
82538312
82548313fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air: Air.Inst.Ref) !MCValue {
8255 const mod = self.bin_file.comp.module.?;
8314 const pt = self.pt;
8315 const mod = pt.zcu;
82568316 const src_ty = self.typeOf(src_air);
82578317 if (src_ty.zigTypeTag(mod) == .Vector)
8258 return self.fail("TODO implement genUnOp for {}", .{src_ty.fmt(mod)});
8318 return self.fail("TODO implement genUnOp for {}", .{src_ty.fmt(pt)});
82598319
82608320 var src_mcv = try self.resolveInst(src_air);
82618321 switch (src_mcv) {
......@@ -8290,7 +8350,7 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
82908350 };
82918351 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
82928352
8293 const abi_size: u16 = @intCast(src_ty.abiSize(mod));
8353 const abi_size: u16 = @intCast(src_ty.abiSize(pt));
82948354 switch (tag) {
82958355 .not => {
82968356 const limb_abi_size: u16 = @min(abi_size, 8);
......@@ -8304,7 +8364,7 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
83048364 .signed => abi_size * 8,
83058365 .unsigned => int_info.bits,
83068366 } - byte_off * 8, limb_abi_size * 8));
8307 const limb_ty = try mod.intType(int_info.signedness, limb_bits);
8367 const limb_ty = try pt.intType(int_info.signedness, limb_bits);
83088368 const limb_mcv = switch (byte_off) {
83098369 0 => dst_mcv,
83108370 else => dst_mcv.address().offset(byte_off).deref(),
......@@ -8340,9 +8400,9 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
83408400}
83418401
83428402fn genUnOpMir(self: *Self, mir_tag: Mir.Inst.FixedTag, dst_ty: Type, dst_mcv: MCValue) !void {
8343 const mod = self.bin_file.comp.module.?;
8344 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
8345 if (abi_size > 8) return self.fail("TODO implement {} for {}", .{ mir_tag, dst_ty.fmt(mod) });
8403 const pt = self.pt;
8404 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
8405 if (abi_size > 8) return self.fail("TODO implement {} for {}", .{ mir_tag, dst_ty.fmt(pt) });
83468406 switch (dst_mcv) {
83478407 .none,
83488408 .unreach,
......@@ -8389,9 +8449,9 @@ fn genShiftBinOpMir(
83898449 rhs_ty: Type,
83908450 rhs_mcv: MCValue,
83918451) !void {
8392 const mod = self.bin_file.comp.module.?;
8393 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
8394 const shift_abi_size: u32 = @intCast(rhs_ty.abiSize(mod));
8452 const pt = self.pt;
8453 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
8454 const shift_abi_size: u32 = @intCast(rhs_ty.abiSize(pt));
83958455 try self.spillEflagsIfOccupied();
83968456
83978457 if (abi_size > 16) {
......@@ -9046,9 +9106,10 @@ fn genShiftBinOp(
90469106 lhs_ty: Type,
90479107 rhs_ty: Type,
90489108) !MCValue {
9049 const mod = self.bin_file.comp.module.?;
9109 const pt = self.pt;
9110 const mod = pt.zcu;
90509111 if (lhs_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement genShiftBinOp for {}", .{
9051 lhs_ty.fmt(mod),
9112 lhs_ty.fmt(pt),
90529113 });
90539114
90549115 try self.register_manager.getKnownReg(.rcx, null);
......@@ -9104,13 +9165,14 @@ fn genMulDivBinOp(
91049165 lhs_mcv: MCValue,
91059166 rhs_mcv: MCValue,
91069167) !MCValue {
9107 const mod = self.bin_file.comp.module.?;
9168 const pt = self.pt;
9169 const mod = pt.zcu;
91089170 if (dst_ty.zigTypeTag(mod) == .Vector or dst_ty.zigTypeTag(mod) == .Float) return self.fail(
91099171 "TODO implement genMulDivBinOp for {s} from {} to {}",
9110 .{ @tagName(tag), src_ty.fmt(mod), dst_ty.fmt(mod) },
9172 .{ @tagName(tag), src_ty.fmt(pt), dst_ty.fmt(pt) },
91119173 );
9112 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
9113 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
9174 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
9175 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
91149176
91159177 assert(self.register_manager.isRegFree(.rax));
91169178 assert(self.register_manager.isRegFree(.rcx));
......@@ -9299,13 +9361,13 @@ fn genMulDivBinOp(
92999361 .signed => {},
93009362 .unsigned => {
93019363 const dst_mcv = try self.allocRegOrMemAdvanced(dst_ty, maybe_inst, false);
9302 const manyptr_u32_ty = try mod.ptrType(.{
9364 const manyptr_u32_ty = try pt.ptrType(.{
93039365 .child = .u32_type,
93049366 .flags = .{
93059367 .size = .Many,
93069368 },
93079369 });
9308 const manyptr_const_u32_ty = try mod.ptrType(.{
9370 const manyptr_const_u32_ty = try pt.ptrType(.{
93099371 .child = .u32_type,
93109372 .flags = .{
93119373 .size = .Many,
......@@ -9348,7 +9410,7 @@ fn genMulDivBinOp(
93489410 }
93499411 return self.fail(
93509412 "TODO implement genMulDivBinOp for {s} from {} to {}",
9351 .{ @tagName(tag), src_ty.fmt(mod), dst_ty.fmt(mod) },
9413 .{ @tagName(tag), src_ty.fmt(pt), dst_ty.fmt(pt) },
93529414 );
93539415 }
93549416 const ty = if (dst_abi_size <= 8) dst_ty else src_ty;
......@@ -9515,10 +9577,11 @@ fn genBinOp(
95159577 lhs_air: Air.Inst.Ref,
95169578 rhs_air: Air.Inst.Ref,
95179579) !MCValue {
9518 const mod = self.bin_file.comp.module.?;
9580 const pt = self.pt;
9581 const mod = pt.zcu;
95199582 const lhs_ty = self.typeOf(lhs_air);
95209583 const rhs_ty = self.typeOf(rhs_air);
9521 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
9584 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
95229585
95239586 if (lhs_ty.isRuntimeFloat()) libcall: {
95249587 const float_bits = lhs_ty.floatBits(self.target.*);
......@@ -9556,7 +9619,7 @@ fn genBinOp(
95569619 floatLibcAbiSuffix(lhs_ty),
95579620 }),
95589621 else => return self.fail("TODO implement genBinOp for {s} {}", .{
9559 @tagName(air_tag), lhs_ty.fmt(mod),
9622 @tagName(air_tag), lhs_ty.fmt(pt),
95609623 }),
95619624 } catch unreachable;
95629625 const result = try self.genCall(.{ .lib = .{
......@@ -9668,7 +9731,7 @@ fn genBinOp(
96689731 break :adjusted .{ .register = dst_reg };
96699732 },
96709733 80, 128 => return self.fail("TODO implement genBinOp for {s} of {}", .{
9671 @tagName(air_tag), lhs_ty.fmt(mod),
9734 @tagName(air_tag), lhs_ty.fmt(pt),
96729735 }),
96739736 else => unreachable,
96749737 };
......@@ -9700,8 +9763,8 @@ fn genBinOp(
97009763 };
97019764 if (sse_op and ((lhs_ty.scalarType(mod).isRuntimeFloat() and
97029765 lhs_ty.scalarType(mod).floatBits(self.target.*) == 80) or
9703 lhs_ty.abiSize(mod) > @as(u6, if (self.hasFeature(.avx)) 32 else 16)))
9704 return self.fail("TODO implement genBinOp for {s} {}", .{ @tagName(air_tag), lhs_ty.fmt(mod) });
9766 lhs_ty.abiSize(pt) > @as(u6, if (self.hasFeature(.avx)) 32 else 16)))
9767 return self.fail("TODO implement genBinOp for {s} {}", .{ @tagName(air_tag), lhs_ty.fmt(pt) });
97059768
97069769 const maybe_mask_reg = switch (air_tag) {
97079770 else => null,
......@@ -9857,7 +9920,7 @@ fn genBinOp(
98579920 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
98589921 defer self.register_manager.unlockReg(tmp_lock);
98599922
9860 const elem_size = lhs_ty.elemType2(mod).abiSize(mod);
9923 const elem_size = lhs_ty.elemType2(mod).abiSize(pt);
98619924 try self.genIntMulComplexOpMir(rhs_ty, tmp_mcv, .{ .immediate = elem_size });
98629925 try self.genBinOpMir(
98639926 switch (air_tag) {
......@@ -10003,7 +10066,7 @@ fn genBinOp(
1000310066 },
1000410067 };
1000510068
10006 const cmov_abi_size = @max(@as(u32, @intCast(lhs_ty.abiSize(mod))), 2);
10069 const cmov_abi_size = @max(@as(u32, @intCast(lhs_ty.abiSize(pt))), 2);
1000710070 const tmp_reg = switch (dst_mcv) {
1000810071 .register => |reg| reg,
1000910072 else => try self.copyToTmpRegister(lhs_ty, dst_mcv),
......@@ -10082,7 +10145,7 @@ fn genBinOp(
1008210145 },
1008310146
1008410147 else => return self.fail("TODO implement genBinOp for {s} {}", .{
10085 @tagName(air_tag), lhs_ty.fmt(mod),
10148 @tagName(air_tag), lhs_ty.fmt(pt),
1008610149 }),
1008710150 }
1008810151 return dst_mcv;
......@@ -10835,7 +10898,7 @@ fn genBinOp(
1083510898 },
1083610899 },
1083710900 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
10838 @tagName(air_tag), lhs_ty.fmt(mod),
10901 @tagName(air_tag), lhs_ty.fmt(pt),
1083910902 });
1084010903
1084110904 const lhs_copy_reg = if (maybe_mask_reg) |_| registerAlias(
......@@ -10978,7 +11041,7 @@ fn genBinOp(
1097811041 },
1097911042 else => unreachable,
1098011043 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
10981 @tagName(air_tag), lhs_ty.fmt(mod),
11044 @tagName(air_tag), lhs_ty.fmt(pt),
1098211045 }),
1098311046 mask_reg,
1098411047 rhs_copy_reg,
......@@ -11010,7 +11073,7 @@ fn genBinOp(
1101011073 },
1101111074 else => unreachable,
1101211075 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11013 @tagName(air_tag), lhs_ty.fmt(mod),
11076 @tagName(air_tag), lhs_ty.fmt(pt),
1101411077 }),
1101511078 dst_reg,
1101611079 dst_reg,
......@@ -11046,7 +11109,7 @@ fn genBinOp(
1104611109 },
1104711110 else => unreachable,
1104811111 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11049 @tagName(air_tag), lhs_ty.fmt(mod),
11112 @tagName(air_tag), lhs_ty.fmt(pt),
1105011113 }),
1105111114 mask_reg,
1105211115 mask_reg,
......@@ -11077,7 +11140,7 @@ fn genBinOp(
1107711140 },
1107811141 else => unreachable,
1107911142 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11080 @tagName(air_tag), lhs_ty.fmt(mod),
11143 @tagName(air_tag), lhs_ty.fmt(pt),
1108111144 }),
1108211145 dst_reg,
1108311146 lhs_copy_reg.?,
......@@ -11107,7 +11170,7 @@ fn genBinOp(
1110711170 },
1110811171 else => unreachable,
1110911172 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11110 @tagName(air_tag), lhs_ty.fmt(mod),
11173 @tagName(air_tag), lhs_ty.fmt(pt),
1111111174 });
1111211175 try self.asmRegisterRegister(.{ mir_fixes, .@"and" }, dst_reg, mask_reg);
1111311176 try self.asmRegisterRegister(.{ mir_fixes, .andn }, mask_reg, lhs_copy_reg.?);
......@@ -11125,8 +11188,8 @@ fn genBinOp(
1112511188 .cmp_gte,
1112611189 .cmp_neq,
1112711190 => {
11128 const unsigned_ty = try lhs_ty.toUnsigned(mod);
11129 const not_mcv = try self.genTypedValue(try unsigned_ty.maxInt(mod, unsigned_ty));
11191 const unsigned_ty = try lhs_ty.toUnsigned(pt);
11192 const not_mcv = try self.genTypedValue(try unsigned_ty.maxInt(pt, unsigned_ty));
1113011193 const not_mem: Memory = if (not_mcv.isMemory())
1113111194 try not_mcv.mem(self, Memory.Size.fromSize(abi_size))
1113211195 else
......@@ -11195,8 +11258,9 @@ fn genBinOpMir(
1119511258 dst_mcv: MCValue,
1119611259 src_mcv: MCValue,
1119711260) !void {
11198 const mod = self.bin_file.comp.module.?;
11199 const abi_size: u32 = @intCast(ty.abiSize(mod));
11261 const pt = self.pt;
11262 const mod = pt.zcu;
11263 const abi_size: u32 = @intCast(ty.abiSize(pt));
1120011264 try self.spillEflagsIfOccupied();
1120111265 switch (dst_mcv) {
1120211266 .none,
......@@ -11358,7 +11422,7 @@ fn genBinOpMir(
1135811422 .load_got,
1135911423 .load_tlv,
1136011424 => {
11361 const ptr_ty = try mod.singleConstPtrType(ty);
11425 const ptr_ty = try pt.singleConstPtrType(ty);
1136211426 const addr_reg = try self.copyToTmpRegister(ptr_ty, src_mcv.address());
1136311427 return self.genBinOpMir(mir_limb_tag, ty, dst_mcv, .{
1136411428 .indirect = .{ .reg = addr_reg, .off = off },
......@@ -11619,8 +11683,8 @@ fn genBinOpMir(
1161911683/// Performs multi-operand integer multiplication between dst_mcv and src_mcv, storing the result in dst_mcv.
1162011684/// Does not support byte-size operands.
1162111685fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: MCValue) InnerError!void {
11622 const mod = self.bin_file.comp.module.?;
11623 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
11686 const pt = self.pt;
11687 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
1162411688 try self.spillEflagsIfOccupied();
1162511689 switch (dst_mcv) {
1162611690 .none,
......@@ -11746,7 +11810,8 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M
1174611810}
1174711811
1174811812fn airArg(self: *Self, inst: Air.Inst.Index) !void {
11749 const mod = self.bin_file.comp.module.?;
11813 const pt = self.pt;
11814 const mod = pt.zcu;
1175011815 // skip zero-bit arguments as they don't have a corresponding arg instruction
1175111816 var arg_index = self.arg_index;
1175211817 while (self.args[arg_index] == .none) arg_index += 1;
......@@ -11808,7 +11873,7 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1180811873 try self.genInlineMemset(
1180911874 dst_mcv.address().offset(@intFromBool(regs_frame_addr.regs > 0)),
1181011875 .{ .immediate = 0 },
11811 .{ .immediate = arg_ty.abiSize(mod) - @intFromBool(regs_frame_addr.regs > 0) },
11876 .{ .immediate = arg_ty.abiSize(pt) - @intFromBool(regs_frame_addr.regs > 0) },
1181211877 .{},
1181311878 );
1181411879
......@@ -11865,7 +11930,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1186511930}
1186611931
1186711932fn genArgDbgInfo(self: Self, ty: Type, name: [:0]const u8, mcv: MCValue) !void {
11868 const mod = self.bin_file.comp.module.?;
11933 const pt = self.pt;
11934 const mod = pt.zcu;
1186911935 switch (self.debug_output) {
1187011936 .dwarf => |dw| {
1187111937 const loc: link.File.Dwarf.DeclState.DbgInfoLoc = switch (mcv) {
......@@ -11901,7 +11967,8 @@ fn genVarDbgInfo(
1190111967 mcv: MCValue,
1190211968 name: [:0]const u8,
1190311969) !void {
11904 const mod = self.bin_file.comp.module.?;
11970 const pt = self.pt;
11971 const mod = pt.zcu;
1190511972 const is_ptr = switch (tag) {
1190611973 .dbg_var_ptr => true,
1190711974 .dbg_var_val => false,
......@@ -12020,7 +12087,8 @@ fn genCall(self: *Self, info: union(enum) {
1202012087 callee: []const u8,
1202112088 },
1202212089}, arg_types: []const Type, args: []const MCValue) !MCValue {
12023 const mod = self.bin_file.comp.module.?;
12090 const pt = self.pt;
12091 const mod = pt.zcu;
1202412092
1202512093 const fn_ty = switch (info) {
1202612094 .air => |callee| fn_info: {
......@@ -12031,7 +12099,7 @@ fn genCall(self: *Self, info: union(enum) {
1203112099 else => unreachable,
1203212100 };
1203312101 },
12034 .lib => |lib| try mod.funcType(.{
12102 .lib => |lib| try pt.funcType(.{
1203512103 .param_types = lib.param_types,
1203612104 .return_type = lib.return_type,
1203712105 .cc = .C,
......@@ -12101,7 +12169,7 @@ fn genCall(self: *Self, info: union(enum) {
1210112169 try reg_locks.appendSlice(&self.register_manager.lockRegs(2, regs));
1210212170 },
1210312171 .indirect => |reg_off| {
12104 frame_index.* = try self.allocFrameIndex(FrameAlloc.initType(arg_ty, mod));
12172 frame_index.* = try self.allocFrameIndex(FrameAlloc.initType(arg_ty, pt));
1210512173 try self.genSetMem(.{ .frame = frame_index.* }, 0, arg_ty, src_arg, .{});
1210612174 try self.register_manager.getReg(reg_off.reg, null);
1210712175 try reg_locks.append(self.register_manager.lockReg(reg_off.reg));
......@@ -12173,7 +12241,7 @@ fn genCall(self: *Self, info: union(enum) {
1217312241 .none, .unreach => {},
1217412242 .indirect => |reg_off| {
1217512243 const ret_ty = Type.fromInterned(fn_info.return_type);
12176 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ret_ty, mod));
12244 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ret_ty, pt));
1217712245 try self.genSetReg(reg_off.reg, Type.usize, .{
1217812246 .lea_frame = .{ .index = frame_index, .off = -reg_off.off },
1217912247 }, .{});
......@@ -12188,14 +12256,14 @@ fn genCall(self: *Self, info: union(enum) {
1218812256 .none, .load_frame => {},
1218912257 .register => |dst_reg| switch (fn_info.cc) {
1219012258 else => try self.genSetReg(
12191 registerAlias(dst_reg, @intCast(arg_ty.abiSize(mod))),
12259 registerAlias(dst_reg, @intCast(arg_ty.abiSize(pt))),
1219212260 arg_ty,
1219312261 src_arg,
1219412262 .{},
1219512263 ),
1219612264 .C, .SysV, .Win64 => {
1219712265 const promoted_ty = self.promoteInt(arg_ty);
12198 const promoted_abi_size: u32 = @intCast(promoted_ty.abiSize(mod));
12266 const promoted_abi_size: u32 = @intCast(promoted_ty.abiSize(pt));
1219912267 const dst_alias = registerAlias(dst_reg, promoted_abi_size);
1220012268 try self.genSetReg(dst_alias, promoted_ty, src_arg, .{});
1220112269 if (promoted_ty.toIntern() != arg_ty.toIntern())
......@@ -12246,7 +12314,7 @@ fn genCall(self: *Self, info: union(enum) {
1224612314 // Due to incremental compilation, how function calls are generated depends
1224712315 // on linking.
1224812316 switch (info) {
12249 .air => |callee| if (try self.air.value(callee, mod)) |func_value| {
12317 .air => |callee| if (try self.air.value(callee, pt)) |func_value| {
1225012318 const func_key = mod.intern_pool.indexToKey(func_value.ip_index);
1225112319 switch (switch (func_key) {
1225212320 else => func_key,
......@@ -12332,7 +12400,8 @@ fn genCall(self: *Self, info: union(enum) {
1233212400}
1233312401
1233412402fn airRet(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
12335 const mod = self.bin_file.comp.module.?;
12403 const pt = self.pt;
12404 const mod = pt.zcu;
1233612405 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1233712406
1233812407 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -12387,7 +12456,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
1238712456}
1238812457
1238912458fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
12390 const mod = self.bin_file.comp.module.?;
12459 const pt = self.pt;
12460 const mod = pt.zcu;
1239112461 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1239212462 var ty = self.typeOf(bin_op.lhs);
1239312463 var null_compare: ?Mir.Inst.Index = null;
......@@ -12457,9 +12527,9 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
1245712527 },
1245812528 .Optional => if (!ty.optionalReprIsPayload(mod)) {
1245912529 const opt_ty = ty;
12460 const opt_abi_size: u31 = @intCast(opt_ty.abiSize(mod));
12530 const opt_abi_size: u31 = @intCast(opt_ty.abiSize(pt));
1246112531 ty = opt_ty.optionalChild(mod);
12462 const payload_abi_size: u31 = @intCast(ty.abiSize(mod));
12532 const payload_abi_size: u31 = @intCast(ty.abiSize(pt));
1246312533
1246412534 const temp_lhs_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
1246512535 const temp_lhs_lock = self.register_manager.lockRegAssumeUnused(temp_lhs_reg);
......@@ -12518,7 +12588,7 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
1251812588
1251912589 switch (ty.zigTypeTag(mod)) {
1252012590 else => {
12521 const abi_size: u16 = @intCast(ty.abiSize(mod));
12591 const abi_size: u16 = @intCast(ty.abiSize(pt));
1252212592 const may_flip: enum {
1252312593 may_flip,
1252412594 must_flip,
......@@ -12845,7 +12915,8 @@ fn airCmpVector(self: *Self, inst: Air.Inst.Index) !void {
1284512915}
1284612916
1284712917fn airCmpLtErrorsLen(self: *Self, inst: Air.Inst.Index) !void {
12848 const mod = self.bin_file.comp.module.?;
12918 const pt = self.pt;
12919 const mod = pt.zcu;
1284912920 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1285012921
1285112922 const addr_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
......@@ -12856,7 +12927,7 @@ fn airCmpLtErrorsLen(self: *Self, inst: Air.Inst.Index) !void {
1285612927 try self.spillEflagsIfOccupied();
1285712928
1285812929 const op_ty = self.typeOf(un_op);
12859 const op_abi_size: u32 = @intCast(op_ty.abiSize(mod));
12930 const op_abi_size: u32 = @intCast(op_ty.abiSize(pt));
1286012931 const op_mcv = try self.resolveInst(un_op);
1286112932 const dst_reg = switch (op_mcv) {
1286212933 .register => |reg| reg,
......@@ -12987,8 +13058,8 @@ fn airDbgVar(self: *Self, inst: Air.Inst.Index) !void {
1298713058}
1298813059
1298913060fn genCondBrMir(self: *Self, ty: Type, mcv: MCValue) !Mir.Inst.Index {
12990 const mod = self.bin_file.comp.module.?;
12991 const abi_size = ty.abiSize(mod);
13061 const pt = self.pt;
13062 const abi_size = ty.abiSize(pt);
1299213063 switch (mcv) {
1299313064 .eflags => |cc| {
1299413065 // Here we map the opposites since the jump is to the false branch.
......@@ -13060,7 +13131,8 @@ fn airCondBr(self: *Self, inst: Air.Inst.Index) !void {
1306013131}
1306113132
1306213133fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MCValue {
13063 const mod = self.bin_file.comp.module.?;
13134 const pt = self.pt;
13135 const mod = pt.zcu;
1306413136 switch (opt_mcv) {
1306513137 .register_overflow => |ro| return .{ .eflags = ro.eflags.negate() },
1306613138 else => {},
......@@ -13073,7 +13145,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1307313145 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(mod))
1307413146 .{ .off = 0, .ty = if (pl_ty.isSlice(mod)) pl_ty.slicePtrFieldType(mod) else pl_ty }
1307513147 else
13076 .{ .off = @intCast(pl_ty.abiSize(mod)), .ty = Type.bool };
13148 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
1307713149
1307813150 self.eflags_inst = inst;
1307913151 switch (opt_mcv) {
......@@ -13098,14 +13170,14 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1309813170
1309913171 .register => |opt_reg| {
1310013172 if (some_info.off == 0) {
13101 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13173 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1310213174 const alias_reg = registerAlias(opt_reg, some_abi_size);
1310313175 assert(some_abi_size * 8 == alias_reg.bitSize());
1310413176 try self.asmRegisterRegister(.{ ._, .@"test" }, alias_reg, alias_reg);
1310513177 return .{ .eflags = .z };
1310613178 }
1310713179 assert(some_info.ty.ip_index == .bool_type);
13108 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(mod));
13180 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(pt));
1310913181 try self.asmRegisterImmediate(
1311013182 .{ ._, .bt },
1311113183 registerAlias(opt_reg, opt_abi_size),
......@@ -13125,7 +13197,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1312513197 defer self.register_manager.unlockReg(addr_reg_lock);
1312613198
1312713199 try self.genSetReg(addr_reg, Type.usize, opt_mcv.address(), .{});
13128 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13200 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1312913201 try self.asmMemoryImmediate(
1313013202 .{ ._, .cmp },
1313113203 .{
......@@ -13141,7 +13213,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1314113213 },
1314213214
1314313215 .indirect, .load_frame => {
13144 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13216 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1314513217 try self.asmMemoryImmediate(
1314613218 .{ ._, .cmp },
1314713219 switch (opt_mcv) {
......@@ -13169,7 +13241,8 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1316913241}
1317013242
1317113243fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue) !MCValue {
13172 const mod = self.bin_file.comp.module.?;
13244 const pt = self.pt;
13245 const mod = pt.zcu;
1317313246 const opt_ty = ptr_ty.childType(mod);
1317413247 const pl_ty = opt_ty.optionalChild(mod);
1317513248
......@@ -13178,7 +13251,7 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1317813251 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(mod))
1317913252 .{ .off = 0, .ty = if (pl_ty.isSlice(mod)) pl_ty.slicePtrFieldType(mod) else pl_ty }
1318013253 else
13181 .{ .off = @intCast(pl_ty.abiSize(mod)), .ty = Type.bool };
13254 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
1318213255
1318313256 const ptr_reg = switch (ptr_mcv) {
1318413257 .register => |reg| reg,
......@@ -13187,7 +13260,7 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1318713260 const ptr_lock = self.register_manager.lockReg(ptr_reg);
1318813261 defer if (ptr_lock) |lock| self.register_manager.unlockReg(lock);
1318913262
13190 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13263 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1319113264 try self.asmMemoryImmediate(
1319213265 .{ ._, .cmp },
1319313266 .{
......@@ -13205,13 +13278,14 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1320513278}
1320613279
1320713280fn isErr(self: *Self, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MCValue {
13208 const mod = self.bin_file.comp.module.?;
13281 const pt = self.pt;
13282 const mod = pt.zcu;
1320913283 const err_ty = eu_ty.errorUnionSet(mod);
1321013284 if (err_ty.errorSetIsEmpty(mod)) return MCValue{ .immediate = 0 }; // always false
1321113285
1321213286 try self.spillEflagsIfOccupied();
1321313287
13214 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), mod));
13288 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), pt));
1321513289 switch (eu_mcv) {
1321613290 .register => |reg| {
1321713291 const eu_lock = self.register_manager.lockReg(reg);
......@@ -13253,7 +13327,8 @@ fn isErr(self: *Self, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue)
1325313327}
1325413328
1325513329fn isErrPtr(self: *Self, maybe_inst: ?Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue) !MCValue {
13256 const mod = self.bin_file.comp.module.?;
13330 const pt = self.pt;
13331 const mod = pt.zcu;
1325713332 const eu_ty = ptr_ty.childType(mod);
1325813333 const err_ty = eu_ty.errorUnionSet(mod);
1325913334 if (err_ty.errorSetIsEmpty(mod)) return MCValue{ .immediate = 0 }; // always false
......@@ -13267,7 +13342,7 @@ fn isErrPtr(self: *Self, maybe_inst: ?Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCV
1326713342 const ptr_lock = self.register_manager.lockReg(ptr_reg);
1326813343 defer if (ptr_lock) |lock| self.register_manager.unlockReg(lock);
1326913344
13270 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), mod));
13345 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), pt));
1327113346 try self.asmMemoryImmediate(
1327213347 .{ ._, .cmp },
1327313348 .{
......@@ -13539,12 +13614,12 @@ fn performReloc(self: *Self, reloc: Mir.Inst.Index) void {
1353913614}
1354013615
1354113616fn airBr(self: *Self, inst: Air.Inst.Index) !void {
13542 const mod = self.bin_file.comp.module.?;
13617 const pt = self.pt;
1354313618 const br = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
1354413619
1354513620 const block_ty = self.typeOfIndex(br.block_inst);
1354613621 const block_unused =
13547 !block_ty.hasRuntimeBitsIgnoreComptime(mod) or self.liveness.isUnused(br.block_inst);
13622 !block_ty.hasRuntimeBitsIgnoreComptime(pt) or self.liveness.isUnused(br.block_inst);
1354813623 const block_tracking = self.inst_tracking.getPtr(br.block_inst).?;
1354913624 const block_data = self.blocks.getPtr(br.block_inst).?;
1355013625 const first_br = block_data.relocs.items.len == 0;
......@@ -13600,7 +13675,8 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
1360013675}
1360113676
1360213677fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
13603 const mod = self.bin_file.comp.module.?;
13678 const pt = self.pt;
13679 const mod = pt.zcu;
1360413680 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1360513681 const extra = self.air.extraData(Air.Asm, ty_pl.payload);
1360613682 const clobbers_len: u31 = @truncate(extra.data.flags);
......@@ -13664,7 +13740,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
1366413740 'x' => abi.RegisterClass.sse,
1366513741 else => unreachable,
1366613742 }) orelse return self.fail("ran out of registers lowering inline asm", .{}),
13667 @intCast(ty.abiSize(mod)),
13743 @intCast(ty.abiSize(pt)),
1366813744 )
1366913745 else if (mem.eql(u8, rest, "m"))
1367013746 if (output != .none) null else return self.fail(
......@@ -13734,7 +13810,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
1373413810 break :arg input_mcv;
1373513811 const reg = try self.register_manager.allocReg(null, rc);
1373613812 try self.genSetReg(reg, ty, input_mcv, .{});
13737 break :arg .{ .register = registerAlias(reg, @intCast(ty.abiSize(mod))) };
13813 break :arg .{ .register = registerAlias(reg, @intCast(ty.abiSize(pt))) };
1373813814 } else if (mem.eql(u8, constraint, "i") or mem.eql(u8, constraint, "n"))
1373913815 switch (input_mcv) {
1374013816 .immediate => |imm| .{ .immediate = imm },
......@@ -14310,18 +14386,19 @@ const MoveStrategy = union(enum) {
1431014386 }
1431114387};
1431214388fn moveStrategy(self: *Self, ty: Type, class: Register.Class, aligned: bool) !MoveStrategy {
14313 const mod = self.bin_file.comp.module.?;
14389 const pt = self.pt;
14390 const mod = pt.zcu;
1431414391 switch (class) {
1431514392 .general_purpose, .segment => return .{ .move = .{ ._, .mov } },
1431614393 .x87 => return .x87_load_store,
1431714394 .mmx => {},
1431814395 .sse => switch (ty.zigTypeTag(mod)) {
1431914396 else => {
14320 const classes = mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .other), .none);
14397 const classes = mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .other), .none);
1432114398 assert(std.mem.indexOfNone(abi.Class, classes, &.{
1432214399 .integer, .sse, .sseup, .memory, .float, .float_combine,
1432314400 }) == null);
14324 const abi_size = ty.abiSize(mod);
14401 const abi_size = ty.abiSize(pt);
1432514402 if (abi_size < 4 or
1432614403 std.mem.indexOfScalar(abi.Class, classes, .integer) != null) switch (abi_size) {
1432714404 1 => if (self.hasFeature(.avx)) return .{ .vex_insert_extract = .{
......@@ -14532,7 +14609,7 @@ fn moveStrategy(self: *Self, ty: Type, class: Register.Class, aligned: bool) !Mo
1453214609 },
1453314610 .ip => {},
1453414611 }
14535 return self.fail("TODO moveStrategy for {}", .{ty.fmt(mod)});
14612 return self.fail("TODO moveStrategy for {}", .{ty.fmt(pt)});
1453614613}
1453714614
1453814615const CopyOptions = struct {
......@@ -14540,7 +14617,7 @@ const CopyOptions = struct {
1454014617};
1454114618
1454214619fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: CopyOptions) InnerError!void {
14543 const mod = self.bin_file.comp.module.?;
14620 const pt = self.pt;
1454414621
1454514622 const src_lock = if (src_mcv.getReg()) |reg| self.register_manager.lockReg(reg) else null;
1454614623 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
......@@ -14601,7 +14678,7 @@ fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: Copy
1460114678 opts,
1460214679 ),
1460314680 else => return self.fail("TODO implement genCopy for {s} of {}", .{
14604 @tagName(src_mcv), ty.fmt(mod),
14681 @tagName(src_mcv), ty.fmt(pt),
1460514682 }),
1460614683 };
1460714684 defer if (src_info) |info| self.register_manager.unlockReg(info.addr_lock);
......@@ -14617,7 +14694,7 @@ fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: Copy
1461714694 } },
1461814695 else => unreachable,
1461914696 }, opts);
14620 part_disp += @intCast(dst_ty.abiSize(mod));
14697 part_disp += @intCast(dst_ty.abiSize(pt));
1462114698 }
1462214699 },
1462314700 .indirect => |reg_off| try self.genSetMem(
......@@ -14658,9 +14735,10 @@ fn genSetReg(
1465814735 src_mcv: MCValue,
1465914736 opts: CopyOptions,
1466014737) InnerError!void {
14661 const mod = self.bin_file.comp.module.?;
14662 const abi_size: u32 = @intCast(ty.abiSize(mod));
14663 if (ty.bitSize(mod) > dst_reg.bitSize())
14738 const pt = self.pt;
14739 const mod = pt.zcu;
14740 const abi_size: u32 = @intCast(ty.abiSize(pt));
14741 if (ty.bitSize(pt) > dst_reg.bitSize())
1466414742 return self.fail("genSetReg called with a value larger than dst_reg", .{});
1466514743 switch (src_mcv) {
1466614744 .none,
......@@ -14686,7 +14764,7 @@ fn genSetReg(
1468614764 ),
1468714765 else => unreachable,
1468814766 },
14689 .segment, .x87, .mmx, .sse => try self.genSetReg(dst_reg, ty, try self.genTypedValue(try mod.undefValue(ty)), opts),
14767 .segment, .x87, .mmx, .sse => try self.genSetReg(dst_reg, ty, try self.genTypedValue(try pt.undefValue(ty)), opts),
1469014768 .ip => unreachable,
1469114769 },
1469214770 .eflags => |cc| try self.asmSetccRegister(cc, dst_reg.to8()),
......@@ -14797,7 +14875,7 @@ fn genSetReg(
1479714875 80 => null,
1479814876 else => unreachable,
1479914877 },
14800 }) orelse return self.fail("TODO implement genSetReg for {}", .{ty.fmt(mod)}),
14878 }) orelse return self.fail("TODO implement genSetReg for {}", .{ty.fmt(pt)}),
1480114879 registerAlias(dst_reg, abi_size),
1480214880 registerAlias(src_reg, abi_size),
1480314881 ),
......@@ -14847,7 +14925,7 @@ fn genSetReg(
1484714925 return (try self.moveStrategy(
1484814926 ty,
1484914927 dst_reg.class(),
14850 ty.abiAlignment(mod).check(@as(u32, @bitCast(small_addr))),
14928 ty.abiAlignment(pt).check(@as(u32, @bitCast(small_addr))),
1485114929 )).read(self, registerAlias(dst_reg, abi_size), .{
1485214930 .base = .{ .reg = .ds },
1485314931 .mod = .{ .rm = .{
......@@ -14967,8 +15045,9 @@ fn genSetMem(
1496715045 src_mcv: MCValue,
1496815046 opts: CopyOptions,
1496915047) InnerError!void {
14970 const mod = self.bin_file.comp.module.?;
14971 const abi_size: u32 = @intCast(ty.abiSize(mod));
15048 const pt = self.pt;
15049 const mod = pt.zcu;
15050 const abi_size: u32 = @intCast(ty.abiSize(pt));
1497215051 const dst_ptr_mcv: MCValue = switch (base) {
1497315052 .none => .{ .immediate = @bitCast(@as(i64, disp)) },
1497415053 .reg => |base_reg| .{ .register_offset = .{ .reg = base_reg, .off = disp } },
......@@ -15094,21 +15173,21 @@ fn genSetMem(
1509415173 var part_disp: i32 = disp;
1509515174 for (try self.splitType(ty), src_regs) |src_ty, src_reg| {
1509615175 try self.genSetMem(base, part_disp, src_ty, .{ .register = src_reg }, opts);
15097 part_disp += @intCast(src_ty.abiSize(mod));
15176 part_disp += @intCast(src_ty.abiSize(pt));
1509815177 }
1509915178 },
1510015179 .register_overflow => |ro| switch (ty.zigTypeTag(mod)) {
1510115180 .Struct => {
1510215181 try self.genSetMem(
1510315182 base,
15104 disp + @as(i32, @intCast(ty.structFieldOffset(0, mod))),
15183 disp + @as(i32, @intCast(ty.structFieldOffset(0, pt))),
1510515184 ty.structFieldType(0, mod),
1510615185 .{ .register = ro.reg },
1510715186 opts,
1510815187 );
1510915188 try self.genSetMem(
1511015189 base,
15111 disp + @as(i32, @intCast(ty.structFieldOffset(1, mod))),
15190 disp + @as(i32, @intCast(ty.structFieldOffset(1, pt))),
1511215191 ty.structFieldType(1, mod),
1511315192 .{ .eflags = ro.eflags },
1511415193 opts,
......@@ -15120,14 +15199,14 @@ fn genSetMem(
1512015199 try self.genSetMem(base, disp, child_ty, .{ .register = ro.reg }, opts);
1512115200 try self.genSetMem(
1512215201 base,
15123 disp + @as(i32, @intCast(child_ty.abiSize(mod))),
15202 disp + @as(i32, @intCast(child_ty.abiSize(pt))),
1512415203 Type.bool,
1512515204 .{ .eflags = ro.eflags },
1512615205 opts,
1512715206 );
1512815207 },
1512915208 else => return self.fail("TODO implement genSetMem for {s} of {}", .{
15130 @tagName(src_mcv), ty.fmt(mod),
15209 @tagName(src_mcv), ty.fmt(pt),
1513115210 }),
1513215211 },
1513315212 .register_offset,
......@@ -15236,8 +15315,9 @@ fn genLazySymbolRef(
1523615315 reg: Register,
1523715316 lazy_sym: link.File.LazySymbol,
1523815317) InnerError!void {
15318 const pt = self.pt;
1523915319 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
15240 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
15320 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
1524115321 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1524215322 const sym = elf_file.symbol(sym_index);
1524315323 if (self.mod.pic) {
......@@ -15273,7 +15353,7 @@ fn genLazySymbolRef(
1527315353 }
1527415354 }
1527515355 } else if (self.bin_file.cast(link.File.Plan9)) |p9_file| {
15276 const atom_index = p9_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
15356 const atom_index = p9_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
1527715357 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1527815358 var atom = p9_file.getAtom(atom_index);
1527915359 _ = atom.getOrCreateOffsetTableEntry(p9_file);
......@@ -15300,7 +15380,7 @@ fn genLazySymbolRef(
1530015380 else => unreachable,
1530115381 }
1530215382 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| {
15303 const atom_index = coff_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
15383 const atom_index = coff_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
1530415384 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1530515385 const sym_index = coff_file.getAtom(atom_index).getSymbolIndex().?;
1530615386 switch (tag) {
......@@ -15314,7 +15394,7 @@ fn genLazySymbolRef(
1531415394 else => unreachable,
1531515395 }
1531615396 } else if (self.bin_file.cast(link.File.MachO)) |macho_file| {
15317 const sym_index = macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, lazy_sym) catch |err|
15397 const sym_index = macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, pt, lazy_sym) catch |err|
1531815398 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1531915399 const sym = macho_file.getSymbol(sym_index);
1532015400 switch (tag) {
......@@ -15353,7 +15433,8 @@ fn airIntFromPtr(self: *Self, inst: Air.Inst.Index) !void {
1535315433}
1535415434
1535515435fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
15356 const mod = self.bin_file.comp.module.?;
15436 const pt = self.pt;
15437 const mod = pt.zcu;
1535715438 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1535815439 const dst_ty = self.typeOfIndex(inst);
1535915440 const src_ty = self.typeOf(ty_op.operand);
......@@ -15366,10 +15447,10 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1536615447 const src_lock = if (src_mcv.getReg()) |reg| self.register_manager.lockReg(reg) else null;
1536715448 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
1536815449
15369 const dst_mcv = if (dst_rc.supersetOf(src_rc) and dst_ty.abiSize(mod) <= src_ty.abiSize(mod) and
15450 const dst_mcv = if (dst_rc.supersetOf(src_rc) and dst_ty.abiSize(pt) <= src_ty.abiSize(pt) and
1537015451 self.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: {
1537115452 const dst_mcv = try self.allocRegOrMem(inst, true);
15372 try self.genCopy(switch (math.order(dst_ty.abiSize(mod), src_ty.abiSize(mod))) {
15453 try self.genCopy(switch (math.order(dst_ty.abiSize(pt), src_ty.abiSize(pt))) {
1537315454 .lt => dst_ty,
1537415455 .eq => if (!dst_mcv.isMemory() or src_mcv.isMemory()) dst_ty else src_ty,
1537515456 .gt => src_ty,
......@@ -15382,8 +15463,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1538215463 if (dst_ty.isAbiInt(mod) and src_ty.isAbiInt(mod) and
1538315464 dst_ty.intInfo(mod).signedness == src_ty.intInfo(mod).signedness) break :result dst_mcv;
1538415465
15385 const abi_size = dst_ty.abiSize(mod);
15386 const bit_size = dst_ty.bitSize(mod);
15466 const abi_size = dst_ty.abiSize(pt);
15467 const bit_size = dst_ty.bitSize(pt);
1538715468 if (abi_size * 8 <= bit_size or dst_ty.isVector(mod)) break :result dst_mcv;
1538815469
1538915470 const dst_limbs_len = math.divCeil(i32, @intCast(bit_size), 64) catch unreachable;
......@@ -15412,7 +15493,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1541215493}
1541315494
1541415495fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
15415 const mod = self.bin_file.comp.module.?;
15496 const pt = self.pt;
15497 const mod = pt.zcu;
1541615498 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1541715499
1541815500 const slice_ty = self.typeOfIndex(inst);
......@@ -15421,11 +15503,11 @@ fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
1542115503 const array_ty = ptr_ty.childType(mod);
1542215504 const array_len = array_ty.arrayLen(mod);
1542315505
15424 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, mod));
15506 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
1542515507 try self.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, ptr, .{});
1542615508 try self.genSetMem(
1542715509 .{ .frame = frame_index },
15428 @intCast(ptr_ty.abiSize(mod)),
15510 @intCast(ptr_ty.abiSize(pt)),
1542915511 Type.usize,
1543015512 .{ .immediate = array_len },
1543115513 .{},
......@@ -15436,14 +15518,15 @@ fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
1543615518}
1543715519
1543815520fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
15439 const mod = self.bin_file.comp.module.?;
15521 const pt = self.pt;
15522 const mod = pt.zcu;
1544015523 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1544115524
1544215525 const dst_ty = self.typeOfIndex(inst);
1544315526 const dst_bits = dst_ty.floatBits(self.target.*);
1544415527
1544515528 const src_ty = self.typeOf(ty_op.operand);
15446 const src_bits: u32 = @intCast(src_ty.bitSize(mod));
15529 const src_bits: u32 = @intCast(src_ty.bitSize(pt));
1544715530 const src_signedness =
1544815531 if (src_ty.isAbiInt(mod)) src_ty.intInfo(mod).signedness else .unsigned;
1544915532 const src_size = math.divCeil(u32, @max(switch (src_signedness) {
......@@ -15458,7 +15541,7 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1545815541 else => unreachable,
1545915542 }) {
1546015543 if (src_bits > 128) return self.fail("TODO implement airFloatFromInt from {} to {}", .{
15461 src_ty.fmt(mod), dst_ty.fmt(mod),
15544 src_ty.fmt(pt), dst_ty.fmt(pt),
1546215545 });
1546315546
1546415547 var callee_buf: ["__floatun?i?f".len]u8 = undefined;
......@@ -15500,7 +15583,7 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1550015583 },
1550115584 else => null,
1550215585 }) orelse return self.fail("TODO implement airFloatFromInt from {} to {}", .{
15503 src_ty.fmt(mod), dst_ty.fmt(mod),
15586 src_ty.fmt(pt), dst_ty.fmt(pt),
1550415587 });
1550515588 const dst_alias = dst_reg.to128();
1550615589 const src_alias = registerAlias(src_reg, src_size);
......@@ -15515,11 +15598,12 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1551515598}
1551615599
1551715600fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
15518 const mod = self.bin_file.comp.module.?;
15601 const pt = self.pt;
15602 const mod = pt.zcu;
1551915603 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1552015604
1552115605 const dst_ty = self.typeOfIndex(inst);
15522 const dst_bits: u32 = @intCast(dst_ty.bitSize(mod));
15606 const dst_bits: u32 = @intCast(dst_ty.bitSize(pt));
1552315607 const dst_signedness =
1552415608 if (dst_ty.isAbiInt(mod)) dst_ty.intInfo(mod).signedness else .unsigned;
1552515609 const dst_size = math.divCeil(u32, @max(switch (dst_signedness) {
......@@ -15537,7 +15621,7 @@ fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
1553715621 else => unreachable,
1553815622 }) {
1553915623 if (dst_bits > 128) return self.fail("TODO implement airIntFromFloat from {} to {}", .{
15540 src_ty.fmt(mod), dst_ty.fmt(mod),
15624 src_ty.fmt(pt), dst_ty.fmt(pt),
1554115625 });
1554215626
1554315627 var callee_buf: ["__fixuns?f?i".len]u8 = undefined;
......@@ -15586,13 +15670,13 @@ fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
1558615670}
1558715671
1558815672fn airCmpxchg(self: *Self, inst: Air.Inst.Index) !void {
15589 const mod = self.bin_file.comp.module.?;
15673 const pt = self.pt;
1559015674 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1559115675 const extra = self.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
1559215676
1559315677 const ptr_ty = self.typeOf(extra.ptr);
1559415678 const val_ty = self.typeOf(extra.expected_value);
15595 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
15679 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
1559615680
1559715681 try self.spillRegisters(&.{ .rax, .rdx, .rbx, .rcx });
1559815682 const regs_lock = self.register_manager.lockRegsAssumeUnused(4, .{ .rax, .rdx, .rbx, .rcx });
......@@ -15682,7 +15766,8 @@ fn atomicOp(
1568215766 rmw_op: ?std.builtin.AtomicRmwOp,
1568315767 order: std.builtin.AtomicOrder,
1568415768) InnerError!MCValue {
15685 const mod = self.bin_file.comp.module.?;
15769 const pt = self.pt;
15770 const mod = pt.zcu;
1568615771 const ptr_lock = switch (ptr_mcv) {
1568715772 .register => |reg| self.register_manager.lockReg(reg),
1568815773 else => null,
......@@ -15695,7 +15780,7 @@ fn atomicOp(
1569515780 };
1569615781 defer if (val_lock) |lock| self.register_manager.unlockReg(lock);
1569715782
15698 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
15783 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
1569915784 const mem_size = Memory.Size.fromSize(val_abi_size);
1570015785 const ptr_mem: Memory = switch (ptr_mcv) {
1570115786 .immediate, .register, .register_offset, .lea_frame => try ptr_mcv.deref().mem(self, mem_size),
......@@ -15809,7 +15894,7 @@ fn atomicOp(
1580915894 },
1581015895 else => unreachable,
1581115896 }) orelse return self.fail("TODO implement atomicOp of {s} for {}", .{
15812 @tagName(op), val_ty.fmt(mod),
15897 @tagName(op), val_ty.fmt(pt),
1581315898 });
1581415899 try self.genSetReg(sse_reg, val_ty, .{ .register = .rax }, .{});
1581515900 switch (mir_tag[0]) {
......@@ -16086,7 +16171,8 @@ fn airAtomicStore(self: *Self, inst: Air.Inst.Index, order: std.builtin.AtomicOr
1608616171}
1608716172
1608816173fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
16089 const mod = self.bin_file.comp.module.?;
16174 const pt = self.pt;
16175 const mod = pt.zcu;
1609016176 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1609116177
1609216178 result: {
......@@ -16112,7 +16198,7 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1611216198 };
1611316199 defer if (src_val_lock) |lock| self.register_manager.unlockReg(lock);
1611416200
16115 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(mod));
16201 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(pt));
1611616202
1611716203 if (elem_abi_size == 1) {
1611816204 const ptr: MCValue = switch (dst_ptr_ty.ptrSize(mod)) {
......@@ -16185,7 +16271,7 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1618516271 self.performReloc(skip_reloc);
1618616272 },
1618716273 .One => {
16188 const elem_ptr_ty = try mod.singleMutPtrType(elem_ty);
16274 const elem_ptr_ty = try pt.singleMutPtrType(elem_ty);
1618916275
1619016276 const len = dst_ptr_ty.childType(mod).arrayLen(mod);
1619116277
......@@ -16214,7 +16300,8 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1621416300}
1621516301
1621616302fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
16217 const mod = self.bin_file.comp.module.?;
16303 const pt = self.pt;
16304 const mod = pt.zcu;
1621816305 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1621916306
1622016307 try self.spillRegisters(&.{ .rdi, .rsi, .rcx });
......@@ -16246,13 +16333,13 @@ fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
1624616333 .{ .i_, .mul },
1624716334 len_reg,
1624816335 try dst_ptr.address().offset(8).deref().mem(self, .qword),
16249 Immediate.s(@intCast(dst_ptr_ty.childType(mod).abiSize(mod))),
16336 Immediate.s(@intCast(dst_ptr_ty.childType(mod).abiSize(pt))),
1625016337 );
1625116338 break :len .{ .register = len_reg };
1625216339 },
1625316340 .One => len: {
1625416341 const array_ty = dst_ptr_ty.childType(mod);
16255 break :len .{ .immediate = array_ty.arrayLen(mod) * array_ty.childType(mod).abiSize(mod) };
16342 break :len .{ .immediate = array_ty.arrayLen(mod) * array_ty.childType(mod).abiSize(pt) };
1625616343 },
1625716344 .C, .Many => unreachable,
1625816345 };
......@@ -16269,7 +16356,8 @@ fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
1626916356}
1627016357
1627116358fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
16272 const mod = self.bin_file.comp.module.?;
16359 const pt = self.pt;
16360 const mod = pt.zcu;
1627316361 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1627416362 const inst_ty = self.typeOfIndex(inst);
1627516363 const enum_ty = self.typeOf(un_op);
......@@ -16278,8 +16366,8 @@ fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
1627816366 // We need a properly aligned and sized call frame to be able to call this function.
1627916367 {
1628016368 const needed_call_frame = FrameAlloc.init(.{
16281 .size = inst_ty.abiSize(mod),
16282 .alignment = inst_ty.abiAlignment(mod),
16369 .size = inst_ty.abiSize(pt),
16370 .alignment = inst_ty.abiAlignment(pt),
1628316371 });
1628416372 const frame_allocs_slice = self.frame_allocs.slice();
1628516373 const stack_frame_size =
......@@ -16311,7 +16399,8 @@ fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
1631116399}
1631216400
1631316401fn airErrorName(self: *Self, inst: Air.Inst.Index) !void {
16314 const mod = self.bin_file.comp.module.?;
16402 const pt = self.pt;
16403 const mod = pt.zcu;
1631516404 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1631616405
1631716406 const err_ty = self.typeOf(un_op);
......@@ -16413,7 +16502,8 @@ fn airErrorName(self: *Self, inst: Air.Inst.Index) !void {
1641316502}
1641416503
1641516504fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
16416 const mod = self.bin_file.comp.module.?;
16505 const pt = self.pt;
16506 const mod = pt.zcu;
1641716507 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1641816508 const vector_ty = self.typeOfIndex(inst);
1641916509 const vector_len = vector_ty.vectorLen(mod);
......@@ -16495,15 +16585,15 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1649516585 const src_mcv = try self.resolveInst(ty_op.operand);
1649616586 if (src_mcv.isMemory()) try self.asmRegisterMemory(
1649716587 mir_tag,
16498 registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod))),
16588 registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt))),
1649916589 try src_mcv.mem(self, self.memSize(scalar_ty)),
1650016590 ) else {
1650116591 if (mir_tag[0] == .v_i128) break :avx2;
1650216592 try self.genSetReg(dst_reg, scalar_ty, src_mcv, .{});
1650316593 try self.asmRegisterRegister(
1650416594 mir_tag,
16505 registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod))),
16506 registerAlias(dst_reg, @intCast(scalar_ty.abiSize(mod))),
16595 registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt))),
16596 registerAlias(dst_reg, @intCast(scalar_ty.abiSize(pt))),
1650716597 );
1650816598 }
1650916599 break :result .{ .register = dst_reg };
......@@ -16515,7 +16605,7 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1651516605 try self.genSetReg(dst_reg, scalar_ty, .{ .air_ref = ty_op.operand }, .{});
1651616606 if (vector_len == 1) break :result .{ .register = dst_reg };
1651716607
16518 const dst_alias = registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod)));
16608 const dst_alias = registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt)));
1651916609 const scalar_bits = scalar_ty.intInfo(mod).bits;
1652016610 if (switch (scalar_bits) {
1652116611 1...8 => true,
......@@ -16745,20 +16835,21 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1674516835 else => unreachable,
1674616836 },
1674716837 }
16748 return self.fail("TODO implement airSplat for {}", .{vector_ty.fmt(mod)});
16838 return self.fail("TODO implement airSplat for {}", .{vector_ty.fmt(pt)});
1674916839 };
1675016840 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
1675116841}
1675216842
1675316843fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
16754 const mod = self.bin_file.comp.module.?;
16844 const pt = self.pt;
16845 const mod = pt.zcu;
1675516846 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
1675616847 const extra = self.air.extraData(Air.Bin, pl_op.payload).data;
1675716848 const ty = self.typeOfIndex(inst);
1675816849 const vec_len = ty.vectorLen(mod);
1675916850 const elem_ty = ty.childType(mod);
16760 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
16761 const abi_size: u32 = @intCast(ty.abiSize(mod));
16851 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
16852 const abi_size: u32 = @intCast(ty.abiSize(pt));
1676216853 const pred_ty = self.typeOf(pl_op.operand);
1676316854
1676416855 const result = result: {
......@@ -16878,17 +16969,17 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1687816969 else => unreachable,
1687916970 }),
1688016971 );
16881 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
16972 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1688216973 const elem_bits: u16 = @intCast(elem_abi_size * 8);
16883 const mask_elem_ty = try mod.intType(.unsigned, elem_bits);
16884 const mask_ty = try mod.vectorType(.{ .len = vec_len, .child = mask_elem_ty.toIntern() });
16974 const mask_elem_ty = try pt.intType(.unsigned, elem_bits);
16975 const mask_ty = try pt.vectorType(.{ .len = vec_len, .child = mask_elem_ty.toIntern() });
1688516976 if (!pred_fits_in_elem) if (self.hasFeature(.ssse3)) {
1688616977 var mask_elems: [32]InternPool.Index = undefined;
16887 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try mod.intern(.{ .int = .{
16978 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try pt.intern(.{ .int = .{
1688816979 .ty = mask_elem_ty.toIntern(),
1688916980 .storage = .{ .u64 = bit / elem_bits },
1689016981 } });
16891 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
16982 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1689216983 .ty = mask_ty.toIntern(),
1689316984 .storage = .{ .elems = mask_elems[0..vec_len] },
1689416985 } })));
......@@ -16906,14 +16997,14 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1690616997 mask_alias,
1690716998 mask_mem,
1690816999 );
16909 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17000 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1691017001 {
1691117002 var mask_elems: [32]InternPool.Index = undefined;
16912 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try mod.intern(.{ .int = .{
17003 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try pt.intern(.{ .int = .{
1691317004 .ty = mask_elem_ty.toIntern(),
1691417005 .storage = .{ .u64 = @as(u32, 1) << @intCast(bit & (elem_bits - 1)) },
1691517006 } });
16916 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17007 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1691717008 .ty = mask_ty.toIntern(),
1691817009 .storage = .{ .elems = mask_elems[0..vec_len] },
1691917010 } })));
......@@ -17014,7 +17105,7 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1701417105 else => null,
1701517106 },
1701617107 },
17017 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17108 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1701817109 if (has_avx) {
1701917110 const rhs_alias = if (rhs_mcv.isRegister())
1702017111 registerAlias(rhs_mcv.getReg().?, abi_size)
......@@ -17061,7 +17152,7 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1706117152 16, 80, 128 => null,
1706217153 else => unreachable,
1706317154 },
17064 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17155 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1706517156 try self.asmRegisterRegister(.{ mir_fixes, .@"and" }, dst_alias, mask_alias);
1706617157 if (rhs_mcv.isMemory()) try self.asmRegisterMemory(
1706717158 .{ mir_fixes, .andn },
......@@ -17083,18 +17174,19 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1708317174}
1708417175
1708517176fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
17086 const mod = self.bin_file.comp.module.?;
17177 const pt = self.pt;
17178 const mod = pt.zcu;
1708717179 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1708817180 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
1708917181
1709017182 const dst_ty = self.typeOfIndex(inst);
1709117183 const elem_ty = dst_ty.childType(mod);
17092 const elem_abi_size: u16 = @intCast(elem_ty.abiSize(mod));
17093 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
17184 const elem_abi_size: u16 = @intCast(elem_ty.abiSize(pt));
17185 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
1709417186 const lhs_ty = self.typeOf(extra.a);
17095 const lhs_abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
17187 const lhs_abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
1709617188 const rhs_ty = self.typeOf(extra.b);
17097 const rhs_abi_size: u32 = @intCast(rhs_ty.abiSize(mod));
17189 const rhs_abi_size: u32 = @intCast(rhs_ty.abiSize(pt));
1709817190 const max_abi_size = @max(dst_abi_size, lhs_abi_size, rhs_abi_size);
1709917191
1710017192 const ExpectedContents = [32]?i32;
......@@ -17106,11 +17198,11 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1710617198 defer allocator.free(mask_elems);
1710717199 for (mask_elems, 0..) |*mask_elem, elem_index| {
1710817200 const mask_elem_val =
17109 Value.fromInterned(extra.mask).elemValue(mod, elem_index) catch unreachable;
17201 Value.fromInterned(extra.mask).elemValue(pt, elem_index) catch unreachable;
1711017202 mask_elem.* = if (mask_elem_val.isUndef(mod))
1711117203 null
1711217204 else
17113 @intCast(mask_elem_val.toSignedInt(mod));
17205 @intCast(mask_elem_val.toSignedInt(pt));
1711417206 }
1711517207
1711617208 const has_avx = self.hasFeature(.avx);
......@@ -17626,8 +17718,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1762617718 else
1762717719 self.hasFeature(.avx2)) 32 else 16)) break :blendv;
1762817720
17629 const select_mask_elem_ty = try mod.intType(.unsigned, elem_abi_size * 8);
17630 const select_mask_ty = try mod.vectorType(.{
17721 const select_mask_elem_ty = try pt.intType(.unsigned, elem_abi_size * 8);
17722 const select_mask_ty = try pt.vectorType(.{
1763117723 .len = @intCast(mask_elems.len),
1763217724 .child = select_mask_elem_ty.toIntern(),
1763317725 });
......@@ -17643,11 +17735,11 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1764317735 if (mask_elem_index != elem_index) break :blendv;
1764417736
1764517737 select_mask_elem.* = (if (mask_elem < 0)
17646 try select_mask_elem_ty.maxIntScalar(mod, select_mask_elem_ty)
17738 try select_mask_elem_ty.maxIntScalar(pt, select_mask_elem_ty)
1764717739 else
17648 try select_mask_elem_ty.minIntScalar(mod, select_mask_elem_ty)).toIntern();
17740 try select_mask_elem_ty.minIntScalar(pt, select_mask_elem_ty)).toIntern();
1764917741 }
17650 const select_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17742 const select_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1765117743 .ty = select_mask_ty.toIntern(),
1765217744 .storage = .{ .elems = select_mask_elems[0..mask_elems.len] },
1765317745 } })));
......@@ -17783,7 +17875,7 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1778317875 var lhs_mask_elems: [16]InternPool.Index = undefined;
1778417876 for (lhs_mask_elems[0..max_abi_size], 0..) |*lhs_mask_elem, byte_index| {
1778517877 const elem_index = byte_index / elem_abi_size;
17786 lhs_mask_elem.* = try mod.intern(.{ .int = .{
17878 lhs_mask_elem.* = try pt.intern(.{ .int = .{
1778717879 .ty = .u8_type,
1778817880 .storage = .{ .u64 = if (elem_index >= mask_elems.len) 0b1_00_00000 else elem: {
1778917881 const mask_elem = mask_elems[elem_index] orelse break :elem 0b1_00_00000;
......@@ -17794,8 +17886,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1779417886 } },
1779517887 } });
1779617888 }
17797 const lhs_mask_ty = try mod.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17798 const lhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17889 const lhs_mask_ty = try pt.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17890 const lhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1779917891 .ty = lhs_mask_ty.toIntern(),
1780017892 .storage = .{ .elems = lhs_mask_elems[0..max_abi_size] },
1780117893 } })));
......@@ -17817,7 +17909,7 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1781717909 var rhs_mask_elems: [16]InternPool.Index = undefined;
1781817910 for (rhs_mask_elems[0..max_abi_size], 0..) |*rhs_mask_elem, byte_index| {
1781917911 const elem_index = byte_index / elem_abi_size;
17820 rhs_mask_elem.* = try mod.intern(.{ .int = .{
17912 rhs_mask_elem.* = try pt.intern(.{ .int = .{
1782117913 .ty = .u8_type,
1782217914 .storage = .{ .u64 = if (elem_index >= mask_elems.len) 0b1_00_00000 else elem: {
1782317915 const mask_elem = mask_elems[elem_index] orelse break :elem 0b1_00_00000;
......@@ -17828,8 +17920,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1782817920 } },
1782917921 } });
1783017922 }
17831 const rhs_mask_ty = try mod.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17832 const rhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17923 const rhs_mask_ty = try pt.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17924 const rhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1783317925 .ty = rhs_mask_ty.toIntern(),
1783417926 .storage = .{ .elems = rhs_mask_elems[0..max_abi_size] },
1783517927 } })));
......@@ -17881,14 +17973,15 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1788117973
1788217974 break :result null;
1788317975 }) orelse return self.fail("TODO implement airShuffle from {} and {} to {} with {}", .{
17884 lhs_ty.fmt(mod), rhs_ty.fmt(mod), dst_ty.fmt(mod),
17885 Value.fromInterned(extra.mask).fmtValue(mod, null),
17976 lhs_ty.fmt(pt), rhs_ty.fmt(pt), dst_ty.fmt(pt),
17977 Value.fromInterned(extra.mask).fmtValue(pt, null),
1788617978 });
1788717979 return self.finishAir(inst, result, .{ extra.a, extra.b, .none });
1788817980}
1788917981
1789017982fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
17891 const mod = self.bin_file.comp.module.?;
17983 const pt = self.pt;
17984 const mod = pt.zcu;
1789217985 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
1789317986
1789417987 const result: MCValue = result: {
......@@ -17898,9 +17991,9 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
1789817991
1789917992 const operand_mcv = try self.resolveInst(reduce.operand);
1790017993 const mask_len = (math.cast(u6, operand_ty.vectorLen(mod)) orelse
17901 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)}));
17994 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)}));
1790217995 const mask = (@as(u64, 1) << mask_len) - 1;
17903 const abi_size: u32 = @intCast(operand_ty.abiSize(mod));
17996 const abi_size: u32 = @intCast(operand_ty.abiSize(pt));
1790417997 switch (reduce.operation) {
1790517998 .Or => {
1790617999 if (operand_mcv.isMemory()) try self.asmMemoryImmediate(
......@@ -17936,16 +18029,17 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
1793618029 try self.asmRegisterRegister(.{ ._, .@"test" }, tmp_reg, tmp_reg);
1793718030 break :result .{ .eflags = .z };
1793818031 },
17939 else => return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)}),
18032 else => return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)}),
1794018033 }
1794118034 }
17942 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)});
18035 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)});
1794318036 };
1794418037 return self.finishAir(inst, result, .{ reduce.operand, .none, .none });
1794518038}
1794618039
1794718040fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
17948 const mod = self.bin_file.comp.module.?;
18041 const pt = self.pt;
18042 const mod = pt.zcu;
1794918043 const result_ty = self.typeOfIndex(inst);
1795018044 const len: usize = @intCast(result_ty.arrayLen(mod));
1795118045 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -17953,30 +18047,30 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1795318047 const result: MCValue = result: {
1795418048 switch (result_ty.zigTypeTag(mod)) {
1795518049 .Struct => {
17956 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, mod));
18050 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
1795718051 if (result_ty.containerLayout(mod) == .@"packed") {
1795818052 const struct_obj = mod.typeToStruct(result_ty).?;
1795918053 try self.genInlineMemset(
1796018054 .{ .lea_frame = .{ .index = frame_index } },
1796118055 .{ .immediate = 0 },
17962 .{ .immediate = result_ty.abiSize(mod) },
18056 .{ .immediate = result_ty.abiSize(pt) },
1796318057 .{},
1796418058 );
1796518059 for (elements, 0..) |elem, elem_i_usize| {
1796618060 const elem_i: u32 = @intCast(elem_i_usize);
17967 if ((try result_ty.structFieldValueComptime(mod, elem_i)) != null) continue;
18061 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
1796818062
1796918063 const elem_ty = result_ty.structFieldType(elem_i, mod);
17970 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(mod));
18064 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(pt));
1797118065 if (elem_bit_size > 64) {
1797218066 return self.fail(
1797318067 "TODO airAggregateInit implement packed structs with large fields",
1797418068 .{},
1797518069 );
1797618070 }
17977 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
18071 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
1797818072 const elem_abi_bits = elem_abi_size * 8;
17979 const elem_off = mod.structPackedFieldBitOffset(struct_obj, elem_i);
18073 const elem_off = pt.structPackedFieldBitOffset(struct_obj, elem_i);
1798018074 const elem_byte_off: i32 = @intCast(elem_off / elem_abi_bits * elem_abi_size);
1798118075 const elem_bit_off = elem_off % elem_abi_bits;
1798218076 const elem_mcv = try self.resolveInst(elem);
......@@ -18046,10 +18140,10 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1804618140 }
1804718141 }
1804818142 } else for (elements, 0..) |elem, elem_i| {
18049 if ((try result_ty.structFieldValueComptime(mod, elem_i)) != null) continue;
18143 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
1805018144
1805118145 const elem_ty = result_ty.structFieldType(elem_i, mod);
18052 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, mod));
18146 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, pt));
1805318147 const elem_mcv = try self.resolveInst(elem);
1805418148 const mat_elem_mcv = switch (elem_mcv) {
1805518149 .load_tlv => |sym_index| MCValue{ .lea_tlv = sym_index },
......@@ -18062,7 +18156,7 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1806218156 .Array, .Vector => {
1806318157 const elem_ty = result_ty.childType(mod);
1806418158 if (result_ty.isVector(mod) and elem_ty.toIntern() == .bool_type) {
18065 const result_size: u32 = @intCast(result_ty.abiSize(mod));
18159 const result_size: u32 = @intCast(result_ty.abiSize(pt));
1806618160 const dst_reg = try self.register_manager.allocReg(inst, abi.RegisterClass.gp);
1806718161 try self.asmRegisterRegister(
1806818162 .{ ._, .xor },
......@@ -18093,8 +18187,8 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1809318187 }
1809418188 break :result .{ .register = dst_reg };
1809518189 } else {
18096 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, mod));
18097 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
18190 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
18191 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
1809818192
1809918193 for (elements, 0..) |elem, elem_i| {
1810018194 const elem_mcv = try self.resolveInst(elem);
......@@ -18136,18 +18230,19 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1813618230}
1813718231
1813818232fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
18139 const mod = self.bin_file.comp.module.?;
18233 const pt = self.pt;
18234 const mod = pt.zcu;
1814018235 const ip = &mod.intern_pool;
1814118236 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1814218237 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
1814318238 const result: MCValue = result: {
1814418239 const union_ty = self.typeOfIndex(inst);
18145 const layout = union_ty.unionGetLayout(mod);
18240 const layout = union_ty.unionGetLayout(pt);
1814618241
1814718242 const src_ty = self.typeOf(extra.init);
1814818243 const src_mcv = try self.resolveInst(extra.init);
1814918244 if (layout.tag_size == 0) {
18150 if (layout.abi_size <= src_ty.abiSize(mod) and
18245 if (layout.abi_size <= src_ty.abiSize(pt) and
1815118246 self.reuseOperand(inst, extra.init, 0, src_mcv)) break :result src_mcv;
1815218247
1815318248 const dst_mcv = try self.allocRegOrMem(inst, true);
......@@ -18161,9 +18256,9 @@ fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
1816118256 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
1816218257 const tag_ty = Type.fromInterned(union_obj.enum_tag_ty);
1816318258 const field_index = tag_ty.enumFieldIndex(field_name, mod).?;
18164 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
18165 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
18166 const tag_int = tag_int_val.toUnsignedInt(mod);
18259 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
18260 const tag_int_val = try tag_val.intFromEnum(tag_ty, pt);
18261 const tag_int = tag_int_val.toUnsignedInt(pt);
1816718262 const tag_off: i32 = if (layout.tag_align.compare(.lt, layout.payload_align))
1816818263 @intCast(layout.payload_size)
1816918264 else
......@@ -18192,7 +18287,8 @@ fn airPrefetch(self: *Self, inst: Air.Inst.Index) !void {
1819218287}
1819318288
1819418289fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
18195 const mod = self.bin_file.comp.module.?;
18290 const pt = self.pt;
18291 const mod = pt.zcu;
1819618292 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
1819718293 const extra = self.air.extraData(Air.Bin, pl_op.payload).data;
1819818294 const ty = self.typeOfIndex(inst);
......@@ -18205,7 +18301,7 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1820518301 else => unreachable,
1820618302 }) {
1820718303 if (ty.zigTypeTag(mod) != .Float) return self.fail("TODO implement airMulAdd for {}", .{
18208 ty.fmt(mod),
18304 ty.fmt(pt),
1820918305 });
1821018306
1821118307 var callee_buf: ["__fma?".len]u8 = undefined;
......@@ -18334,12 +18430,12 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1833418430 else => unreachable,
1833518431 }
1833618432 else
18337 unreachable) orelse return self.fail("TODO implement airMulAdd for {}", .{ty.fmt(mod)});
18433 unreachable) orelse return self.fail("TODO implement airMulAdd for {}", .{ty.fmt(pt)});
1833818434
1833918435 var mops: [3]MCValue = undefined;
1834018436 for (order, mcvs) |mop_index, mcv| mops[mop_index - 1] = mcv;
1834118437
18342 const abi_size: u32 = @intCast(ty.abiSize(mod));
18438 const abi_size: u32 = @intCast(ty.abiSize(pt));
1834318439 const mop1_reg = registerAlias(mops[0].getReg().?, abi_size);
1834418440 const mop2_reg = registerAlias(mops[1].getReg().?, abi_size);
1834518441 if (mops[2].isRegister()) try self.asmRegisterRegisterRegister(
......@@ -18359,9 +18455,10 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1835918455}
1836018456
1836118457fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
18362 const mod = self.bin_file.comp.module.?;
18458 const pt = self.pt;
18459 const mod = pt.zcu;
1836318460 const va_list_ty = self.air.instructions.items(.data)[@intFromEnum(inst)].ty;
18364 const ptr_anyopaque_ty = try mod.singleMutPtrType(Type.anyopaque);
18461 const ptr_anyopaque_ty = try pt.singleMutPtrType(Type.anyopaque);
1836518462
1836618463 const result: MCValue = switch (abi.resolveCallingConvention(
1836718464 self.fn_type.fnCallingConvention(mod),
......@@ -18369,7 +18466,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1836918466 )) {
1837018467 .SysV => result: {
1837118468 const info = self.va_info.sysv;
18372 const dst_fi = try self.allocFrameIndex(FrameAlloc.initSpill(va_list_ty, mod));
18469 const dst_fi = try self.allocFrameIndex(FrameAlloc.initSpill(va_list_ty, pt));
1837318470 var field_off: u31 = 0;
1837418471 // gp_offset: c_uint,
1837518472 try self.genSetMem(
......@@ -18379,7 +18476,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1837918476 .{ .immediate = info.gp_count * 8 },
1838018477 .{},
1838118478 );
18382 field_off += @intCast(Type.c_uint.abiSize(mod));
18479 field_off += @intCast(Type.c_uint.abiSize(pt));
1838318480 // fp_offset: c_uint,
1838418481 try self.genSetMem(
1838518482 .{ .frame = dst_fi },
......@@ -18388,7 +18485,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1838818485 .{ .immediate = abi.SysV.c_abi_int_param_regs.len * 8 + info.fp_count * 16 },
1838918486 .{},
1839018487 );
18391 field_off += @intCast(Type.c_uint.abiSize(mod));
18488 field_off += @intCast(Type.c_uint.abiSize(pt));
1839218489 // overflow_arg_area: *anyopaque,
1839318490 try self.genSetMem(
1839418491 .{ .frame = dst_fi },
......@@ -18397,7 +18494,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1839718494 .{ .lea_frame = info.overflow_arg_area },
1839818495 .{},
1839918496 );
18400 field_off += @intCast(ptr_anyopaque_ty.abiSize(mod));
18497 field_off += @intCast(ptr_anyopaque_ty.abiSize(pt));
1840118498 // reg_save_area: *anyopaque,
1840218499 try self.genSetMem(
1840318500 .{ .frame = dst_fi },
......@@ -18406,7 +18503,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1840618503 .{ .lea_frame = info.reg_save_area },
1840718504 .{},
1840818505 );
18409 field_off += @intCast(ptr_anyopaque_ty.abiSize(mod));
18506 field_off += @intCast(ptr_anyopaque_ty.abiSize(pt));
1841018507 break :result .{ .load_frame = .{ .index = dst_fi } };
1841118508 },
1841218509 .Win64 => return self.fail("TODO implement c_va_start for Win64", .{}),
......@@ -18416,11 +18513,12 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1841618513}
1841718514
1841818515fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
18419 const mod = self.bin_file.comp.module.?;
18516 const pt = self.pt;
18517 const mod = pt.zcu;
1842018518 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1842118519 const ty = self.typeOfIndex(inst);
1842218520 const promote_ty = self.promoteVarArg(ty);
18423 const ptr_anyopaque_ty = try mod.singleMutPtrType(Type.anyopaque);
18521 const ptr_anyopaque_ty = try pt.singleMutPtrType(Type.anyopaque);
1842418522 const unused = self.liveness.isUnused(inst);
1842518523
1842618524 const result: MCValue = switch (abi.resolveCallingConvention(
......@@ -18454,7 +18552,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1845418552 const overflow_arg_area: MCValue = .{ .indirect = .{ .reg = ptr_arg_list_reg, .off = 8 } };
1845518553 const reg_save_area: MCValue = .{ .indirect = .{ .reg = ptr_arg_list_reg, .off = 16 } };
1845618554
18457 const classes = mem.sliceTo(&abi.classifySystemV(promote_ty, mod, self.target.*, .arg), .none);
18555 const classes = mem.sliceTo(&abi.classifySystemV(promote_ty, pt, self.target.*, .arg), .none);
1845818556 switch (classes[0]) {
1845918557 .integer => {
1846018558 assert(classes.len == 1);
......@@ -18489,7 +18587,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1848918587 .base = .{ .reg = addr_reg },
1849018588 .mod = .{ .rm = .{
1849118589 .size = .qword,
18492 .disp = @intCast(@max(promote_ty.abiSize(mod), 8)),
18590 .disp = @intCast(@max(promote_ty.abiSize(pt), 8)),
1849318591 } },
1849418592 });
1849518593 try self.genCopy(
......@@ -18537,7 +18635,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1853718635 .base = .{ .reg = addr_reg },
1853818636 .mod = .{ .rm = .{
1853918637 .size = .qword,
18540 .disp = @intCast(@max(promote_ty.abiSize(mod), 8)),
18638 .disp = @intCast(@max(promote_ty.abiSize(pt), 8)),
1854118639 } },
1854218640 });
1854318641 try self.genCopy(
......@@ -18557,7 +18655,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1855718655 unreachable;
1855818656 },
1855918657 else => return self.fail("TODO implement c_va_arg for {} on SysV", .{
18560 promote_ty.fmt(mod),
18658 promote_ty.fmt(pt),
1856118659 }),
1856218660 }
1856318661
......@@ -18627,11 +18725,11 @@ fn airVaEnd(self: *Self, inst: Air.Inst.Index) !void {
1862718725}
1862818726
1862918727fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!MCValue {
18630 const mod = self.bin_file.comp.module.?;
18728 const pt = self.pt;
1863118729 const ty = self.typeOf(ref);
1863218730
1863318731 // If the type has no codegen bits, no need to store it.
18634 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
18732 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
1863518733
1863618734 const mcv = if (ref.toIndex()) |inst| mcv: {
1863718735 break :mcv self.inst_tracking.getPtr(inst).?.short;
......@@ -18705,8 +18803,8 @@ fn limitImmediateType(self: *Self, operand: Air.Inst.Ref, comptime T: type) !MCV
1870518803}
1870618804
1870718805fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
18708 const mod = self.bin_file.comp.module.?;
18709 return switch (try codegen.genTypedValue(self.bin_file, self.src_loc, val, self.owner.getDecl(mod))) {
18806 const pt = self.pt;
18807 return switch (try codegen.genTypedValue(self.bin_file, pt, self.src_loc, val, self.owner.getDecl(pt.zcu))) {
1871018808 .mcv => |mcv| switch (mcv) {
1871118809 .none => .none,
1871218810 .undef => .undef,
......@@ -18745,7 +18843,8 @@ fn resolveCallingConventionValues(
1874518843 var_args: []const Type,
1874618844 stack_frame_base: FrameIndex,
1874718845) !CallMCValues {
18748 const mod = self.bin_file.comp.module.?;
18846 const pt = self.pt;
18847 const mod = pt.zcu;
1874918848 const ip = &mod.intern_pool;
1875018849 const cc = fn_info.cc;
1875118850 const param_types = try self.gpa.alloc(Type, fn_info.param_types.len + var_args.len);
......@@ -18788,7 +18887,7 @@ fn resolveCallingConventionValues(
1878818887 .SysV => {},
1878918888 .Win64 => {
1879018889 // Align the stack to 16bytes before allocating shadow stack space (if any).
18791 result.stack_byte_count += @intCast(4 * Type.usize.abiSize(mod));
18890 result.stack_byte_count += @intCast(4 * Type.usize.abiSize(pt));
1879218891 },
1879318892 else => unreachable,
1879418893 }
......@@ -18796,7 +18895,7 @@ fn resolveCallingConventionValues(
1879618895 // Return values
1879718896 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
1879818897 result.return_value = InstTracking.init(.unreach);
18799 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
18898 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1880018899 // TODO: is this even possible for C calling convention?
1880118900 result.return_value = InstTracking.init(.none);
1880218901 } else {
......@@ -18804,15 +18903,15 @@ fn resolveCallingConventionValues(
1880418903 var ret_tracking_i: usize = 0;
1880518904
1880618905 const classes = switch (resolved_cc) {
18807 .SysV => mem.sliceTo(&abi.classifySystemV(ret_ty, mod, self.target.*, .ret), .none),
18808 .Win64 => &.{abi.classifyWindows(ret_ty, mod)},
18906 .SysV => mem.sliceTo(&abi.classifySystemV(ret_ty, pt, self.target.*, .ret), .none),
18907 .Win64 => &.{abi.classifyWindows(ret_ty, pt)},
1880918908 else => unreachable,
1881018909 };
1881118910 for (classes) |class| switch (class) {
1881218911 .integer => {
1881318912 const ret_int_reg = registerAlias(
1881418913 abi.getCAbiIntReturnRegs(resolved_cc)[ret_int_reg_i],
18815 @intCast(@min(ret_ty.abiSize(mod), 8)),
18914 @intCast(@min(ret_ty.abiSize(pt), 8)),
1881618915 );
1881718916 ret_int_reg_i += 1;
1881818917
......@@ -18822,7 +18921,7 @@ fn resolveCallingConventionValues(
1882218921 .sse, .float, .float_combine, .win_i128 => {
1882318922 const ret_sse_reg = registerAlias(
1882418923 abi.getCAbiSseReturnRegs(resolved_cc)[ret_sse_reg_i],
18825 @intCast(ret_ty.abiSize(mod)),
18924 @intCast(ret_ty.abiSize(pt)),
1882618925 );
1882718926 ret_sse_reg_i += 1;
1882818927
......@@ -18865,7 +18964,7 @@ fn resolveCallingConventionValues(
1886518964
1886618965 // Input params
1886718966 for (param_types, result.args) |ty, *arg| {
18868 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
18967 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
1886918968 switch (resolved_cc) {
1887018969 .SysV => {},
1887118970 .Win64 => {
......@@ -18879,8 +18978,8 @@ fn resolveCallingConventionValues(
1887918978 var arg_mcv_i: usize = 0;
1888018979
1888118980 const classes = switch (resolved_cc) {
18882 .SysV => mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .arg), .none),
18883 .Win64 => &.{abi.classifyWindows(ty, mod)},
18981 .SysV => mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .arg), .none),
18982 .Win64 => &.{abi.classifyWindows(ty, pt)},
1888418983 else => unreachable,
1888518984 };
1888618985 for (classes) |class| switch (class) {
......@@ -18890,7 +18989,7 @@ fn resolveCallingConventionValues(
1889018989
1889118990 const param_int_reg = registerAlias(
1889218991 abi.getCAbiIntParamRegs(resolved_cc)[param_int_reg_i],
18893 @intCast(@min(ty.abiSize(mod), 8)),
18992 @intCast(@min(ty.abiSize(pt), 8)),
1889418993 );
1889518994 param_int_reg_i += 1;
1889618995
......@@ -18903,7 +19002,7 @@ fn resolveCallingConventionValues(
1890319002
1890419003 const param_sse_reg = registerAlias(
1890519004 abi.getCAbiSseParamRegs(resolved_cc)[param_sse_reg_i],
18906 @intCast(ty.abiSize(mod)),
19005 @intCast(ty.abiSize(pt)),
1890719006 );
1890819007 param_sse_reg_i += 1;
1890919008
......@@ -18916,7 +19015,7 @@ fn resolveCallingConventionValues(
1891619015 .x87, .x87up, .complex_x87, .memory => break,
1891719016 else => unreachable,
1891819017 },
18919 .Win64 => if (ty.abiSize(mod) > 8) {
19018 .Win64 => if (ty.abiSize(pt) > 8) {
1892019019 const param_int_reg =
1892119020 abi.getCAbiIntParamRegs(resolved_cc)[param_int_reg_i].to64();
1892219021 param_int_reg_i += 1;
......@@ -18938,7 +19037,7 @@ fn resolveCallingConventionValues(
1893819037 const frame_elems_len = ty.vectorLen(mod) - remaining_param_int_regs;
1893919038 const frame_elem_size = mem.alignForward(
1894019039 u64,
18941 ty.childType(mod).abiSize(mod),
19040 ty.childType(mod).abiSize(pt),
1894219041 frame_elem_align,
1894319042 );
1894419043 const frame_size: u31 = @intCast(frame_elems_len * frame_elem_size);
......@@ -18962,9 +19061,9 @@ fn resolveCallingConventionValues(
1896219061 continue;
1896319062 }
1896419063
18965 const param_size: u31 = @intCast(ty.abiSize(mod));
19064 const param_size: u31 = @intCast(ty.abiSize(pt));
1896619065 const param_align: u31 =
18967 @intCast(@max(ty.abiAlignment(mod).toByteUnits().?, 8));
19066 @intCast(@max(ty.abiAlignment(pt).toByteUnits().?, 8));
1896819067 result.stack_byte_count =
1896919068 mem.alignForward(u31, result.stack_byte_count, param_align);
1897019069 arg.* = .{ .load_frame = .{
......@@ -18984,11 +19083,11 @@ fn resolveCallingConventionValues(
1898419083 // Return values
1898519084 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
1898619085 result.return_value = InstTracking.init(.unreach);
18987 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
19086 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1898819087 result.return_value = InstTracking.init(.none);
1898919088 } else {
1899019089 const ret_reg = abi.getCAbiIntReturnRegs(resolved_cc)[0];
18991 const ret_ty_size: u31 = @intCast(ret_ty.abiSize(mod));
19090 const ret_ty_size: u31 = @intCast(ret_ty.abiSize(pt));
1899219091 if (ret_ty_size <= 8 and !ret_ty.isRuntimeFloat()) {
1899319092 const aliased_reg = registerAlias(ret_reg, ret_ty_size);
1899419093 result.return_value = .{ .short = .{ .register = aliased_reg }, .long = .none };
......@@ -19003,12 +19102,12 @@ fn resolveCallingConventionValues(
1900319102
1900419103 // Input params
1900519104 for (param_types, result.args) |ty, *arg| {
19006 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {
19105 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
1900719106 arg.* = .none;
1900819107 continue;
1900919108 }
19010 const param_size: u31 = @intCast(ty.abiSize(mod));
19011 const param_align: u31 = @intCast(ty.abiAlignment(mod).toByteUnits().?);
19109 const param_size: u31 = @intCast(ty.abiSize(pt));
19110 const param_align: u31 = @intCast(ty.abiAlignment(pt).toByteUnits().?);
1901219111 result.stack_byte_count =
1901319112 mem.alignForward(u31, result.stack_byte_count, param_align);
1901419113 arg.* = .{ .load_frame = .{
......@@ -19093,47 +19192,49 @@ fn registerAlias(reg: Register, size_bytes: u32) Register {
1909319192}
1909419193
1909519194fn memSize(self: *Self, ty: Type) Memory.Size {
19096 const mod = self.bin_file.comp.module.?;
19195 const pt = self.pt;
19196 const mod = pt.zcu;
1909719197 return switch (ty.zigTypeTag(mod)) {
1909819198 .Float => Memory.Size.fromBitSize(ty.floatBits(self.target.*)),
19099 else => Memory.Size.fromSize(@intCast(ty.abiSize(mod))),
19199 else => Memory.Size.fromSize(@intCast(ty.abiSize(pt))),
1910019200 };
1910119201}
1910219202
1910319203fn splitType(self: *Self, ty: Type) ![2]Type {
19104 const mod = self.bin_file.comp.module.?;
19105 const classes = mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .other), .none);
19204 const pt = self.pt;
19205 const classes = mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .other), .none);
1910619206 var parts: [2]Type = undefined;
1910719207 if (classes.len == 2) for (&parts, classes, 0..) |*part, class, part_i| {
1910819208 part.* = switch (class) {
1910919209 .integer => switch (part_i) {
1911019210 0 => Type.u64,
1911119211 1 => part: {
19112 const elem_size = ty.abiAlignment(mod).minStrict(.@"8").toByteUnits().?;
19113 const elem_ty = try mod.intType(.unsigned, @intCast(elem_size * 8));
19114 break :part switch (@divExact(ty.abiSize(mod) - 8, elem_size)) {
19212 const elem_size = ty.abiAlignment(pt).minStrict(.@"8").toByteUnits().?;
19213 const elem_ty = try pt.intType(.unsigned, @intCast(elem_size * 8));
19214 break :part switch (@divExact(ty.abiSize(pt) - 8, elem_size)) {
1911519215 1 => elem_ty,
19116 else => |len| try mod.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
19216 else => |len| try pt.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
1911719217 };
1911819218 },
1911919219 else => unreachable,
1912019220 },
1912119221 .float => Type.f32,
19122 .float_combine => try mod.arrayType(.{ .len = 2, .child = .f32_type }),
19222 .float_combine => try pt.arrayType(.{ .len = 2, .child = .f32_type }),
1912319223 .sse => Type.f64,
1912419224 else => break,
1912519225 };
19126 } else if (parts[0].abiSize(mod) + parts[1].abiSize(mod) == ty.abiSize(mod)) return parts;
19127 return self.fail("TODO implement splitType for {}", .{ty.fmt(mod)});
19226 } else if (parts[0].abiSize(pt) + parts[1].abiSize(pt) == ty.abiSize(pt)) return parts;
19227 return self.fail("TODO implement splitType for {}", .{ty.fmt(pt)});
1912819228}
1912919229
1913019230/// Truncates the value in the register in place.
1913119231/// Clobbers any remaining bits.
1913219232fn truncateRegister(self: *Self, ty: Type, reg: Register) !void {
19133 const mod = self.bin_file.comp.module.?;
19233 const pt = self.pt;
19234 const mod = pt.zcu;
1913419235 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{
1913519236 .signedness = .unsigned,
19136 .bits = @intCast(ty.bitSize(mod)),
19237 .bits = @intCast(ty.bitSize(pt)),
1913719238 };
1913819239 const shift = math.cast(u6, 64 - int_info.bits % 64) orelse return;
1913919240 try self.spillEflagsIfOccupied();
......@@ -19177,8 +19278,9 @@ fn truncateRegister(self: *Self, ty: Type, reg: Register) !void {
1917719278}
1917819279
1917919280fn regBitSize(self: *Self, ty: Type) u64 {
19180 const mod = self.bin_file.comp.module.?;
19181 const abi_size = ty.abiSize(mod);
19281 const pt = self.pt;
19282 const mod = pt.zcu;
19283 const abi_size = ty.abiSize(pt);
1918219284 return switch (ty.zigTypeTag(mod)) {
1918319285 else => switch (abi_size) {
1918419286 1 => 8,
......@@ -19196,8 +19298,7 @@ fn regBitSize(self: *Self, ty: Type) u64 {
1919619298}
1919719299
1919819300fn regExtraBits(self: *Self, ty: Type) u64 {
19199 const mod = self.bin_file.comp.module.?;
19200 return self.regBitSize(ty) - ty.bitSize(mod);
19301 return self.regBitSize(ty) - ty.bitSize(self.pt);
1920119302}
1920219303
1920319304fn hasFeature(self: *Self, feature: Target.x86.Feature) bool {
......@@ -19211,12 +19312,14 @@ fn hasAllFeatures(self: *Self, features: anytype) bool {
1921119312}
1921219313
1921319314fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
19214 const mod = self.bin_file.comp.module.?;
19315 const pt = self.pt;
19316 const mod = pt.zcu;
1921519317 return self.air.typeOf(inst, &mod.intern_pool);
1921619318}
1921719319
1921819320fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
19219 const mod = self.bin_file.comp.module.?;
19321 const pt = self.pt;
19322 const mod = pt.zcu;
1922019323 return self.air.typeOfIndex(inst, &mod.intern_pool);
1922119324}
1922219325
......@@ -19268,7 +19371,8 @@ fn floatLibcAbiSuffix(ty: Type) []const u8 {
1926819371}
1926919372
1927019373fn promoteInt(self: *Self, ty: Type) Type {
19271 const mod = self.bin_file.comp.module.?;
19374 const pt = self.pt;
19375 const mod = pt.zcu;
1927219376 const int_info: InternPool.Key.IntType = switch (ty.toIntern()) {
1927319377 .bool_type => .{ .signedness = .unsigned, .bits = 1 },
1927419378 else => if (ty.isAbiInt(mod)) ty.intInfo(mod) else return ty,
src/arch/x86_64/Lower.zig+2-4
......@@ -8,7 +8,7 @@ allocator: Allocator,
88mir: Mir,
99cc: std.builtin.CallingConvention,
1010err_msg: ?*ErrorMsg = null,
11src_loc: Module.LazySrcLoc,
11src_loc: Zcu.LazySrcLoc,
1212result_insts_len: u8 = undefined,
1313result_relocs_len: u8 = undefined,
1414result_insts: [
......@@ -657,7 +657,7 @@ const std = @import("std");
657657
658658const Air = @import("../../Air.zig");
659659const Allocator = std.mem.Allocator;
660const ErrorMsg = Module.ErrorMsg;
660const ErrorMsg = Zcu.ErrorMsg;
661661const Immediate = bits.Immediate;
662662const Instruction = encoder.Instruction;
663663const Lower = @This();
......@@ -665,8 +665,6 @@ const Memory = Instruction.Memory;
665665const Mir = @import("Mir.zig");
666666const Mnemonic = Instruction.Mnemonic;
667667const Zcu = @import("../../Zcu.zig");
668/// Deprecated.
669const Module = Zcu;
670668const Operand = Instruction.Operand;
671669const Prefix = Instruction.Prefix;
672670const Register = bits.Register;
src/arch/x86_64/abi.zig+35-35
......@@ -44,7 +44,7 @@ pub const Class = enum {
4444 }
4545};
4646
47pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
47pub fn classifyWindows(ty: Type, pt: Zcu.PerThread) Class {
4848 // https://docs.microsoft.com/en-gb/cpp/build/x64-calling-convention?view=vs-2017
4949 // "There's a strict one-to-one correspondence between a function call's arguments
5050 // and the registers used for those arguments. Any argument that doesn't fit in 8
......@@ -53,7 +53,7 @@ pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
5353 // "All floating point operations are done using the 16 XMM registers."
5454 // "Structs and unions of size 8, 16, 32, or 64 bits, and __m64 types, are passed
5555 // as if they were integers of the same size."
56 switch (ty.zigTypeTag(zcu)) {
56 switch (ty.zigTypeTag(pt.zcu)) {
5757 .Pointer,
5858 .Int,
5959 .Bool,
......@@ -68,12 +68,12 @@ pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
6868 .ErrorUnion,
6969 .AnyFrame,
7070 .Frame,
71 => switch (ty.abiSize(zcu)) {
71 => switch (ty.abiSize(pt)) {
7272 0 => unreachable,
7373 1, 2, 4, 8 => return .integer,
74 else => switch (ty.zigTypeTag(zcu)) {
74 else => switch (ty.zigTypeTag(pt.zcu)) {
7575 .Int => return .win_i128,
76 .Struct, .Union => if (ty.containerLayout(zcu) == .@"packed") {
76 .Struct, .Union => if (ty.containerLayout(pt.zcu) == .@"packed") {
7777 return .win_i128;
7878 } else {
7979 return .memory;
......@@ -100,14 +100,14 @@ pub const Context = enum { ret, arg, field, other };
100100
101101/// There are a maximum of 8 possible return slots. Returned values are in
102102/// the beginning of the array; unused slots are filled with .none.
103pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8]Class {
103pub fn classifySystemV(ty: Type, pt: Zcu.PerThread, target: std.Target, ctx: Context) [8]Class {
104104 const memory_class = [_]Class{
105105 .memory, .none, .none, .none,
106106 .none, .none, .none, .none,
107107 };
108108 var result = [1]Class{.none} ** 8;
109 switch (ty.zigTypeTag(zcu)) {
110 .Pointer => switch (ty.ptrSize(zcu)) {
109 switch (ty.zigTypeTag(pt.zcu)) {
110 .Pointer => switch (ty.ptrSize(pt.zcu)) {
111111 .Slice => {
112112 result[0] = .integer;
113113 result[1] = .integer;
......@@ -119,7 +119,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
119119 },
120120 },
121121 .Int, .Enum, .ErrorSet => {
122 const bits = ty.intInfo(zcu).bits;
122 const bits = ty.intInfo(pt.zcu).bits;
123123 if (bits <= 64) {
124124 result[0] = .integer;
125125 return result;
......@@ -185,8 +185,8 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
185185 else => unreachable,
186186 },
187187 .Vector => {
188 const elem_ty = ty.childType(zcu);
189 const bits = elem_ty.bitSize(zcu) * ty.arrayLen(zcu);
188 const elem_ty = ty.childType(pt.zcu);
189 const bits = elem_ty.bitSize(pt) * ty.arrayLen(pt.zcu);
190190 if (elem_ty.toIntern() == .bool_type) {
191191 if (bits <= 32) return .{
192192 .integer, .none, .none, .none,
......@@ -250,7 +250,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
250250 return memory_class;
251251 },
252252 .Optional => {
253 if (ty.isPtrLikeOptional(zcu)) {
253 if (ty.isPtrLikeOptional(pt.zcu)) {
254254 result[0] = .integer;
255255 return result;
256256 }
......@@ -261,8 +261,8 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
261261 // it contains unaligned fields, it has class MEMORY"
262262 // "If the size of the aggregate exceeds a single eightbyte, each is classified
263263 // separately.".
264 const ty_size = ty.abiSize(zcu);
265 switch (ty.containerLayout(zcu)) {
264 const ty_size = ty.abiSize(pt);
265 switch (ty.containerLayout(pt.zcu)) {
266266 .auto, .@"extern" => {},
267267 .@"packed" => {
268268 assert(ty_size <= 16);
......@@ -274,10 +274,10 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
274274 if (ty_size > 64)
275275 return memory_class;
276276
277 _ = if (zcu.typeToStruct(ty)) |loaded_struct|
278 classifySystemVStruct(&result, 0, loaded_struct, zcu, target)
279 else if (zcu.typeToUnion(ty)) |loaded_union|
280 classifySystemVUnion(&result, 0, loaded_union, zcu, target)
277 _ = if (pt.zcu.typeToStruct(ty)) |loaded_struct|
278 classifySystemVStruct(&result, 0, loaded_struct, pt, target)
279 else if (pt.zcu.typeToUnion(ty)) |loaded_union|
280 classifySystemVUnion(&result, 0, loaded_union, pt, target)
281281 else
282282 unreachable;
283283
......@@ -306,7 +306,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
306306 return result;
307307 },
308308 .Array => {
309 const ty_size = ty.abiSize(zcu);
309 const ty_size = ty.abiSize(pt);
310310 if (ty_size <= 8) {
311311 result[0] = .integer;
312312 return result;
......@@ -326,10 +326,10 @@ fn classifySystemVStruct(
326326 result: *[8]Class,
327327 starting_byte_offset: u64,
328328 loaded_struct: InternPool.LoadedStructType,
329 zcu: *Zcu,
329 pt: Zcu.PerThread,
330330 target: std.Target,
331331) u64 {
332 const ip = &zcu.intern_pool;
332 const ip = &pt.zcu.intern_pool;
333333 var byte_offset = starting_byte_offset;
334334 var field_it = loaded_struct.iterateRuntimeOrder(ip);
335335 while (field_it.next()) |field_index| {
......@@ -338,29 +338,29 @@ fn classifySystemVStruct(
338338 byte_offset = std.mem.alignForward(
339339 u64,
340340 byte_offset,
341 field_align.toByteUnits() orelse field_ty.abiAlignment(zcu).toByteUnits().?,
341 field_align.toByteUnits() orelse field_ty.abiAlignment(pt).toByteUnits().?,
342342 );
343 if (zcu.typeToStruct(field_ty)) |field_loaded_struct| {
343 if (pt.zcu.typeToStruct(field_ty)) |field_loaded_struct| {
344344 switch (field_loaded_struct.layout) {
345345 .auto, .@"extern" => {
346 byte_offset = classifySystemVStruct(result, byte_offset, field_loaded_struct, zcu, target);
346 byte_offset = classifySystemVStruct(result, byte_offset, field_loaded_struct, pt, target);
347347 continue;
348348 },
349349 .@"packed" => {},
350350 }
351 } else if (zcu.typeToUnion(field_ty)) |field_loaded_union| {
351 } else if (pt.zcu.typeToUnion(field_ty)) |field_loaded_union| {
352352 switch (field_loaded_union.getLayout(ip)) {
353353 .auto, .@"extern" => {
354 byte_offset = classifySystemVUnion(result, byte_offset, field_loaded_union, zcu, target);
354 byte_offset = classifySystemVUnion(result, byte_offset, field_loaded_union, pt, target);
355355 continue;
356356 },
357357 .@"packed" => {},
358358 }
359359 }
360 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, zcu, target, .field), .none);
360 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, pt, target, .field), .none);
361361 for (result[@intCast(byte_offset / 8)..][0..field_classes.len], field_classes) |*result_class, field_class|
362362 result_class.* = result_class.combineSystemV(field_class);
363 byte_offset += field_ty.abiSize(zcu);
363 byte_offset += field_ty.abiSize(pt);
364364 }
365365 const final_byte_offset = starting_byte_offset + loaded_struct.size(ip).*;
366366 std.debug.assert(final_byte_offset == std.mem.alignForward(
......@@ -375,30 +375,30 @@ fn classifySystemVUnion(
375375 result: *[8]Class,
376376 starting_byte_offset: u64,
377377 loaded_union: InternPool.LoadedUnionType,
378 zcu: *Zcu,
378 pt: Zcu.PerThread,
379379 target: std.Target,
380380) u64 {
381 const ip = &zcu.intern_pool;
381 const ip = &pt.zcu.intern_pool;
382382 for (0..loaded_union.field_types.len) |field_index| {
383383 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
384 if (zcu.typeToStruct(field_ty)) |field_loaded_struct| {
384 if (pt.zcu.typeToStruct(field_ty)) |field_loaded_struct| {
385385 switch (field_loaded_struct.layout) {
386386 .auto, .@"extern" => {
387 _ = classifySystemVStruct(result, starting_byte_offset, field_loaded_struct, zcu, target);
387 _ = classifySystemVStruct(result, starting_byte_offset, field_loaded_struct, pt, target);
388388 continue;
389389 },
390390 .@"packed" => {},
391391 }
392 } else if (zcu.typeToUnion(field_ty)) |field_loaded_union| {
392 } else if (pt.zcu.typeToUnion(field_ty)) |field_loaded_union| {
393393 switch (field_loaded_union.getLayout(ip)) {
394394 .auto, .@"extern" => {
395 _ = classifySystemVUnion(result, starting_byte_offset, field_loaded_union, zcu, target);
395 _ = classifySystemVUnion(result, starting_byte_offset, field_loaded_union, pt, target);
396396 continue;
397397 },
398398 .@"packed" => {},
399399 }
400400 }
401 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, zcu, target, .field), .none);
401 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, pt, target, .field), .none);
402402 for (result[@intCast(starting_byte_offset / 8)..][0..field_classes.len], field_classes) |*result_class, field_class|
403403 result_class.* = result_class.combineSystemV(field_class);
404404 }
src/codegen.zig+140-129
......@@ -13,12 +13,10 @@ const trace = @import("tracy.zig").trace;
1313const Air = @import("Air.zig");
1414const Allocator = mem.Allocator;
1515const Compilation = @import("Compilation.zig");
16const ErrorMsg = Module.ErrorMsg;
16const ErrorMsg = Zcu.ErrorMsg;
1717const InternPool = @import("InternPool.zig");
1818const Liveness = @import("Liveness.zig");
1919const Zcu = @import("Zcu.zig");
20/// Deprecated.
21const Module = Zcu;
2220const Target = std.Target;
2321const Type = @import("Type.zig");
2422const Value = @import("Value.zig");
......@@ -47,14 +45,15 @@ pub const DebugInfoOutput = union(enum) {
4745
4846pub fn generateFunction(
4947 lf: *link.File,
50 src_loc: Module.LazySrcLoc,
48 pt: Zcu.PerThread,
49 src_loc: Zcu.LazySrcLoc,
5150 func_index: InternPool.Index,
5251 air: Air,
5352 liveness: Liveness,
5453 code: *std.ArrayList(u8),
5554 debug_output: DebugInfoOutput,
5655) CodeGenError!Result {
57 const zcu = lf.comp.module.?;
56 const zcu = pt.zcu;
5857 const func = zcu.funcInfo(func_index);
5958 const decl = zcu.declPtr(func.owner_decl);
6059 const namespace = zcu.namespacePtr(decl.src_namespace);
......@@ -62,35 +61,36 @@ pub fn generateFunction(
6261 switch (target.cpu.arch) {
6362 .arm,
6463 .armeb,
65 => return @import("arch/arm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
64 => return @import("arch/arm/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
6665 .aarch64,
6766 .aarch64_be,
6867 .aarch64_32,
69 => return @import("arch/aarch64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
70 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
71 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
72 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
68 => return @import("arch/aarch64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
69 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
70 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
71 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
7372 .wasm32,
7473 .wasm64,
75 => return @import("arch/wasm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
74 => return @import("arch/wasm/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
7675 else => unreachable,
7776 }
7877}
7978
8079pub fn generateLazyFunction(
8180 lf: *link.File,
82 src_loc: Module.LazySrcLoc,
81 pt: Zcu.PerThread,
82 src_loc: Zcu.LazySrcLoc,
8383 lazy_sym: link.File.LazySymbol,
8484 code: *std.ArrayList(u8),
8585 debug_output: DebugInfoOutput,
8686) CodeGenError!Result {
87 const zcu = lf.comp.module.?;
87 const zcu = pt.zcu;
8888 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
8989 const decl = zcu.declPtr(decl_index);
9090 const namespace = zcu.namespacePtr(decl.src_namespace);
9191 const target = namespace.fileScope(zcu).mod.resolved_target.result;
9292 switch (target.cpu.arch) {
93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),
93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, pt, src_loc, lazy_sym, code, debug_output),
9494 else => unreachable,
9595 }
9696}
......@@ -105,7 +105,8 @@ fn writeFloat(comptime F: type, f: F, target: Target, endian: std.builtin.Endian
105105
106106pub fn generateLazySymbol(
107107 bin_file: *link.File,
108 src_loc: Module.LazySrcLoc,
108 pt: Zcu.PerThread,
109 src_loc: Zcu.LazySrcLoc,
109110 lazy_sym: link.File.LazySymbol,
110111 // TODO don't use an "out" parameter like this; put it in the result instead
111112 alignment: *Alignment,
......@@ -119,25 +120,24 @@ pub fn generateLazySymbol(
119120 defer tracy.end();
120121
121122 const comp = bin_file.comp;
122 const zcu = comp.module.?;
123 const ip = &zcu.intern_pool;
123 const ip = &pt.zcu.intern_pool;
124124 const target = comp.root_mod.resolved_target.result;
125125 const endian = target.cpu.arch.endian();
126126 const gpa = comp.gpa;
127127
128128 log.debug("generateLazySymbol: kind = {s}, ty = {}", .{
129129 @tagName(lazy_sym.kind),
130 lazy_sym.ty.fmt(zcu),
130 lazy_sym.ty.fmt(pt),
131131 });
132132
133133 if (lazy_sym.kind == .code) {
134134 alignment.* = target_util.defaultFunctionAlignment(target);
135 return generateLazyFunction(bin_file, src_loc, lazy_sym, code, debug_output);
135 return generateLazyFunction(bin_file, pt, src_loc, lazy_sym, code, debug_output);
136136 }
137137
138 if (lazy_sym.ty.isAnyError(zcu)) {
138 if (lazy_sym.ty.isAnyError(pt.zcu)) {
139139 alignment.* = .@"4";
140 const err_names = zcu.global_error_set.keys();
140 const err_names = pt.zcu.global_error_set.keys();
141141 mem.writeInt(u32, try code.addManyAsArray(4), @intCast(err_names.len), endian);
142142 var offset = code.items.len;
143143 try code.resize((1 + err_names.len + 1) * 4);
......@@ -151,9 +151,9 @@ pub fn generateLazySymbol(
151151 }
152152 mem.writeInt(u32, code.items[offset..][0..4], @intCast(code.items.len), endian);
153153 return Result.ok;
154 } else if (lazy_sym.ty.zigTypeTag(zcu) == .Enum) {
154 } else if (lazy_sym.ty.zigTypeTag(pt.zcu) == .Enum) {
155155 alignment.* = .@"1";
156 const tag_names = lazy_sym.ty.enumFields(zcu);
156 const tag_names = lazy_sym.ty.enumFields(pt.zcu);
157157 for (0..tag_names.len) |tag_index| {
158158 const tag_name = tag_names.get(ip)[tag_index].toSlice(ip);
159159 try code.ensureUnusedCapacity(tag_name.len + 1);
......@@ -165,13 +165,14 @@ pub fn generateLazySymbol(
165165 gpa,
166166 src_loc,
167167 "TODO implement generateLazySymbol for {s} {}",
168 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(zcu) },
168 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(pt) },
169169 ) };
170170}
171171
172172pub fn generateSymbol(
173173 bin_file: *link.File,
174 src_loc: Module.LazySrcLoc,
174 pt: Zcu.PerThread,
175 src_loc: Zcu.LazySrcLoc,
175176 val: Value,
176177 code: *std.ArrayList(u8),
177178 debug_output: DebugInfoOutput,
......@@ -180,17 +181,17 @@ pub fn generateSymbol(
180181 const tracy = trace(@src());
181182 defer tracy.end();
182183
183 const mod = bin_file.comp.module.?;
184 const mod = pt.zcu;
184185 const ip = &mod.intern_pool;
185186 const ty = val.typeOf(mod);
186187
187188 const target = mod.getTarget();
188189 const endian = target.cpu.arch.endian();
189190
190 log.debug("generateSymbol: val = {}", .{val.fmtValue(mod, null)});
191 log.debug("generateSymbol: val = {}", .{val.fmtValue(pt, null)});
191192
192193 if (val.isUndefDeep(mod)) {
193 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
194 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
194195 try code.appendNTimes(0xaa, abi_size);
195196 return .ok;
196197 }
......@@ -236,9 +237,9 @@ pub fn generateSymbol(
236237 .empty_enum_value,
237238 => unreachable, // non-runtime values
238239 .int => {
239 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
240 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
240241 var space: Value.BigIntSpace = undefined;
241 const int_val = val.toBigInt(&space, mod);
242 const int_val = val.toBigInt(&space, pt);
242243 int_val.writeTwosComplement(try code.addManyAsSlice(abi_size), endian);
243244 },
244245 .err => |err| {
......@@ -252,14 +253,14 @@ pub fn generateSymbol(
252253 .payload => 0,
253254 };
254255
255 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
256 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
256257 try code.writer().writeInt(u16, err_val, endian);
257258 return .ok;
258259 }
259260
260 const payload_align = payload_ty.abiAlignment(mod);
261 const error_align = Type.anyerror.abiAlignment(mod);
262 const abi_align = ty.abiAlignment(mod);
261 const payload_align = payload_ty.abiAlignment(pt);
262 const error_align = Type.anyerror.abiAlignment(pt);
263 const abi_align = ty.abiAlignment(pt);
263264
264265 // error value first when its type is larger than the error union's payload
265266 if (error_align.order(payload_align) == .gt) {
......@@ -269,8 +270,8 @@ pub fn generateSymbol(
269270 // emit payload part of the error union
270271 {
271272 const begin = code.items.len;
272 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (error_union.val) {
273 .err_name => try mod.intern(.{ .undef = payload_ty.toIntern() }),
273 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (error_union.val) {
274 .err_name => try pt.intern(.{ .undef = payload_ty.toIntern() }),
274275 .payload => |payload| payload,
275276 }), code, debug_output, reloc_info)) {
276277 .ok => {},
......@@ -300,7 +301,7 @@ pub fn generateSymbol(
300301 },
301302 .enum_tag => |enum_tag| {
302303 const int_tag_ty = ty.intTagType(mod);
303 switch (try generateSymbol(bin_file, src_loc, try mod.getCoerced(Value.fromInterned(enum_tag.int), int_tag_ty), code, debug_output, reloc_info)) {
304 switch (try generateSymbol(bin_file, pt, src_loc, try pt.getCoerced(Value.fromInterned(enum_tag.int), int_tag_ty), code, debug_output, reloc_info)) {
304305 .ok => {},
305306 .fail => |em| return .{ .fail = em },
306307 }
......@@ -311,21 +312,21 @@ pub fn generateSymbol(
311312 .f64 => |f64_val| writeFloat(f64, f64_val, target, endian, try code.addManyAsArray(8)),
312313 .f80 => |f80_val| {
313314 writeFloat(f80, f80_val, target, endian, try code.addManyAsArray(10));
314 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
315 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
315316 try code.appendNTimes(0, abi_size - 10);
316317 },
317318 .f128 => |f128_val| writeFloat(f128, f128_val, target, endian, try code.addManyAsArray(16)),
318319 },
319 .ptr => switch (try lowerPtr(bin_file, src_loc, val.toIntern(), code, debug_output, reloc_info, 0)) {
320 .ptr => switch (try lowerPtr(bin_file, pt, src_loc, val.toIntern(), code, debug_output, reloc_info, 0)) {
320321 .ok => {},
321322 .fail => |em| return .{ .fail = em },
322323 },
323324 .slice => |slice| {
324 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(slice.ptr), code, debug_output, reloc_info)) {
325 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(slice.ptr), code, debug_output, reloc_info)) {
325326 .ok => {},
326327 .fail => |em| return .{ .fail = em },
327328 }
328 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(slice.len), code, debug_output, reloc_info)) {
329 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(slice.len), code, debug_output, reloc_info)) {
329330 .ok => {},
330331 .fail => |em| return .{ .fail = em },
331332 }
......@@ -333,11 +334,11 @@ pub fn generateSymbol(
333334 .opt => {
334335 const payload_type = ty.optionalChild(mod);
335336 const payload_val = val.optionalValue(mod);
336 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
337 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
337338
338339 if (ty.optionalReprIsPayload(mod)) {
339340 if (payload_val) |value| {
340 switch (try generateSymbol(bin_file, src_loc, value, code, debug_output, reloc_info)) {
341 switch (try generateSymbol(bin_file, pt, src_loc, value, code, debug_output, reloc_info)) {
341342 .ok => {},
342343 .fail => |em| return Result{ .fail = em },
343344 }
......@@ -345,10 +346,12 @@ pub fn generateSymbol(
345346 try code.appendNTimes(0, abi_size);
346347 }
347348 } else {
348 const padding = abi_size - (math.cast(usize, payload_type.abiSize(mod)) orelse return error.Overflow) - 1;
349 if (payload_type.hasRuntimeBits(mod)) {
350 const value = payload_val orelse Value.fromInterned((try mod.intern(.{ .undef = payload_type.toIntern() })));
351 switch (try generateSymbol(bin_file, src_loc, value, code, debug_output, reloc_info)) {
349 const padding = abi_size - (math.cast(usize, payload_type.abiSize(pt)) orelse return error.Overflow) - 1;
350 if (payload_type.hasRuntimeBits(pt)) {
351 const value = payload_val orelse Value.fromInterned(try pt.intern(.{
352 .undef = payload_type.toIntern(),
353 }));
354 switch (try generateSymbol(bin_file, pt, src_loc, value, code, debug_output, reloc_info)) {
352355 .ok => {},
353356 .fail => |em| return Result{ .fail = em },
354357 }
......@@ -363,7 +366,7 @@ pub fn generateSymbol(
363366 .elems, .repeated_elem => {
364367 var index: u64 = 0;
365368 while (index < array_type.lenIncludingSentinel()) : (index += 1) {
366 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (aggregate.storage) {
369 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (aggregate.storage) {
367370 .bytes => unreachable,
368371 .elems => |elems| elems[@intCast(index)],
369372 .repeated_elem => |elem| if (index < array_type.len)
......@@ -378,8 +381,7 @@ pub fn generateSymbol(
378381 },
379382 },
380383 .vector_type => |vector_type| {
381 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse
382 return error.Overflow;
384 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
383385 if (vector_type.child == .bool_type) {
384386 const bytes = try code.addManyAsSlice(abi_size);
385387 @memset(bytes, 0xaa);
......@@ -424,7 +426,7 @@ pub fn generateSymbol(
424426 .elems, .repeated_elem => {
425427 var index: u64 = 0;
426428 while (index < vector_type.len) : (index += 1) {
427 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (aggregate.storage) {
429 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (aggregate.storage) {
428430 .bytes => unreachable,
429431 .elems => |elems| elems[
430432 math.cast(usize, index) orelse return error.Overflow
......@@ -439,7 +441,7 @@ pub fn generateSymbol(
439441 }
440442
441443 const padding = abi_size -
442 (math.cast(usize, Type.fromInterned(vector_type.child).abiSize(mod) * vector_type.len) orelse
444 (math.cast(usize, Type.fromInterned(vector_type.child).abiSize(pt) * vector_type.len) orelse
443445 return error.Overflow);
444446 if (padding > 0) try code.appendNTimes(0, padding);
445447 }
......@@ -452,10 +454,10 @@ pub fn generateSymbol(
452454 0..,
453455 ) |field_ty, comptime_val, index| {
454456 if (comptime_val != .none) continue;
455 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
457 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
456458
457459 const field_val = switch (aggregate.storage) {
458 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
460 .bytes => |bytes| try pt.intern(.{ .int = .{
459461 .ty = field_ty,
460462 .storage = .{ .u64 = bytes.at(index, ip) },
461463 } }),
......@@ -463,14 +465,14 @@ pub fn generateSymbol(
463465 .repeated_elem => |elem| elem,
464466 };
465467
466 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
468 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
467469 .ok => {},
468470 .fail => |em| return Result{ .fail = em },
469471 }
470472 const unpadded_field_end = code.items.len - struct_begin;
471473
472474 // Pad struct members if required
473 const padded_field_end = ty.structFieldOffset(index + 1, mod);
475 const padded_field_end = ty.structFieldOffset(index + 1, pt);
474476 const padding = math.cast(usize, padded_field_end - unpadded_field_end) orelse
475477 return error.Overflow;
476478
......@@ -483,15 +485,14 @@ pub fn generateSymbol(
483485 const struct_type = ip.loadStructType(ty.toIntern());
484486 switch (struct_type.layout) {
485487 .@"packed" => {
486 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse
487 return error.Overflow;
488 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
488489 const current_pos = code.items.len;
489490 try code.appendNTimes(0, abi_size);
490491 var bits: u16 = 0;
491492
492493 for (struct_type.field_types.get(ip), 0..) |field_ty, index| {
493494 const field_val = switch (aggregate.storage) {
494 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
495 .bytes => |bytes| try pt.intern(.{ .int = .{
495496 .ty = field_ty,
496497 .storage = .{ .u64 = bytes.at(index, ip) },
497498 } }),
......@@ -502,18 +503,18 @@ pub fn generateSymbol(
502503 // pointer may point to a decl which must be marked used
503504 // but can also result in a relocation. Therefore we handle those separately.
504505 if (Type.fromInterned(field_ty).zigTypeTag(mod) == .Pointer) {
505 const field_size = math.cast(usize, Type.fromInterned(field_ty).abiSize(mod)) orelse
506 const field_size = math.cast(usize, Type.fromInterned(field_ty).abiSize(pt)) orelse
506507 return error.Overflow;
507508 var tmp_list = try std.ArrayList(u8).initCapacity(code.allocator, field_size);
508509 defer tmp_list.deinit();
509 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), &tmp_list, debug_output, reloc_info)) {
510 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), &tmp_list, debug_output, reloc_info)) {
510511 .ok => @memcpy(code.items[current_pos..][0..tmp_list.items.len], tmp_list.items),
511512 .fail => |em| return Result{ .fail = em },
512513 }
513514 } else {
514 Value.fromInterned(field_val).writeToPackedMemory(Type.fromInterned(field_ty), mod, code.items[current_pos..], bits) catch unreachable;
515 Value.fromInterned(field_val).writeToPackedMemory(Type.fromInterned(field_ty), pt, code.items[current_pos..], bits) catch unreachable;
515516 }
516 bits += @intCast(Type.fromInterned(field_ty).bitSize(mod));
517 bits += @intCast(Type.fromInterned(field_ty).bitSize(pt));
517518 }
518519 },
519520 .auto, .@"extern" => {
......@@ -524,10 +525,10 @@ pub fn generateSymbol(
524525 var it = struct_type.iterateRuntimeOrder(ip);
525526 while (it.next()) |field_index| {
526527 const field_ty = field_types[field_index];
527 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
528 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
528529
529530 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
530 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
531 .bytes => |bytes| try pt.intern(.{ .int = .{
531532 .ty = field_ty,
532533 .storage = .{ .u64 = bytes.at(field_index, ip) },
533534 } }),
......@@ -541,7 +542,7 @@ pub fn generateSymbol(
541542 ) orelse return error.Overflow;
542543 if (padding > 0) try code.appendNTimes(0, padding);
543544
544 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
545 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
545546 .ok => {},
546547 .fail => |em| return Result{ .fail = em },
547548 }
......@@ -562,15 +563,15 @@ pub fn generateSymbol(
562563 else => unreachable,
563564 },
564565 .un => |un| {
565 const layout = ty.unionGetLayout(mod);
566 const layout = ty.unionGetLayout(pt);
566567
567568 if (layout.payload_size == 0) {
568 return generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info);
569 return generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info);
569570 }
570571
571572 // Check if we should store the tag first.
572573 if (layout.tag_size > 0 and layout.tag_align.compare(.gte, layout.payload_align)) {
573 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
574 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
574575 .ok => {},
575576 .fail => |em| return Result{ .fail = em },
576577 }
......@@ -580,28 +581,28 @@ pub fn generateSymbol(
580581 if (un.tag != .none) {
581582 const field_index = ty.unionTagFieldIndex(Value.fromInterned(un.tag), mod).?;
582583 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
583 if (!field_ty.hasRuntimeBits(mod)) {
584 if (!field_ty.hasRuntimeBits(pt)) {
584585 try code.appendNTimes(0xaa, math.cast(usize, layout.payload_size) orelse return error.Overflow);
585586 } else {
586 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
587 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
587588 .ok => {},
588589 .fail => |em| return Result{ .fail = em },
589590 }
590591
591 const padding = math.cast(usize, layout.payload_size - field_ty.abiSize(mod)) orelse return error.Overflow;
592 const padding = math.cast(usize, layout.payload_size - field_ty.abiSize(pt)) orelse return error.Overflow;
592593 if (padding > 0) {
593594 try code.appendNTimes(0, padding);
594595 }
595596 }
596597 } else {
597 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
598 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
598599 .ok => {},
599600 .fail => |em| return Result{ .fail = em },
600601 }
601602 }
602603
603604 if (layout.tag_size > 0 and layout.tag_align.compare(.lt, layout.payload_align)) {
604 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
605 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
605606 .ok => {},
606607 .fail => |em| return Result{ .fail = em },
607608 }
......@@ -618,22 +619,24 @@ pub fn generateSymbol(
618619
619620fn lowerPtr(
620621 bin_file: *link.File,
621 src_loc: Module.LazySrcLoc,
622 pt: Zcu.PerThread,
623 src_loc: Zcu.LazySrcLoc,
622624 ptr_val: InternPool.Index,
623625 code: *std.ArrayList(u8),
624626 debug_output: DebugInfoOutput,
625627 reloc_info: RelocInfo,
626628 prev_offset: u64,
627629) CodeGenError!Result {
628 const zcu = bin_file.comp.module.?;
630 const zcu = pt.zcu;
629631 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
630632 const offset: u64 = prev_offset + ptr.byte_offset;
631633 return switch (ptr.base_addr) {
632 .decl => |decl| try lowerDeclRef(bin_file, src_loc, decl, code, debug_output, reloc_info, offset),
633 .anon_decl => |ad| try lowerAnonDeclRef(bin_file, src_loc, ad, code, debug_output, reloc_info, offset),
634 .int => try generateSymbol(bin_file, src_loc, try zcu.intValue(Type.usize, offset), code, debug_output, reloc_info),
634 .decl => |decl| try lowerDeclRef(bin_file, pt, src_loc, decl, code, debug_output, reloc_info, offset),
635 .anon_decl => |ad| try lowerAnonDeclRef(bin_file, pt, src_loc, ad, code, debug_output, reloc_info, offset),
636 .int => try generateSymbol(bin_file, pt, src_loc, try pt.intValue(Type.usize, offset), code, debug_output, reloc_info),
635637 .eu_payload => |eu_ptr| try lowerPtr(
636638 bin_file,
639 pt,
637640 src_loc,
638641 eu_ptr,
639642 code,
......@@ -641,11 +644,12 @@ fn lowerPtr(
641644 reloc_info,
642645 offset + errUnionPayloadOffset(
643646 Value.fromInterned(eu_ptr).typeOf(zcu).childType(zcu).errorUnionPayload(zcu),
644 zcu,
647 pt,
645648 ),
646649 ),
647650 .opt_payload => |opt_ptr| try lowerPtr(
648651 bin_file,
652 pt,
649653 src_loc,
650654 opt_ptr,
651655 code,
......@@ -666,12 +670,12 @@ fn lowerPtr(
666670 };
667671 },
668672 .Struct, .Union => switch (base_ty.containerLayout(zcu)) {
669 .auto => base_ty.structFieldOffset(@intCast(field.index), zcu),
673 .auto => base_ty.structFieldOffset(@intCast(field.index), pt),
670674 .@"extern", .@"packed" => unreachable,
671675 },
672676 else => unreachable,
673677 };
674 return lowerPtr(bin_file, src_loc, field.base, code, debug_output, reloc_info, offset + field_off);
678 return lowerPtr(bin_file, pt, src_loc, field.base, code, debug_output, reloc_info, offset + field_off);
675679 },
676680 .arr_elem, .comptime_field, .comptime_alloc => unreachable,
677681 };
......@@ -683,7 +687,8 @@ const RelocInfo = struct {
683687
684688fn lowerAnonDeclRef(
685689 lf: *link.File,
686 src_loc: Module.LazySrcLoc,
690 pt: Zcu.PerThread,
691 src_loc: Zcu.LazySrcLoc,
687692 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
688693 code: *std.ArrayList(u8),
689694 debug_output: DebugInfoOutput,
......@@ -691,22 +696,21 @@ fn lowerAnonDeclRef(
691696 offset: u64,
692697) CodeGenError!Result {
693698 _ = debug_output;
694 const zcu = lf.comp.module.?;
695 const ip = &zcu.intern_pool;
699 const ip = &pt.zcu.intern_pool;
696700 const target = lf.comp.root_mod.resolved_target.result;
697701
698702 const ptr_width_bytes = @divExact(target.ptrBitWidth(), 8);
699703 const decl_val = anon_decl.val;
700704 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));
701 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(zcu)});
702 const is_fn_body = decl_ty.zigTypeTag(zcu) == .Fn;
703 if (!is_fn_body and !decl_ty.hasRuntimeBits(zcu)) {
705 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(pt)});
706 const is_fn_body = decl_ty.zigTypeTag(pt.zcu) == .Fn;
707 if (!is_fn_body and !decl_ty.hasRuntimeBits(pt)) {
704708 try code.appendNTimes(0xaa, ptr_width_bytes);
705709 return Result.ok;
706710 }
707711
708712 const decl_align = ip.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;
709 const res = try lf.lowerAnonDecl(decl_val, decl_align, src_loc);
713 const res = try lf.lowerAnonDecl(pt, decl_val, decl_align, src_loc);
710714 switch (res) {
711715 .ok => {},
712716 .fail => |em| return .{ .fail = em },
......@@ -730,7 +734,8 @@ fn lowerAnonDeclRef(
730734
731735fn lowerDeclRef(
732736 lf: *link.File,
733 src_loc: Module.LazySrcLoc,
737 pt: Zcu.PerThread,
738 src_loc: Zcu.LazySrcLoc,
734739 decl_index: InternPool.DeclIndex,
735740 code: *std.ArrayList(u8),
736741 debug_output: DebugInfoOutput,
......@@ -739,14 +744,14 @@ fn lowerDeclRef(
739744) CodeGenError!Result {
740745 _ = src_loc;
741746 _ = debug_output;
742 const zcu = lf.comp.module.?;
747 const zcu = pt.zcu;
743748 const decl = zcu.declPtr(decl_index);
744749 const namespace = zcu.namespacePtr(decl.src_namespace);
745750 const target = namespace.fileScope(zcu).mod.resolved_target.result;
746751
747752 const ptr_width = target.ptrBitWidth();
748753 const is_fn_body = decl.typeOf(zcu).zigTypeTag(zcu) == .Fn;
749 if (!is_fn_body and !decl.typeOf(zcu).hasRuntimeBits(zcu)) {
754 if (!is_fn_body and !decl.typeOf(zcu).hasRuntimeBits(pt)) {
750755 try code.appendNTimes(0xaa, @divExact(ptr_width, 8));
751756 return Result.ok;
752757 }
......@@ -814,7 +819,7 @@ pub const GenResult = union(enum) {
814819
815820 fn fail(
816821 gpa: Allocator,
817 src_loc: Module.LazySrcLoc,
822 src_loc: Zcu.LazySrcLoc,
818823 comptime format: []const u8,
819824 args: anytype,
820825 ) Allocator.Error!GenResult {
......@@ -825,14 +830,15 @@ pub const GenResult = union(enum) {
825830
826831fn genDeclRef(
827832 lf: *link.File,
828 src_loc: Module.LazySrcLoc,
833 pt: Zcu.PerThread,
834 src_loc: Zcu.LazySrcLoc,
829835 val: Value,
830836 ptr_decl_index: InternPool.DeclIndex,
831837) CodeGenError!GenResult {
832 const zcu = lf.comp.module.?;
838 const zcu = pt.zcu;
833839 const ip = &zcu.intern_pool;
834840 const ty = val.typeOf(zcu);
835 log.debug("genDeclRef: val = {}", .{val.fmtValue(zcu, null)});
841 log.debug("genDeclRef: val = {}", .{val.fmtValue(pt, null)});
836842
837843 const ptr_decl = zcu.declPtr(ptr_decl_index);
838844 const namespace = zcu.namespacePtr(ptr_decl.src_namespace);
......@@ -848,7 +854,7 @@ fn genDeclRef(
848854 };
849855 const decl = zcu.declPtr(decl_index);
850856
851 if (!decl.typeOf(zcu).isFnOrHasRuntimeBitsIgnoreComptime(zcu)) {
857 if (!decl.typeOf(zcu).isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
852858 const imm: u64 = switch (ptr_bytes) {
853859 1 => 0xaa,
854860 2 => 0xaaaa,
......@@ -865,12 +871,12 @@ fn genDeclRef(
865871 // TODO this feels clunky. Perhaps we should check for it in `genTypedValue`?
866872 if (ty.castPtrToFn(zcu)) |fn_ty| {
867873 if (zcu.typeToFunc(fn_ty).?.is_generic) {
868 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(zcu).toByteUnits().? });
874 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(pt).toByteUnits().? });
869875 }
870876 } else if (ty.zigTypeTag(zcu) == .Pointer) {
871877 const elem_ty = ty.elemType2(zcu);
872 if (!elem_ty.hasRuntimeBits(zcu)) {
873 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(zcu).toByteUnits().? });
878 if (!elem_ty.hasRuntimeBits(pt)) {
879 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(pt).toByteUnits().? });
874880 }
875881 }
876882
......@@ -931,15 +937,15 @@ fn genDeclRef(
931937
932938fn genUnnamedConst(
933939 lf: *link.File,
934 src_loc: Module.LazySrcLoc,
940 pt: Zcu.PerThread,
941 src_loc: Zcu.LazySrcLoc,
935942 val: Value,
936943 owner_decl_index: InternPool.DeclIndex,
937944) CodeGenError!GenResult {
938 const zcu = lf.comp.module.?;
939945 const gpa = lf.comp.gpa;
940 log.debug("genUnnamedConst: val = {}", .{val.fmtValue(zcu, null)});
946 log.debug("genUnnamedConst: val = {}", .{val.fmtValue(pt, null)});
941947
942 const local_sym_index = lf.lowerUnnamedConst(val, owner_decl_index) catch |err| {
948 const local_sym_index = lf.lowerUnnamedConst(pt, val, owner_decl_index) catch |err| {
943949 return GenResult.fail(gpa, src_loc, "lowering unnamed constant failed: {s}", .{@errorName(err)});
944950 };
945951 switch (lf.tag) {
......@@ -970,15 +976,16 @@ fn genUnnamedConst(
970976
971977pub fn genTypedValue(
972978 lf: *link.File,
973 src_loc: Module.LazySrcLoc,
979 pt: Zcu.PerThread,
980 src_loc: Zcu.LazySrcLoc,
974981 val: Value,
975982 owner_decl_index: InternPool.DeclIndex,
976983) CodeGenError!GenResult {
977 const zcu = lf.comp.module.?;
984 const zcu = pt.zcu;
978985 const ip = &zcu.intern_pool;
979986 const ty = val.typeOf(zcu);
980987
981 log.debug("genTypedValue: val = {}", .{val.fmtValue(zcu, null)});
988 log.debug("genTypedValue: val = {}", .{val.fmtValue(pt, null)});
982989
983990 if (val.isUndef(zcu))
984991 return GenResult.mcv(.undef);
......@@ -990,7 +997,7 @@ pub fn genTypedValue(
990997
991998 if (!ty.isSlice(zcu)) switch (ip.indexToKey(val.toIntern())) {
992999 .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
993 .decl => |decl| return genDeclRef(lf, src_loc, val, decl),
1000 .decl => |decl| return genDeclRef(lf, pt, src_loc, val, decl),
9941001 else => {},
9951002 },
9961003 else => {},
......@@ -1007,7 +1014,7 @@ pub fn genTypedValue(
10071014 .none => {},
10081015 else => switch (ip.indexToKey(val.toIntern())) {
10091016 .int => {
1010 return GenResult.mcv(.{ .immediate = val.toUnsignedInt(zcu) });
1017 return GenResult.mcv(.{ .immediate = val.toUnsignedInt(pt) });
10111018 },
10121019 else => {},
10131020 },
......@@ -1017,8 +1024,8 @@ pub fn genTypedValue(
10171024 const info = ty.intInfo(zcu);
10181025 if (info.bits <= ptr_bits) {
10191026 const unsigned: u64 = switch (info.signedness) {
1020 .signed => @bitCast(val.toSignedInt(zcu)),
1021 .unsigned => val.toUnsignedInt(zcu),
1027 .signed => @bitCast(val.toSignedInt(pt)),
1028 .unsigned => val.toUnsignedInt(pt),
10221029 };
10231030 return GenResult.mcv(.{ .immediate = unsigned });
10241031 }
......@@ -1030,11 +1037,12 @@ pub fn genTypedValue(
10301037 if (ty.isPtrLikeOptional(zcu)) {
10311038 return genTypedValue(
10321039 lf,
1040 pt,
10331041 src_loc,
10341042 val.optionalValue(zcu) orelse return GenResult.mcv(.{ .immediate = 0 }),
10351043 owner_decl_index,
10361044 );
1037 } else if (ty.abiSize(zcu) == 1) {
1045 } else if (ty.abiSize(pt) == 1) {
10381046 return GenResult.mcv(.{ .immediate = @intFromBool(!val.isNull(zcu)) });
10391047 }
10401048 },
......@@ -1042,6 +1050,7 @@ pub fn genTypedValue(
10421050 const enum_tag = ip.indexToKey(val.toIntern()).enum_tag;
10431051 return genTypedValue(
10441052 lf,
1053 pt,
10451054 src_loc,
10461055 Value.fromInterned(enum_tag.int),
10471056 owner_decl_index,
......@@ -1055,14 +1064,15 @@ pub fn genTypedValue(
10551064 .ErrorUnion => {
10561065 const err_type = ty.errorUnionSet(zcu);
10571066 const payload_type = ty.errorUnionPayload(zcu);
1058 if (!payload_type.hasRuntimeBitsIgnoreComptime(zcu)) {
1067 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
10591068 // We use the error type directly as the type.
1060 const err_int_ty = try zcu.errorIntType();
1069 const err_int_ty = try pt.errorIntType();
10611070 switch (ip.indexToKey(val.toIntern()).error_union.val) {
10621071 .err_name => |err_name| return genTypedValue(
10631072 lf,
1073 pt,
10641074 src_loc,
1065 Value.fromInterned(try zcu.intern(.{ .err = .{
1075 Value.fromInterned(try pt.intern(.{ .err = .{
10661076 .ty = err_type.toIntern(),
10671077 .name = err_name,
10681078 } })),
......@@ -1070,8 +1080,9 @@ pub fn genTypedValue(
10701080 ),
10711081 .payload => return genTypedValue(
10721082 lf,
1083 pt,
10731084 src_loc,
1074 try zcu.intValue(err_int_ty, 0),
1085 try pt.intValue(err_int_ty, 0),
10751086 owner_decl_index,
10761087 ),
10771088 }
......@@ -1090,26 +1101,26 @@ pub fn genTypedValue(
10901101 else => {},
10911102 }
10921103
1093 return genUnnamedConst(lf, src_loc, val, owner_decl_index);
1104 return genUnnamedConst(lf, pt, src_loc, val, owner_decl_index);
10941105}
10951106
1096pub fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) u64 {
1097 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return 0;
1098 const payload_align = payload_ty.abiAlignment(mod);
1099 const error_align = Type.anyerror.abiAlignment(mod);
1100 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1107pub fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
1108 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
1109 const payload_align = payload_ty.abiAlignment(pt);
1110 const error_align = Type.anyerror.abiAlignment(pt);
1111 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
11011112 return 0;
11021113 } else {
1103 return payload_align.forward(Type.anyerror.abiSize(mod));
1114 return payload_align.forward(Type.anyerror.abiSize(pt));
11041115 }
11051116}
11061117
1107pub fn errUnionErrorOffset(payload_ty: Type, mod: *Module) u64 {
1108 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return 0;
1109 const payload_align = payload_ty.abiAlignment(mod);
1110 const error_align = Type.anyerror.abiAlignment(mod);
1111 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1112 return error_align.forward(payload_ty.abiSize(mod));
1118pub fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
1119 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
1120 const payload_align = payload_ty.abiAlignment(pt);
1121 const error_align = Type.anyerror.abiAlignment(pt);
1122 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1123 return error_align.forward(payload_ty.abiSize(pt));
11131124 } else {
11141125 return 0;
11151126 }
src/codegen/c.zig+408-337
......@@ -333,15 +333,15 @@ pub const Function = struct {
333333 const gop = try f.value_map.getOrPut(ref);
334334 if (gop.found_existing) return gop.value_ptr.*;
335335
336 const zcu = f.object.dg.zcu;
337 const val = (try f.air.value(ref, zcu)).?;
336 const pt = f.object.dg.pt;
337 const val = (try f.air.value(ref, pt)).?;
338338 const ty = f.typeOf(ref);
339339
340 const result: CValue = if (lowersToArray(ty, zcu)) result: {
340 const result: CValue = if (lowersToArray(ty, pt)) result: {
341341 const writer = f.object.codeHeaderWriter();
342342 const decl_c_value = try f.allocLocalValue(.{
343343 .ctype = try f.ctypeFromType(ty, .complete),
344 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(zcu)),
344 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(pt)),
345345 });
346346 const gpa = f.object.dg.gpa;
347347 try f.allocs.put(gpa, decl_c_value.new_local, false);
......@@ -358,7 +358,7 @@ pub const Function = struct {
358358 }
359359
360360 fn wantSafety(f: *Function) bool {
361 return switch (f.object.dg.zcu.optimizeMode()) {
361 return switch (f.object.dg.pt.zcu.optimizeMode()) {
362362 .Debug, .ReleaseSafe => true,
363363 .ReleaseFast, .ReleaseSmall => false,
364364 };
......@@ -379,7 +379,7 @@ pub const Function = struct {
379379 fn allocLocal(f: *Function, inst: ?Air.Inst.Index, ty: Type) !CValue {
380380 return f.allocAlignedLocal(inst, .{
381381 .ctype = try f.ctypeFromType(ty, .complete),
382 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(f.object.dg.zcu)),
382 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(f.object.dg.pt)),
383383 });
384384 }
385385
......@@ -500,7 +500,8 @@ pub const Function = struct {
500500
501501 fn getLazyFnName(f: *Function, key: LazyFnKey, data: LazyFnValue.Data) ![]const u8 {
502502 const gpa = f.object.dg.gpa;
503 const zcu = f.object.dg.zcu;
503 const pt = f.object.dg.pt;
504 const zcu = pt.zcu;
504505 const ctype_pool = &f.object.dg.ctype_pool;
505506
506507 const gop = try f.lazy_fns.getOrPut(gpa, key);
......@@ -539,13 +540,11 @@ pub const Function = struct {
539540 }
540541
541542 fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {
542 const zcu = f.object.dg.zcu;
543 return f.air.typeOf(inst, &zcu.intern_pool);
543 return f.air.typeOf(inst, &f.object.dg.pt.zcu.intern_pool);
544544 }
545545
546546 fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {
547 const zcu = f.object.dg.zcu;
548 return f.air.typeOfIndex(inst, &zcu.intern_pool);
547 return f.air.typeOfIndex(inst, &f.object.dg.pt.zcu.intern_pool);
549548 }
550549
551550 fn copyCValue(f: *Function, ctype: CType, dst: CValue, src: CValue) !void {
......@@ -608,7 +607,7 @@ pub const Object = struct {
608607/// This data is available both when outputting .c code and when outputting an .h file.
609608pub const DeclGen = struct {
610609 gpa: mem.Allocator,
611 zcu: *Zcu,
610 pt: Zcu.PerThread,
612611 mod: *Module,
613612 pass: Pass,
614613 is_naked_fn: bool,
......@@ -634,7 +633,7 @@ pub const DeclGen = struct {
634633
635634 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
636635 @setCold(true);
637 const zcu = dg.zcu;
636 const zcu = dg.pt.zcu;
638637 const decl_index = dg.pass.decl;
639638 const decl = zcu.declPtr(decl_index);
640639 const src_loc = decl.navSrcLoc(zcu);
......@@ -648,7 +647,8 @@ pub const DeclGen = struct {
648647 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
649648 location: ValueRenderLocation,
650649 ) error{ OutOfMemory, AnalysisFail }!void {
651 const zcu = dg.zcu;
650 const pt = dg.pt;
651 const zcu = pt.zcu;
652652 const ip = &zcu.intern_pool;
653653 const ctype_pool = &dg.ctype_pool;
654654 const decl_val = Value.fromInterned(anon_decl.val);
......@@ -656,7 +656,7 @@ pub const DeclGen = struct {
656656
657657 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
658658 const ptr_ty = Type.fromInterned(anon_decl.orig_ty);
659 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(zcu)) {
659 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(pt)) {
660660 return dg.writeCValue(writer, .{ .undef = ptr_ty });
661661 }
662662
......@@ -696,7 +696,7 @@ pub const DeclGen = struct {
696696 // alignment. If there is already an entry, keep the greater alignment.
697697 const explicit_alignment = ptr_type.flags.alignment;
698698 if (explicit_alignment != .none) {
699 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(zcu);
699 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(pt);
700700 if (explicit_alignment.order(abi_alignment).compare(.gt)) {
701701 const aligned_gop = try dg.aligned_anon_decls.getOrPut(dg.gpa, anon_decl.val);
702702 aligned_gop.value_ptr.* = if (aligned_gop.found_existing)
......@@ -713,15 +713,16 @@ pub const DeclGen = struct {
713713 decl_index: InternPool.DeclIndex,
714714 location: ValueRenderLocation,
715715 ) error{ OutOfMemory, AnalysisFail }!void {
716 const zcu = dg.zcu;
716 const pt = dg.pt;
717 const zcu = pt.zcu;
717718 const ctype_pool = &dg.ctype_pool;
718719 const decl = zcu.declPtr(decl_index);
719720 assert(decl.has_tv);
720721
721722 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
722723 const decl_ty = decl.typeOf(zcu);
723 const ptr_ty = try decl.declPtrType(zcu);
724 if (!decl_ty.isFnOrHasRuntimeBits(zcu)) {
724 const ptr_ty = try decl.declPtrType(pt);
725 if (!decl_ty.isFnOrHasRuntimeBits(pt)) {
725726 return dg.writeCValue(writer, .{ .undef = ptr_ty });
726727 }
727728
......@@ -756,12 +757,13 @@ pub const DeclGen = struct {
756757 derivation: Value.PointerDeriveStep,
757758 location: ValueRenderLocation,
758759 ) error{ OutOfMemory, AnalysisFail }!void {
759 const zcu = dg.zcu;
760 const pt = dg.pt;
761 const zcu = pt.zcu;
760762 switch (derivation) {
761763 .comptime_alloc_ptr, .comptime_field_ptr => unreachable,
762764 .int => |int| {
763765 const ptr_ctype = try dg.ctypeFromType(int.ptr_ty, .complete);
764 const addr_val = try zcu.intValue(Type.usize, int.addr);
766 const addr_val = try pt.intValue(Type.usize, int.addr);
765767 try writer.writeByte('(');
766768 try dg.renderCType(writer, ptr_ctype);
767769 try writer.print("){x}", .{try dg.fmtIntLiteral(addr_val, .Other)});
......@@ -777,12 +779,12 @@ pub const DeclGen = struct {
777779 },
778780
779781 .field_ptr => |field| {
780 const parent_ptr_ty = try field.parent.ptrType(zcu);
782 const parent_ptr_ty = try field.parent.ptrType(pt);
781783
782784 // Ensure complete type definition is available before accessing fields.
783785 _ = try dg.ctypeFromType(parent_ptr_ty.childType(zcu), .complete);
784786
785 switch (fieldLocation(parent_ptr_ty, field.result_ptr_ty, field.field_idx, zcu)) {
787 switch (fieldLocation(parent_ptr_ty, field.result_ptr_ty, field.field_idx, pt)) {
786788 .begin => {
787789 const ptr_ctype = try dg.ctypeFromType(field.result_ptr_ty, .complete);
788790 try writer.writeByte('(');
......@@ -801,7 +803,7 @@ pub const DeclGen = struct {
801803 try writer.writeByte('(');
802804 try dg.renderCType(writer, ptr_ctype);
803805 try writer.writeByte(')');
804 const offset_val = try zcu.intValue(Type.usize, byte_offset);
806 const offset_val = try pt.intValue(Type.usize, byte_offset);
805807 try writer.writeAll("((char *)");
806808 try dg.renderPointer(writer, field.parent.*, location);
807809 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
......@@ -809,7 +811,7 @@ pub const DeclGen = struct {
809811 }
810812 },
811813
812 .elem_ptr => |elem| if (!(try elem.parent.ptrType(zcu)).childType(zcu).hasRuntimeBits(zcu)) {
814 .elem_ptr => |elem| if (!(try elem.parent.ptrType(pt)).childType(zcu).hasRuntimeBits(pt)) {
813815 // Element type is zero-bit, so lowers to `void`. The index is irrelevant; just cast the pointer.
814816 const ptr_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
815817 try writer.writeByte('(');
......@@ -817,11 +819,11 @@ pub const DeclGen = struct {
817819 try writer.writeByte(')');
818820 try dg.renderPointer(writer, elem.parent.*, location);
819821 } else {
820 const index_val = try zcu.intValue(Type.usize, elem.elem_idx);
822 const index_val = try pt.intValue(Type.usize, elem.elem_idx);
821823 // We want to do pointer arithmetic on a pointer to the element type.
822824 // We might have a pointer-to-array. In this case, we must cast first.
823825 const result_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
824 const parent_ctype = try dg.ctypeFromType(try elem.parent.ptrType(zcu), .complete);
826 const parent_ctype = try dg.ctypeFromType(try elem.parent.ptrType(pt), .complete);
825827 if (result_ctype.eql(parent_ctype)) {
826828 // The pointer already has an appropriate type - just do the arithmetic.
827829 try writer.writeByte('(');
......@@ -846,7 +848,7 @@ pub const DeclGen = struct {
846848 if (oac.byte_offset == 0) {
847849 try dg.renderPointer(writer, oac.parent.*, location);
848850 } else {
849 const offset_val = try zcu.intValue(Type.usize, oac.byte_offset);
851 const offset_val = try pt.intValue(Type.usize, oac.byte_offset);
850852 try writer.writeAll("((char *)");
851853 try dg.renderPointer(writer, oac.parent.*, location);
852854 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
......@@ -856,8 +858,7 @@ pub const DeclGen = struct {
856858 }
857859
858860 fn renderErrorName(dg: *DeclGen, writer: anytype, err_name: InternPool.NullTerminatedString) !void {
859 const zcu = dg.zcu;
860 const ip = &zcu.intern_pool;
861 const ip = &dg.pt.zcu.intern_pool;
861862 try writer.print("zig_error_{}", .{fmtIdent(err_name.toSlice(ip))});
862863 }
863864
......@@ -867,7 +868,8 @@ pub const DeclGen = struct {
867868 val: Value,
868869 location: ValueRenderLocation,
869870 ) error{ OutOfMemory, AnalysisFail }!void {
870 const zcu = dg.zcu;
871 const pt = dg.pt;
872 const zcu = pt.zcu;
871873 const ip = &zcu.intern_pool;
872874 const target = &dg.mod.resolved_target.result;
873875 const ctype_pool = &dg.ctype_pool;
......@@ -927,7 +929,7 @@ pub const DeclGen = struct {
927929 try writer.writeAll("((");
928930 try dg.renderCType(writer, ctype);
929931 try writer.print("){x})", .{try dg.fmtIntLiteral(
930 try zcu.intValue(Type.usize, val.toUnsignedInt(zcu)),
932 try pt.intValue(Type.usize, val.toUnsignedInt(pt)),
931933 .Other,
932934 )});
933935 },
......@@ -974,10 +976,10 @@ pub const DeclGen = struct {
974976 .enum_tag => |enum_tag| try dg.renderValue(writer, Value.fromInterned(enum_tag.int), location),
975977 .float => {
976978 const bits = ty.floatBits(target.*);
977 const f128_val = val.toFloat(f128, zcu);
979 const f128_val = val.toFloat(f128, pt);
978980
979981 // All unsigned ints matching float types are pre-allocated.
980 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
982 const repr_ty = pt.intType(.unsigned, bits) catch unreachable;
981983
982984 assert(bits <= 128);
983985 var repr_val_limbs: [BigInt.calcTwosCompLimbCount(128)]BigIntLimb = undefined;
......@@ -988,10 +990,10 @@ pub const DeclGen = struct {
988990 };
989991
990992 switch (bits) {
991 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, zcu)))),
992 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, zcu)))),
993 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, zcu)))),
994 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, zcu)))),
993 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, pt)))),
994 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, pt)))),
995 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, pt)))),
996 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, pt)))),
995997 128 => repr_val_big.set(@as(u128, @bitCast(f128_val))),
996998 else => unreachable,
997999 }
......@@ -1002,10 +1004,10 @@ pub const DeclGen = struct {
10021004 try dg.renderTypeForBuiltinFnName(writer, ty);
10031005 try writer.writeByte('(');
10041006 switch (bits) {
1005 16 => try writer.print("{x}", .{val.toFloat(f16, zcu)}),
1006 32 => try writer.print("{x}", .{val.toFloat(f32, zcu)}),
1007 64 => try writer.print("{x}", .{val.toFloat(f64, zcu)}),
1008 80 => try writer.print("{x}", .{val.toFloat(f80, zcu)}),
1007 16 => try writer.print("{x}", .{val.toFloat(f16, pt)}),
1008 32 => try writer.print("{x}", .{val.toFloat(f32, pt)}),
1009 64 => try writer.print("{x}", .{val.toFloat(f64, pt)}),
1010 80 => try writer.print("{x}", .{val.toFloat(f80, pt)}),
10091011 128 => try writer.print("{x}", .{f128_val}),
10101012 else => unreachable,
10111013 }
......@@ -1045,10 +1047,10 @@ pub const DeclGen = struct {
10451047 if (std.math.isNan(f128_val)) switch (bits) {
10461048 // We only actually need to pass the significand, but it will get
10471049 // properly masked anyway, so just pass the whole value.
1048 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, zcu)))}),
1049 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, zcu)))}),
1050 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, zcu)))}),
1051 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, zcu)))}),
1050 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, pt)))}),
1051 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, pt)))}),
1052 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, pt)))}),
1053 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, pt)))}),
10521054 128 => try writer.print("\"0x{x}\"", .{@as(u128, @bitCast(f128_val))}),
10531055 else => unreachable,
10541056 };
......@@ -1056,7 +1058,7 @@ pub const DeclGen = struct {
10561058 empty = false;
10571059 }
10581060 try writer.print("{x}", .{try dg.fmtIntLiteral(
1059 try zcu.intValue_big(repr_ty, repr_val_big.toConst()),
1061 try pt.intValue_big(repr_ty, repr_val_big.toConst()),
10601062 location,
10611063 )});
10621064 if (!empty) try writer.writeByte(')');
......@@ -1084,7 +1086,7 @@ pub const DeclGen = struct {
10841086 .ptr => {
10851087 var arena = std.heap.ArenaAllocator.init(zcu.gpa);
10861088 defer arena.deinit();
1087 const derivation = try val.pointerDerivation(arena.allocator(), zcu);
1089 const derivation = try val.pointerDerivation(arena.allocator(), pt);
10881090 try dg.renderPointer(writer, derivation, location);
10891091 },
10901092 .opt => |opt| switch (ctype.info(ctype_pool)) {
......@@ -1167,15 +1169,15 @@ pub const DeclGen = struct {
11671169 try literal.start();
11681170 var index: usize = 0;
11691171 while (index < ai.len) : (index += 1) {
1170 const elem_val = try val.elemValue(zcu, index);
1172 const elem_val = try val.elemValue(pt, index);
11711173 const elem_val_u8: u8 = if (elem_val.isUndef(zcu))
11721174 undefPattern(u8)
11731175 else
1174 @intCast(elem_val.toUnsignedInt(zcu));
1176 @intCast(elem_val.toUnsignedInt(pt));
11751177 try literal.writeChar(elem_val_u8);
11761178 }
11771179 if (ai.sentinel) |s| {
1178 const s_u8: u8 = @intCast(s.toUnsignedInt(zcu));
1180 const s_u8: u8 = @intCast(s.toUnsignedInt(pt));
11791181 if (s_u8 != 0) try literal.writeChar(s_u8);
11801182 }
11811183 try literal.end();
......@@ -1184,7 +1186,7 @@ pub const DeclGen = struct {
11841186 var index: usize = 0;
11851187 while (index < ai.len) : (index += 1) {
11861188 if (index != 0) try writer.writeByte(',');
1187 const elem_val = try val.elemValue(zcu, index);
1189 const elem_val = try val.elemValue(pt, index);
11881190 try dg.renderValue(writer, elem_val, initializer_type);
11891191 }
11901192 if (ai.sentinel) |s| {
......@@ -1207,13 +1209,13 @@ pub const DeclGen = struct {
12071209 const comptime_val = tuple.values.get(ip)[field_index];
12081210 if (comptime_val != .none) continue;
12091211 const field_ty = Type.fromInterned(tuple.types.get(ip)[field_index]);
1210 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1212 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12111213
12121214 if (!empty) try writer.writeByte(',');
12131215
12141216 const field_val = Value.fromInterned(
12151217 switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1216 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1218 .bytes => |bytes| try pt.intern(.{ .int = .{
12171219 .ty = field_ty.toIntern(),
12181220 .storage = .{ .u64 = bytes.at(field_index, ip) },
12191221 } }),
......@@ -1242,12 +1244,12 @@ pub const DeclGen = struct {
12421244 var need_comma = false;
12431245 while (field_it.next()) |field_index| {
12441246 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1245 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1247 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12461248
12471249 if (need_comma) try writer.writeByte(',');
12481250 need_comma = true;
12491251 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1250 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1252 .bytes => |bytes| try pt.intern(.{ .int = .{
12511253 .ty = field_ty.toIntern(),
12521254 .storage = .{ .u64 = bytes.at(field_index, ip) },
12531255 } }),
......@@ -1262,14 +1264,14 @@ pub const DeclGen = struct {
12621264 const int_info = ty.intInfo(zcu);
12631265
12641266 const bits = Type.smallestUnsignedBits(int_info.bits - 1);
1265 const bit_offset_ty = try zcu.intType(.unsigned, bits);
1267 const bit_offset_ty = try pt.intType(.unsigned, bits);
12661268
12671269 var bit_offset: u64 = 0;
12681270 var eff_num_fields: usize = 0;
12691271
12701272 for (0..loaded_struct.field_types.len) |field_index| {
12711273 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1272 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1274 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12731275 eff_num_fields += 1;
12741276 }
12751277
......@@ -1277,7 +1279,7 @@ pub const DeclGen = struct {
12771279 try writer.writeByte('(');
12781280 try dg.renderUndefValue(writer, ty, location);
12791281 try writer.writeByte(')');
1280 } else if (ty.bitSize(zcu) > 64) {
1282 } else if (ty.bitSize(pt) > 64) {
12811283 // zig_or_u128(zig_or_u128(zig_shl_u128(a, a_off), zig_shl_u128(b, b_off)), zig_shl_u128(c, c_off))
12821284 var num_or = eff_num_fields - 1;
12831285 while (num_or > 0) : (num_or -= 1) {
......@@ -1290,10 +1292,10 @@ pub const DeclGen = struct {
12901292 var needs_closing_paren = false;
12911293 for (0..loaded_struct.field_types.len) |field_index| {
12921294 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1293 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1295 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12941296
12951297 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1296 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1298 .bytes => |bytes| try pt.intern(.{ .int = .{
12971299 .ty = field_ty.toIntern(),
12981300 .storage = .{ .u64 = bytes.at(field_index, ip) },
12991301 } }),
......@@ -1307,7 +1309,7 @@ pub const DeclGen = struct {
13071309 try writer.writeByte('(');
13081310 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
13091311 try writer.writeAll(", ");
1310 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1312 try dg.renderValue(writer, try pt.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
13111313 try writer.writeByte(')');
13121314 } else {
13131315 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
......@@ -1316,7 +1318,7 @@ pub const DeclGen = struct {
13161318 if (needs_closing_paren) try writer.writeByte(')');
13171319 if (eff_index != eff_num_fields - 1) try writer.writeAll(", ");
13181320
1319 bit_offset += field_ty.bitSize(zcu);
1321 bit_offset += field_ty.bitSize(pt);
13201322 needs_closing_paren = true;
13211323 eff_index += 1;
13221324 }
......@@ -1326,7 +1328,7 @@ pub const DeclGen = struct {
13261328 var empty = true;
13271329 for (0..loaded_struct.field_types.len) |field_index| {
13281330 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1329 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1331 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
13301332
13311333 if (!empty) try writer.writeAll(" | ");
13321334 try writer.writeByte('(');
......@@ -1334,7 +1336,7 @@ pub const DeclGen = struct {
13341336 try writer.writeByte(')');
13351337
13361338 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1337 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1339 .bytes => |bytes| try pt.intern(.{ .int = .{
13381340 .ty = field_ty.toIntern(),
13391341 .storage = .{ .u64 = bytes.at(field_index, ip) },
13401342 } }),
......@@ -1345,12 +1347,12 @@ pub const DeclGen = struct {
13451347 if (bit_offset != 0) {
13461348 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
13471349 try writer.writeAll(" << ");
1348 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1350 try dg.renderValue(writer, try pt.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
13491351 } else {
13501352 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
13511353 }
13521354
1353 bit_offset += field_ty.bitSize(zcu);
1355 bit_offset += field_ty.bitSize(pt);
13541356 empty = false;
13551357 }
13561358 try writer.writeByte(')');
......@@ -1363,7 +1365,7 @@ pub const DeclGen = struct {
13631365 .un => |un| {
13641366 const loaded_union = ip.loadUnionType(ty.toIntern());
13651367 if (un.tag == .none) {
1366 const backing_ty = try ty.unionBackingType(zcu);
1368 const backing_ty = try ty.unionBackingType(pt);
13671369 switch (loaded_union.getLayout(ip)) {
13681370 .@"packed" => {
13691371 if (!location.isInitializer()) {
......@@ -1378,7 +1380,7 @@ pub const DeclGen = struct {
13781380 return dg.fail("TODO: C backend: implement extern union backing type rendering in static initializers", .{});
13791381 }
13801382
1381 const ptr_ty = try zcu.singleConstPtrType(ty);
1383 const ptr_ty = try pt.singleConstPtrType(ty);
13821384 try writer.writeAll("*((");
13831385 try dg.renderType(writer, ptr_ty);
13841386 try writer.writeAll(")(");
......@@ -1400,7 +1402,7 @@ pub const DeclGen = struct {
14001402 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
14011403 const field_name = loaded_union.loadTagType(ip).names.get(ip)[field_index];
14021404 if (loaded_union.getLayout(ip) == .@"packed") {
1403 if (field_ty.hasRuntimeBits(zcu)) {
1405 if (field_ty.hasRuntimeBits(pt)) {
14041406 if (field_ty.isPtrAtRuntime(zcu)) {
14051407 try writer.writeByte('(');
14061408 try dg.renderCType(writer, ctype);
......@@ -1431,7 +1433,7 @@ pub const DeclGen = struct {
14311433 ),
14321434 .payload => {
14331435 try writer.writeByte('{');
1434 if (field_ty.hasRuntimeBits(zcu)) {
1436 if (field_ty.hasRuntimeBits(pt)) {
14351437 try writer.print(" .{ } = ", .{fmtIdent(field_name.toSlice(ip))});
14361438 try dg.renderValue(
14371439 writer,
......@@ -1443,7 +1445,7 @@ pub const DeclGen = struct {
14431445 const inner_field_ty = Type.fromInterned(
14441446 loaded_union.field_types.get(ip)[inner_field_index],
14451447 );
1446 if (!inner_field_ty.hasRuntimeBits(zcu)) continue;
1448 if (!inner_field_ty.hasRuntimeBits(pt)) continue;
14471449 try dg.renderUndefValue(writer, inner_field_ty, initializer_type);
14481450 break;
14491451 }
......@@ -1464,7 +1466,8 @@ pub const DeclGen = struct {
14641466 ty: Type,
14651467 location: ValueRenderLocation,
14661468 ) error{ OutOfMemory, AnalysisFail }!void {
1467 const zcu = dg.zcu;
1469 const pt = dg.pt;
1470 const zcu = pt.zcu;
14681471 const ip = &zcu.intern_pool;
14691472 const target = &dg.mod.resolved_target.result;
14701473 const ctype_pool = &dg.ctype_pool;
......@@ -1490,7 +1493,7 @@ pub const DeclGen = struct {
14901493 => {
14911494 const bits = ty.floatBits(target.*);
14921495 // All unsigned ints matching float types are pre-allocated.
1493 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
1496 const repr_ty = dg.pt.intType(.unsigned, bits) catch unreachable;
14941497
14951498 try writer.writeAll("zig_make_");
14961499 try dg.renderTypeForBuiltinFnName(writer, ty);
......@@ -1515,14 +1518,14 @@ pub const DeclGen = struct {
15151518 .error_set_type,
15161519 .inferred_error_set_type,
15171520 => return writer.print("{x}", .{
1518 try dg.fmtIntLiteral(try zcu.undefValue(ty), location),
1521 try dg.fmtIntLiteral(try pt.undefValue(ty), location),
15191522 }),
15201523 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
15211524 .One, .Many, .C => {
15221525 try writer.writeAll("((");
15231526 try dg.renderCType(writer, ctype);
15241527 return writer.print("){x})", .{
1525 try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other),
1528 try dg.fmtIntLiteral(try pt.undefValue(Type.usize), .Other),
15261529 });
15271530 },
15281531 .Slice => {
......@@ -1536,7 +1539,7 @@ pub const DeclGen = struct {
15361539 const ptr_ty = ty.slicePtrFieldType(zcu);
15371540 try dg.renderType(writer, ptr_ty);
15381541 return writer.print("){x}, {0x}}}", .{
1539 try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other),
1542 try dg.fmtIntLiteral(try dg.pt.undefValue(Type.usize), .Other),
15401543 });
15411544 },
15421545 },
......@@ -1591,7 +1594,7 @@ pub const DeclGen = struct {
15911594 var need_comma = false;
15921595 while (field_it.next()) |field_index| {
15931596 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1594 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1597 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
15951598
15961599 if (need_comma) try writer.writeByte(',');
15971600 need_comma = true;
......@@ -1600,7 +1603,7 @@ pub const DeclGen = struct {
16001603 return writer.writeByte('}');
16011604 },
16021605 .@"packed" => return writer.print("{x}", .{
1603 try dg.fmtIntLiteral(try zcu.undefValue(ty), .Other),
1606 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
16041607 }),
16051608 }
16061609 },
......@@ -1616,7 +1619,7 @@ pub const DeclGen = struct {
16161619 for (0..anon_struct_info.types.len) |field_index| {
16171620 if (anon_struct_info.values.get(ip)[field_index] != .none) continue;
16181621 const field_ty = Type.fromInterned(anon_struct_info.types.get(ip)[field_index]);
1619 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1622 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
16201623
16211624 if (need_comma) try writer.writeByte(',');
16221625 need_comma = true;
......@@ -1654,7 +1657,7 @@ pub const DeclGen = struct {
16541657 const inner_field_ty = Type.fromInterned(
16551658 loaded_union.field_types.get(ip)[inner_field_index],
16561659 );
1657 if (!inner_field_ty.hasRuntimeBits(zcu)) continue;
1660 if (!inner_field_ty.hasRuntimeBits(pt)) continue;
16581661 try dg.renderUndefValue(
16591662 writer,
16601663 inner_field_ty,
......@@ -1670,7 +1673,7 @@ pub const DeclGen = struct {
16701673 if (has_tag) try writer.writeByte('}');
16711674 },
16721675 .@"packed" => return writer.print("{x}", .{
1673 try dg.fmtIntLiteral(try zcu.undefValue(ty), .Other),
1676 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
16741677 }),
16751678 }
16761679 },
......@@ -1775,7 +1778,7 @@ pub const DeclGen = struct {
17751778 },
17761779 },
17771780 ) !void {
1778 const zcu = dg.zcu;
1781 const zcu = dg.pt.zcu;
17791782 const ip = &zcu.intern_pool;
17801783
17811784 const fn_ty = fn_val.typeOf(zcu);
......@@ -1856,7 +1859,7 @@ pub const DeclGen = struct {
18561859
18571860 fn ctypeFromType(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType {
18581861 defer std.debug.assert(dg.scratch.items.len == 0);
1859 return dg.ctype_pool.fromType(dg.gpa, &dg.scratch, ty, dg.zcu, dg.mod, kind);
1862 return dg.ctype_pool.fromType(dg.gpa, &dg.scratch, ty, dg.pt, dg.mod, kind);
18601863 }
18611864
18621865 fn byteSize(dg: *DeclGen, ctype: CType) u64 {
......@@ -1879,8 +1882,8 @@ pub const DeclGen = struct {
18791882 }
18801883
18811884 fn renderCType(dg: *DeclGen, w: anytype, ctype: CType) error{OutOfMemory}!void {
1882 _ = try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
1883 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
1885 _ = try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.pt.zcu, w, ctype, .suffix, .{});
1886 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.pt.zcu, w, ctype, .suffix, .{});
18841887 }
18851888
18861889 const IntCastContext = union(enum) {
......@@ -1904,18 +1907,18 @@ pub const DeclGen = struct {
19041907 }
19051908 };
19061909 fn intCastIsNoop(dg: *DeclGen, dest_ty: Type, src_ty: Type) bool {
1907 const zcu = dg.zcu;
1908 const dest_bits = dest_ty.bitSize(zcu);
1909 const dest_int_info = dest_ty.intInfo(zcu);
1910 const pt = dg.pt;
1911 const dest_bits = dest_ty.bitSize(pt);
1912 const dest_int_info = dest_ty.intInfo(pt.zcu);
19101913
1911 const src_is_ptr = src_ty.isPtrAtRuntime(zcu);
1914 const src_is_ptr = src_ty.isPtrAtRuntime(pt.zcu);
19121915 const src_eff_ty: Type = if (src_is_ptr) switch (dest_int_info.signedness) {
19131916 .unsigned => Type.usize,
19141917 .signed => Type.isize,
19151918 } else src_ty;
19161919
1917 const src_bits = src_eff_ty.bitSize(zcu);
1918 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
1920 const src_bits = src_eff_ty.bitSize(pt);
1921 const src_int_info = if (src_eff_ty.isAbiInt(pt.zcu)) src_eff_ty.intInfo(pt.zcu) else null;
19191922 if (dest_bits <= 64 and src_bits <= 64) {
19201923 const needs_cast = src_int_info == null or
19211924 (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or
......@@ -1944,8 +1947,9 @@ pub const DeclGen = struct {
19441947 src_ty: Type,
19451948 location: ValueRenderLocation,
19461949 ) !void {
1947 const zcu = dg.zcu;
1948 const dest_bits = dest_ty.bitSize(zcu);
1950 const pt = dg.pt;
1951 const zcu = pt.zcu;
1952 const dest_bits = dest_ty.bitSize(pt);
19491953 const dest_int_info = dest_ty.intInfo(zcu);
19501954
19511955 const src_is_ptr = src_ty.isPtrAtRuntime(zcu);
......@@ -1954,7 +1958,7 @@ pub const DeclGen = struct {
19541958 .signed => Type.isize,
19551959 } else src_ty;
19561960
1957 const src_bits = src_eff_ty.bitSize(zcu);
1961 const src_bits = src_eff_ty.bitSize(pt);
19581962 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
19591963 if (dest_bits <= 64 and src_bits <= 64) {
19601964 const needs_cast = src_int_info == null or
......@@ -2035,7 +2039,7 @@ pub const DeclGen = struct {
20352039 qualifiers,
20362040 CType.AlignAs.fromAlignment(.{
20372041 .@"align" = alignment,
2038 .abi = ty.abiAlignment(dg.zcu),
2042 .abi = ty.abiAlignment(dg.pt),
20392043 }),
20402044 );
20412045 }
......@@ -2048,6 +2052,7 @@ pub const DeclGen = struct {
20482052 qualifiers: CQualifiers,
20492053 alignas: CType.AlignAs,
20502054 ) error{ OutOfMemory, AnalysisFail }!void {
2055 const zcu = dg.pt.zcu;
20512056 switch (alignas.abiOrder()) {
20522057 .lt => try w.print("zig_under_align({}) ", .{alignas.toByteUnits()}),
20532058 .eq => {},
......@@ -2055,10 +2060,10 @@ pub const DeclGen = struct {
20552060 }
20562061
20572062 try w.print("{}", .{
2058 try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, qualifiers),
2063 try renderTypePrefix(dg.pass, &dg.ctype_pool, zcu, w, ctype, .suffix, qualifiers),
20592064 });
20602065 try dg.writeName(w, name);
2061 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
2066 try renderTypeSuffix(dg.pass, &dg.ctype_pool, zcu, w, ctype, .suffix, .{});
20622067 }
20632068
20642069 fn writeName(dg: *DeclGen, w: anytype, c_value: CValue) !void {
......@@ -2162,7 +2167,7 @@ pub const DeclGen = struct {
21622167 decl_index: InternPool.DeclIndex,
21632168 variable: InternPool.Key.Variable,
21642169 ) !void {
2165 const zcu = dg.zcu;
2170 const zcu = dg.pt.zcu;
21662171 const decl = zcu.declPtr(decl_index);
21672172 const fwd = dg.fwdDeclWriter();
21682173 try fwd.writeAll(if (variable.is_extern) "zig_extern " else "static ");
......@@ -2180,7 +2185,7 @@ pub const DeclGen = struct {
21802185 }
21812186
21822187 fn renderDeclName(dg: *DeclGen, writer: anytype, decl_index: InternPool.DeclIndex) !void {
2183 const zcu = dg.zcu;
2188 const zcu = dg.pt.zcu;
21842189 const ip = &zcu.intern_pool;
21852190 const decl = zcu.declPtr(decl_index);
21862191
......@@ -2236,15 +2241,15 @@ pub const DeclGen = struct {
22362241 .bits => {},
22372242 }
22382243
2239 const zcu = dg.zcu;
2240 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
2244 const pt = dg.pt;
2245 const int_info = if (ty.isAbiInt(pt.zcu)) ty.intInfo(pt.zcu) else std.builtin.Type.Int{
22412246 .signedness = .unsigned,
2242 .bits = @as(u16, @intCast(ty.bitSize(zcu))),
2247 .bits = @as(u16, @intCast(ty.bitSize(pt))),
22432248 };
22442249
22452250 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});
22462251 try writer.print(", {}", .{try dg.fmtIntLiteral(
2247 try zcu.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
2252 try pt.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
22482253 .FunctionArgument,
22492254 )});
22502255 }
......@@ -2254,7 +2259,7 @@ pub const DeclGen = struct {
22542259 val: Value,
22552260 loc: ValueRenderLocation,
22562261 ) !std.fmt.Formatter(formatIntLiteral) {
2257 const zcu = dg.zcu;
2262 const zcu = dg.pt.zcu;
22582263 const kind = loc.toCTypeKind();
22592264 const ty = val.typeOf(zcu);
22602265 return std.fmt.Formatter(formatIntLiteral){ .data = .{
......@@ -2616,7 +2621,8 @@ pub fn genGlobalAsm(zcu: *Zcu, writer: anytype) !void {
26162621}
26172622
26182623pub fn genErrDecls(o: *Object) !void {
2619 const zcu = o.dg.zcu;
2624 const pt = o.dg.pt;
2625 const zcu = pt.zcu;
26202626 const ip = &zcu.intern_pool;
26212627 const writer = o.writer();
26222628
......@@ -2628,7 +2634,7 @@ pub fn genErrDecls(o: *Object) !void {
26282634 for (zcu.global_error_set.keys()[1..], 1..) |name_nts, value| {
26292635 const name = name_nts.toSlice(ip);
26302636 max_name_len = @max(name.len, max_name_len);
2631 const err_val = try zcu.intern(.{ .err = .{
2637 const err_val = try pt.intern(.{ .err = .{
26322638 .ty = .anyerror_type,
26332639 .name = name_nts,
26342640 } });
......@@ -2649,12 +2655,12 @@ pub fn genErrDecls(o: *Object) !void {
26492655 @memcpy(name_buf[name_prefix.len..][0..name_slice.len], name_slice);
26502656 const identifier = name_buf[0 .. name_prefix.len + name_slice.len];
26512657
2652 const name_ty = try zcu.arrayType(.{
2658 const name_ty = try pt.arrayType(.{
26532659 .len = name_slice.len,
26542660 .child = .u8_type,
26552661 .sentinel = .zero_u8,
26562662 });
2657 const name_val = try zcu.intern(.{ .aggregate = .{
2663 const name_val = try pt.intern(.{ .aggregate = .{
26582664 .ty = name_ty.toIntern(),
26592665 .storage = .{ .bytes = name.toString() },
26602666 } });
......@@ -2673,7 +2679,7 @@ pub fn genErrDecls(o: *Object) !void {
26732679 try writer.writeAll(";\n");
26742680 }
26752681
2676 const name_array_ty = try zcu.arrayType(.{
2682 const name_array_ty = try pt.arrayType(.{
26772683 .len = zcu.global_error_set.count(),
26782684 .child = .slice_const_u8_sentinel_0_type,
26792685 });
......@@ -2693,14 +2699,15 @@ pub fn genErrDecls(o: *Object) !void {
26932699 if (value != 0) try writer.writeByte(',');
26942700 try writer.print("{{" ++ name_prefix ++ "{}, {}}}", .{
26952701 fmtIdent(name),
2696 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, name.len), .StaticInitializer),
2702 try o.dg.fmtIntLiteral(try pt.intValue(Type.usize, name.len), .StaticInitializer),
26972703 });
26982704 }
26992705 try writer.writeAll("};\n");
27002706}
27012707
27022708pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFnMap.Entry) !void {
2703 const zcu = o.dg.zcu;
2709 const pt = o.dg.pt;
2710 const zcu = pt.zcu;
27042711 const ip = &zcu.intern_pool;
27052712 const ctype_pool = &o.dg.ctype_pool;
27062713 const w = o.writer();
......@@ -2721,20 +2728,20 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
27212728 for (0..tag_names.len) |tag_index| {
27222729 const tag_name = tag_names.get(ip)[tag_index];
27232730 const tag_name_len = tag_name.length(ip);
2724 const tag_val = try zcu.enumValueFieldIndex(enum_ty, @intCast(tag_index));
2731 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
27252732
2726 const name_ty = try zcu.arrayType(.{
2733 const name_ty = try pt.arrayType(.{
27272734 .len = tag_name_len,
27282735 .child = .u8_type,
27292736 .sentinel = .zero_u8,
27302737 });
2731 const name_val = try zcu.intern(.{ .aggregate = .{
2738 const name_val = try pt.intern(.{ .aggregate = .{
27322739 .ty = name_ty.toIntern(),
27332740 .storage = .{ .bytes = tag_name.toString() },
27342741 } });
27352742
27362743 try w.print(" case {}: {{\n static ", .{
2737 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, zcu), .Other),
2744 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, pt), .Other),
27382745 });
27392746 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);
27402747 try w.writeAll(" = ");
......@@ -2743,7 +2750,7 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
27432750 try o.dg.renderType(w, name_slice_ty);
27442751 try w.print("){{{}, {}}};\n", .{
27452752 fmtIdent("name"),
2746 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, tag_name_len), .Other),
2753 try o.dg.fmtIntLiteral(try pt.intValue(Type.usize, tag_name_len), .Other),
27472754 });
27482755
27492756 try w.writeAll(" }\n");
......@@ -2788,7 +2795,7 @@ pub fn genFunc(f: *Function) !void {
27882795 defer tracy.end();
27892796
27902797 const o = &f.object;
2791 const zcu = o.dg.zcu;
2798 const zcu = o.dg.pt.zcu;
27922799 const gpa = o.dg.gpa;
27932800 const decl_index = o.dg.pass.decl;
27942801 const decl = zcu.declPtr(decl_index);
......@@ -2879,12 +2886,13 @@ pub fn genDecl(o: *Object) !void {
28792886 const tracy = trace(@src());
28802887 defer tracy.end();
28812888
2882 const zcu = o.dg.zcu;
2889 const pt = o.dg.pt;
2890 const zcu = pt.zcu;
28832891 const decl_index = o.dg.pass.decl;
28842892 const decl = zcu.declPtr(decl_index);
28852893 const decl_ty = decl.typeOf(zcu);
28862894
2887 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return;
2895 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return;
28882896 if (decl.val.getExternFunc(zcu)) |_| {
28892897 const fwd = o.dg.fwdDeclWriter();
28902898 try fwd.writeAll("zig_extern ");
......@@ -2928,7 +2936,7 @@ pub fn genDeclValue(
29282936 alignment: Alignment,
29292937 @"linksection": InternPool.OptionalNullTerminatedString,
29302938) !void {
2931 const zcu = o.dg.zcu;
2939 const zcu = o.dg.pt.zcu;
29322940 const ty = val.typeOf(zcu);
29332941
29342942 const fwd = o.dg.fwdDeclWriter();
......@@ -2946,7 +2954,7 @@ pub fn genDeclValue(
29462954}
29472955
29482956pub fn genExports(dg: *DeclGen, exported: Zcu.Exported, export_indices: []const u32) !void {
2949 const zcu = dg.zcu;
2957 const zcu = dg.pt.zcu;
29502958 const ip = &zcu.intern_pool;
29512959 const fwd = dg.fwdDeclWriter();
29522960
......@@ -3088,7 +3096,7 @@ fn genBodyResolveState(f: *Function, inst: Air.Inst.Index, leading_deaths: []con
30883096}
30893097
30903098fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfMemory }!void {
3091 const zcu = f.object.dg.zcu;
3099 const zcu = f.object.dg.pt.zcu;
30923100 const ip = &zcu.intern_pool;
30933101 const air_tags = f.air.instructions.items(.tag);
30943102 const air_datas = f.air.instructions.items(.data);
......@@ -3388,10 +3396,10 @@ fn airSliceField(f: *Function, inst: Air.Inst.Index, is_ptr: bool, field_name: [
33883396}
33893397
33903398fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3391 const zcu = f.object.dg.zcu;
3399 const pt = f.object.dg.pt;
33923400 const inst_ty = f.typeOfIndex(inst);
33933401 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3394 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3402 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
33953403 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
33963404 return .none;
33973405 }
......@@ -3414,13 +3422,14 @@ fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
34143422}
34153423
34163424fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3417 const zcu = f.object.dg.zcu;
3425 const pt = f.object.dg.pt;
3426 const zcu = pt.zcu;
34183427 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34193428 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34203429
34213430 const inst_ty = f.typeOfIndex(inst);
34223431 const ptr_ty = f.typeOf(bin_op.lhs);
3423 const elem_has_bits = ptr_ty.elemType2(zcu).hasRuntimeBitsIgnoreComptime(zcu);
3432 const elem_has_bits = ptr_ty.elemType2(zcu).hasRuntimeBitsIgnoreComptime(pt);
34243433
34253434 const ptr = try f.resolveInst(bin_op.lhs);
34263435 const index = try f.resolveInst(bin_op.rhs);
......@@ -3449,10 +3458,10 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
34493458}
34503459
34513460fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3452 const zcu = f.object.dg.zcu;
3461 const pt = f.object.dg.pt;
34533462 const inst_ty = f.typeOfIndex(inst);
34543463 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3455 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3464 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
34563465 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
34573466 return .none;
34583467 }
......@@ -3475,14 +3484,15 @@ fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
34753484}
34763485
34773486fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3478 const zcu = f.object.dg.zcu;
3487 const pt = f.object.dg.pt;
3488 const zcu = pt.zcu;
34793489 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34803490 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34813491
34823492 const inst_ty = f.typeOfIndex(inst);
34833493 const slice_ty = f.typeOf(bin_op.lhs);
34843494 const elem_ty = slice_ty.elemType2(zcu);
3485 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(zcu);
3495 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(pt);
34863496
34873497 const slice = try f.resolveInst(bin_op.lhs);
34883498 const index = try f.resolveInst(bin_op.rhs);
......@@ -3505,10 +3515,10 @@ fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
35053515}
35063516
35073517fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3508 const zcu = f.object.dg.zcu;
3518 const pt = f.object.dg.pt;
35093519 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
35103520 const inst_ty = f.typeOfIndex(inst);
3511 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3521 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35123522 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
35133523 return .none;
35143524 }
......@@ -3531,40 +3541,40 @@ fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
35313541}
35323542
35333543fn airAlloc(f: *Function, inst: Air.Inst.Index) !CValue {
3534 const zcu = f.object.dg.zcu;
3544 const pt = f.object.dg.pt;
3545 const zcu = pt.zcu;
35353546 const inst_ty = f.typeOfIndex(inst);
35363547 const elem_ty = inst_ty.childType(zcu);
3537 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
3548 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .{ .undef = inst_ty };
35383549
35393550 const local = try f.allocLocalValue(.{
35403551 .ctype = try f.ctypeFromType(elem_ty, .complete),
35413552 .alignas = CType.AlignAs.fromAlignment(.{
35423553 .@"align" = inst_ty.ptrInfo(zcu).flags.alignment,
3543 .abi = elem_ty.abiAlignment(zcu),
3554 .abi = elem_ty.abiAlignment(pt),
35443555 }),
35453556 });
35463557 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3547 const gpa = f.object.dg.zcu.gpa;
3548 try f.allocs.put(gpa, local.new_local, true);
3558 try f.allocs.put(zcu.gpa, local.new_local, true);
35493559 return .{ .local_ref = local.new_local };
35503560}
35513561
35523562fn airRetPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3553 const zcu = f.object.dg.zcu;
3563 const pt = f.object.dg.pt;
3564 const zcu = pt.zcu;
35543565 const inst_ty = f.typeOfIndex(inst);
35553566 const elem_ty = inst_ty.childType(zcu);
3556 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
3567 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .{ .undef = inst_ty };
35573568
35583569 const local = try f.allocLocalValue(.{
35593570 .ctype = try f.ctypeFromType(elem_ty, .complete),
35603571 .alignas = CType.AlignAs.fromAlignment(.{
35613572 .@"align" = inst_ty.ptrInfo(zcu).flags.alignment,
3562 .abi = elem_ty.abiAlignment(zcu),
3573 .abi = elem_ty.abiAlignment(pt),
35633574 }),
35643575 });
35653576 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3566 const gpa = f.object.dg.zcu.gpa;
3567 try f.allocs.put(gpa, local.new_local, true);
3577 try f.allocs.put(zcu.gpa, local.new_local, true);
35683578 return .{ .local_ref = local.new_local };
35693579}
35703580
......@@ -3593,7 +3603,8 @@ fn airArg(f: *Function, inst: Air.Inst.Index) !CValue {
35933603}
35943604
35953605fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3596 const zcu = f.object.dg.zcu;
3606 const pt = f.object.dg.pt;
3607 const zcu = pt.zcu;
35973608 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35983609
35993610 const ptr_ty = f.typeOf(ty_op.operand);
......@@ -3601,7 +3612,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36013612 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
36023613 const src_ty = Type.fromInterned(ptr_info.child);
36033614
3604 if (!src_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3615 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) {
36053616 try reap(f, inst, &.{ty_op.operand});
36063617 return .none;
36073618 }
......@@ -3611,10 +3622,10 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36113622 try reap(f, inst, &.{ty_op.operand});
36123623
36133624 const is_aligned = if (ptr_info.flags.alignment != .none)
3614 ptr_info.flags.alignment.order(src_ty.abiAlignment(zcu)).compare(.gte)
3625 ptr_info.flags.alignment.order(src_ty.abiAlignment(pt)).compare(.gte)
36153626 else
36163627 true;
3617 const is_array = lowersToArray(src_ty, zcu);
3628 const is_array = lowersToArray(src_ty, pt);
36183629 const need_memcpy = !is_aligned or is_array;
36193630
36203631 const writer = f.object.writer();
......@@ -3634,12 +3645,12 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36343645 try writer.writeAll("))");
36353646 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
36363647 const host_bits: u16 = ptr_info.packed_offset.host_size * 8;
3637 const host_ty = try zcu.intType(.unsigned, host_bits);
3648 const host_ty = try pt.intType(.unsigned, host_bits);
36383649
3639 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3640 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3650 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3651 const bit_offset_val = try pt.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
36413652
3642 const field_ty = try zcu.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(zcu))));
3653 const field_ty = try pt.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(pt))));
36433654
36443655 try f.writeCValue(writer, local, .Other);
36453656 try v.elem(f, writer);
......@@ -3650,9 +3661,9 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36503661 try writer.writeAll("((");
36513662 try f.renderType(writer, field_ty);
36523663 try writer.writeByte(')');
3653 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3664 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(pt) > 64;
36543665 if (cant_cast) {
3655 if (field_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3666 if (field_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
36563667 try writer.writeAll("zig_lo_");
36573668 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
36583669 try writer.writeByte('(');
......@@ -3680,7 +3691,8 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36803691}
36813692
36823693fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
3683 const zcu = f.object.dg.zcu;
3694 const pt = f.object.dg.pt;
3695 const zcu = pt.zcu;
36843696 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
36853697 const writer = f.object.writer();
36863698 const op_inst = un_op.toIndex();
......@@ -3695,11 +3707,11 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
36953707 const operand = try f.resolveInst(un_op);
36963708 try reap(f, inst, &.{un_op});
36973709 var deref = is_ptr;
3698 const is_array = lowersToArray(ret_ty, zcu);
3710 const is_array = lowersToArray(ret_ty, pt);
36993711 const ret_val = if (is_array) ret_val: {
37003712 const array_local = try f.allocAlignedLocal(inst, .{
37013713 .ctype = ret_ctype,
3702 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(f.object.dg.zcu)),
3714 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(pt)),
37033715 });
37043716 try writer.writeAll("memcpy(");
37053717 try f.writeCValueMember(writer, array_local, .{ .identifier = "array" });
......@@ -3733,7 +3745,8 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
37333745}
37343746
37353747fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
3736 const zcu = f.object.dg.zcu;
3748 const pt = f.object.dg.pt;
3749 const zcu = pt.zcu;
37373750 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37383751
37393752 const operand = try f.resolveInst(ty_op.operand);
......@@ -3760,7 +3773,8 @@ fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
37603773}
37613774
37623775fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3763 const zcu = f.object.dg.zcu;
3776 const pt = f.object.dg.pt;
3777 const zcu = pt.zcu;
37643778 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37653779
37663780 const operand = try f.resolveInst(ty_op.operand);
......@@ -3809,13 +3823,13 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
38093823 try f.writeCValue(writer, operand, .FunctionArgument);
38103824 try v.elem(f, writer);
38113825 try writer.print(", {x})", .{
3812 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(zcu, scalar_ty)),
3826 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(pt, scalar_ty)),
38133827 });
38143828 },
38153829 .signed => {
38163830 const c_bits = toCIntBits(scalar_int_info.bits) orelse
38173831 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
3818 const shift_val = try zcu.intValue(Type.u8, c_bits - dest_bits);
3832 const shift_val = try pt.intValue(Type.u8, c_bits - dest_bits);
38193833
38203834 try writer.writeAll("zig_shr_");
38213835 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
......@@ -3860,7 +3874,8 @@ fn airIntFromBool(f: *Function, inst: Air.Inst.Index) !CValue {
38603874}
38613875
38623876fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3863 const zcu = f.object.dg.zcu;
3877 const pt = f.object.dg.pt;
3878 const zcu = pt.zcu;
38643879 // *a = b;
38653880 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38663881
......@@ -3871,7 +3886,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38713886 const ptr_val = try f.resolveInst(bin_op.lhs);
38723887 const src_ty = f.typeOf(bin_op.rhs);
38733888
3874 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |v| v.isUndefDeep(zcu) else false;
3889 const val_is_undef = if (try f.air.value(bin_op.rhs, pt)) |v| v.isUndefDeep(zcu) else false;
38753890
38763891 if (val_is_undef) {
38773892 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
......@@ -3887,10 +3902,10 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38873902 }
38883903
38893904 const is_aligned = if (ptr_info.flags.alignment != .none)
3890 ptr_info.flags.alignment.order(src_ty.abiAlignment(zcu)).compare(.gte)
3905 ptr_info.flags.alignment.order(src_ty.abiAlignment(pt)).compare(.gte)
38913906 else
38923907 true;
3893 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), zcu);
3908 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), pt);
38943909 const need_memcpy = !is_aligned or is_array;
38953910
38963911 const src_val = try f.resolveInst(bin_op.rhs);
......@@ -3901,7 +3916,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39013916 if (need_memcpy) {
39023917 // For this memcpy to safely work we need the rhs to have the same
39033918 // underlying type as the lhs (i.e. they must both be arrays of the same underlying type).
3904 assert(src_ty.eql(Type.fromInterned(ptr_info.child), f.object.dg.zcu));
3919 assert(src_ty.eql(Type.fromInterned(ptr_info.child), zcu));
39053920
39063921 // If the source is a constant, writeCValue will emit a brace initialization
39073922 // so work around this by initializing into new local.
......@@ -3932,12 +3947,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39323947 try v.end(f, inst, writer);
39333948 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
39343949 const host_bits = ptr_info.packed_offset.host_size * 8;
3935 const host_ty = try zcu.intType(.unsigned, host_bits);
3950 const host_ty = try pt.intType(.unsigned, host_bits);
39363951
3937 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3938 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3952 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3953 const bit_offset_val = try pt.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
39393954
3940 const src_bits = src_ty.bitSize(zcu);
3955 const src_bits = src_ty.bitSize(pt);
39413956
39423957 const ExpectedContents = [BigInt.Managed.default_capacity]BigIntLimb;
39433958 var stack align(@alignOf(ExpectedContents)) =
......@@ -3950,7 +3965,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39503965 try mask.shiftLeft(&mask, ptr_info.packed_offset.bit_offset);
39513966 try mask.bitNotWrap(&mask, .unsigned, host_bits);
39523967
3953 const mask_val = try zcu.intValue_big(host_ty, mask.toConst());
3968 const mask_val = try pt.intValue_big(host_ty, mask.toConst());
39543969
39553970 const v = try Vectorize.start(f, inst, writer, ptr_ty);
39563971 const a = try Assignment.start(f, writer, src_scalar_ctype);
......@@ -3967,9 +3982,9 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39673982 try writer.print(", {x}), zig_shl_", .{try f.fmtIntLiteral(mask_val)});
39683983 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39693984 try writer.writeByte('(');
3970 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3985 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(pt) > 64;
39713986 if (cant_cast) {
3972 if (src_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3987 if (src_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
39733988 try writer.writeAll("zig_make_");
39743989 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39753990 try writer.writeAll("(0, ");
......@@ -4013,7 +4028,8 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
40134028}
40144029
40154030fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info: BuiltinInfo) !CValue {
4016 const zcu = f.object.dg.zcu;
4031 const pt = f.object.dg.pt;
4032 const zcu = pt.zcu;
40174033 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40184034 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
40194035
......@@ -4051,7 +4067,8 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:
40514067}
40524068
40534069fn airNot(f: *Function, inst: Air.Inst.Index) !CValue {
4054 const zcu = f.object.dg.zcu;
4070 const pt = f.object.dg.pt;
4071 const zcu = pt.zcu;
40554072 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
40564073 const operand_ty = f.typeOf(ty_op.operand);
40574074 const scalar_ty = operand_ty.scalarType(zcu);
......@@ -4084,11 +4101,12 @@ fn airBinOp(
40844101 operation: []const u8,
40854102 info: BuiltinInfo,
40864103) !CValue {
4087 const zcu = f.object.dg.zcu;
4104 const pt = f.object.dg.pt;
4105 const zcu = pt.zcu;
40884106 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
40894107 const operand_ty = f.typeOf(bin_op.lhs);
40904108 const scalar_ty = operand_ty.scalarType(zcu);
4091 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(zcu) > 64) or scalar_ty.isRuntimeFloat())
4109 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(pt) > 64) or scalar_ty.isRuntimeFloat())
40924110 return try airBinBuiltinCall(f, inst, operation, info);
40934111
40944112 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -4122,11 +4140,12 @@ fn airCmpOp(
41224140 data: anytype,
41234141 operator: std.math.CompareOperator,
41244142) !CValue {
4125 const zcu = f.object.dg.zcu;
4143 const pt = f.object.dg.pt;
4144 const zcu = pt.zcu;
41264145 const lhs_ty = f.typeOf(data.lhs);
41274146 const scalar_ty = lhs_ty.scalarType(zcu);
41284147
4129 const scalar_bits = scalar_ty.bitSize(zcu);
4148 const scalar_bits = scalar_ty.bitSize(pt);
41304149 if (scalar_ty.isInt(zcu) and scalar_bits > 64)
41314150 return airCmpBuiltinCall(
41324151 f,
......@@ -4170,12 +4189,13 @@ fn airEquality(
41704189 inst: Air.Inst.Index,
41714190 operator: std.math.CompareOperator,
41724191) !CValue {
4173 const zcu = f.object.dg.zcu;
4192 const pt = f.object.dg.pt;
4193 const zcu = pt.zcu;
41744194 const ctype_pool = &f.object.dg.ctype_pool;
41754195 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
41764196
41774197 const operand_ty = f.typeOf(bin_op.lhs);
4178 const operand_bits = operand_ty.bitSize(zcu);
4198 const operand_bits = operand_ty.bitSize(pt);
41794199 if (operand_ty.isAbiInt(zcu) and operand_bits > 64)
41804200 return airCmpBuiltinCall(
41814201 f,
......@@ -4256,7 +4276,8 @@ fn airCmpLtErrorsLen(f: *Function, inst: Air.Inst.Index) !CValue {
42564276}
42574277
42584278fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4259 const zcu = f.object.dg.zcu;
4279 const pt = f.object.dg.pt;
4280 const zcu = pt.zcu;
42604281 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
42614282 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
42624283
......@@ -4267,7 +4288,7 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42674288 const inst_ty = f.typeOfIndex(inst);
42684289 const inst_scalar_ty = inst_ty.scalarType(zcu);
42694290 const elem_ty = inst_scalar_ty.elemType2(zcu);
4270 if (!elem_ty.hasRuntimeBitsIgnoreComptime(zcu)) return f.moveCValue(inst, inst_ty, lhs);
4291 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return f.moveCValue(inst, inst_ty, lhs);
42714292 const inst_scalar_ctype = try f.ctypeFromType(inst_scalar_ty, .complete);
42724293
42734294 const local = try f.allocLocal(inst, inst_ty);
......@@ -4299,13 +4320,14 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42994320}
43004321
43014322fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []const u8) !CValue {
4302 const zcu = f.object.dg.zcu;
4323 const pt = f.object.dg.pt;
4324 const zcu = pt.zcu;
43034325 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
43044326
43054327 const inst_ty = f.typeOfIndex(inst);
43064328 const inst_scalar_ty = inst_ty.scalarType(zcu);
43074329
4308 if ((inst_scalar_ty.isInt(zcu) and inst_scalar_ty.bitSize(zcu) > 64) or inst_scalar_ty.isRuntimeFloat())
4330 if ((inst_scalar_ty.isInt(zcu) and inst_scalar_ty.bitSize(pt) > 64) or inst_scalar_ty.isRuntimeFloat())
43094331 return try airBinBuiltinCall(f, inst, operation, .none);
43104332
43114333 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -4339,7 +4361,8 @@ fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []cons
43394361}
43404362
43414363fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4342 const zcu = f.object.dg.zcu;
4364 const pt = f.object.dg.pt;
4365 const zcu = pt.zcu;
43434366 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
43444367 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
43454368
......@@ -4374,7 +4397,8 @@ fn airCall(
43744397 inst: Air.Inst.Index,
43754398 modifier: std.builtin.CallModifier,
43764399) !CValue {
4377 const zcu = f.object.dg.zcu;
4400 const pt = f.object.dg.pt;
4401 const zcu = pt.zcu;
43784402 // Not even allowed to call panic in a naked function.
43794403 if (f.object.dg.is_naked_fn) return .none;
43804404
......@@ -4398,7 +4422,7 @@ fn airCall(
43984422 if (!arg_ctype.eql(try f.ctypeFromType(arg_ty, .complete))) {
43994423 const array_local = try f.allocAlignedLocal(inst, .{
44004424 .ctype = arg_ctype,
4401 .alignas = CType.AlignAs.fromAbiAlignment(arg_ty.abiAlignment(zcu)),
4425 .alignas = CType.AlignAs.fromAbiAlignment(arg_ty.abiAlignment(pt)),
44024426 });
44034427 try writer.writeAll("memcpy(");
44044428 try f.writeCValueMember(writer, array_local, .{ .identifier = "array" });
......@@ -4445,7 +4469,7 @@ fn airCall(
44454469 } else {
44464470 const local = try f.allocAlignedLocal(inst, .{
44474471 .ctype = ret_ctype,
4448 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(zcu)),
4472 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(pt)),
44494473 });
44504474 try f.writeCValue(writer, local, .Other);
44514475 try writer.writeAll(" = ");
......@@ -4456,7 +4480,7 @@ fn airCall(
44564480 callee: {
44574481 known: {
44584482 const fn_decl = fn_decl: {
4459 const callee_val = (try f.air.value(pl_op.operand, zcu)) orelse break :known;
4483 const callee_val = (try f.air.value(pl_op.operand, pt)) orelse break :known;
44604484 break :fn_decl switch (zcu.intern_pool.indexToKey(callee_val.toIntern())) {
44614485 .extern_func => |extern_func| extern_func.decl,
44624486 .func => |func| func.owner_decl,
......@@ -4499,7 +4523,7 @@ fn airCall(
44994523 try writer.writeAll(");\n");
45004524
45014525 const result = result: {
4502 if (result_local == .none or !lowersToArray(ret_ty, zcu))
4526 if (result_local == .none or !lowersToArray(ret_ty, pt))
45034527 break :result result_local;
45044528
45054529 const array_local = try f.allocLocal(inst, ret_ty);
......@@ -4533,7 +4557,8 @@ fn airDbgStmt(f: *Function, inst: Air.Inst.Index) !CValue {
45334557}
45344558
45354559fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
4536 const zcu = f.object.dg.zcu;
4560 const pt = f.object.dg.pt;
4561 const zcu = pt.zcu;
45374562 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
45384563 const extra = f.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
45394564 const owner_decl = zcu.funcOwnerDeclPtr(extra.data.func);
......@@ -4545,10 +4570,11 @@ fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
45454570}
45464571
45474572fn airDbgVar(f: *Function, inst: Air.Inst.Index) !CValue {
4548 const zcu = f.object.dg.zcu;
4573 const pt = f.object.dg.pt;
4574 const zcu = pt.zcu;
45494575 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
45504576 const name = f.air.nullTerminatedString(pl_op.payload);
4551 const operand_is_undef = if (try f.air.value(pl_op.operand, zcu)) |v| v.isUndefDeep(zcu) else false;
4577 const operand_is_undef = if (try f.air.value(pl_op.operand, pt)) |v| v.isUndefDeep(zcu) else false;
45524578 if (!operand_is_undef) _ = try f.resolveInst(pl_op.operand);
45534579
45544580 try reap(f, inst, &.{pl_op.operand});
......@@ -4564,7 +4590,8 @@ fn airBlock(f: *Function, inst: Air.Inst.Index) !CValue {
45644590}
45654591
45664592fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index) !CValue {
4567 const zcu = f.object.dg.zcu;
4593 const pt = f.object.dg.pt;
4594 const zcu = pt.zcu;
45684595 const liveness_block = f.liveness.getBlock(inst);
45694596
45704597 const block_id: usize = f.next_block_index;
......@@ -4572,7 +4599,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)
45724599 const writer = f.object.writer();
45734600
45744601 const inst_ty = f.typeOfIndex(inst);
4575 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu) and !f.liveness.isUnused(inst))
4602 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !f.liveness.isUnused(inst))
45764603 try f.allocLocal(inst, inst_ty)
45774604 else
45784605 .none;
......@@ -4611,7 +4638,8 @@ fn airTry(f: *Function, inst: Air.Inst.Index) !CValue {
46114638}
46124639
46134640fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {
4614 const zcu = f.object.dg.zcu;
4641 const pt = f.object.dg.pt;
4642 const zcu = pt.zcu;
46154643 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46164644 const extra = f.air.extraData(Air.TryPtr, ty_pl.payload);
46174645 const body: []const Air.Inst.Index = @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]);
......@@ -4627,13 +4655,14 @@ fn lowerTry(
46274655 err_union_ty: Type,
46284656 is_ptr: bool,
46294657) !CValue {
4630 const zcu = f.object.dg.zcu;
4658 const pt = f.object.dg.pt;
4659 const zcu = pt.zcu;
46314660 const err_union = try f.resolveInst(operand);
46324661 const inst_ty = f.typeOfIndex(inst);
46334662 const liveness_condbr = f.liveness.getCondBr(inst);
46344663 const writer = f.object.writer();
46354664 const payload_ty = err_union_ty.errorUnionPayload(zcu);
4636 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
4665 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt);
46374666
46384667 if (!err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu)) {
46394668 try writer.writeAll("if (");
......@@ -4725,7 +4754,8 @@ fn airBitcast(f: *Function, inst: Air.Inst.Index) !CValue {
47254754}
47264755
47274756fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CValue {
4728 const zcu = f.object.dg.zcu;
4757 const pt = f.object.dg.pt;
4758 const zcu = pt.zcu;
47294759 const target = &f.object.dg.mod.resolved_target.result;
47304760 const ctype_pool = &f.object.dg.ctype_pool;
47314761 const writer = f.object.writer();
......@@ -4771,7 +4801,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CVal
47714801 try writer.writeAll(", sizeof(");
47724802 try f.renderType(
47734803 writer,
4774 if (dest_ty.abiSize(zcu) <= operand_ty.abiSize(zcu)) dest_ty else operand_ty,
4804 if (dest_ty.abiSize(pt) <= operand_ty.abiSize(pt)) dest_ty else operand_ty,
47754805 );
47764806 try writer.writeAll("));\n");
47774807
......@@ -4805,7 +4835,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CVal
48054835 try writer.writeByte('(');
48064836 }
48074837 try writer.writeAll("zig_wrap_");
4808 const info_ty = try zcu.intType(dest_info.signedness, bits);
4838 const info_ty = try pt.intType(dest_info.signedness, bits);
48094839 if (wrap_ctype) |ctype|
48104840 try f.object.dg.renderCTypeForBuiltinFnName(writer, ctype)
48114841 else
......@@ -4935,7 +4965,8 @@ fn airCondBr(f: *Function, inst: Air.Inst.Index) !CValue {
49354965}
49364966
49374967fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4938 const zcu = f.object.dg.zcu;
4968 const pt = f.object.dg.pt;
4969 const zcu = pt.zcu;
49394970 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
49404971 const condition = try f.resolveInst(pl_op.operand);
49414972 try reap(f, inst, &.{pl_op.operand});
......@@ -4979,16 +5010,16 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
49795010 for (items) |item| {
49805011 try f.object.indent_writer.insertNewline();
49815012 try writer.writeAll("case ");
4982 const item_value = try f.air.value(item, zcu);
4983 if (item_value.?.getUnsignedInt(zcu)) |item_int| try writer.print("{}\n", .{
4984 try f.fmtIntLiteral(try zcu.intValue(lowered_condition_ty, item_int)),
5013 const item_value = try f.air.value(item, pt);
5014 if (item_value.?.getUnsignedInt(pt)) |item_int| try writer.print("{}\n", .{
5015 try f.fmtIntLiteral(try pt.intValue(lowered_condition_ty, item_int)),
49855016 }) else {
49865017 if (condition_ty.isPtrAtRuntime(zcu)) {
49875018 try writer.writeByte('(');
49885019 try f.renderType(writer, Type.usize);
49895020 try writer.writeByte(')');
49905021 }
4991 try f.object.dg.renderValue(writer, (try f.air.value(item, zcu)).?, .Other);
5022 try f.object.dg.renderValue(writer, (try f.air.value(item, pt)).?, .Other);
49925023 }
49935024 try writer.writeByte(':');
49945025 }
......@@ -5026,13 +5057,14 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
50265057}
50275058
50285059fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool {
5029 const target = &f.object.dg.mod.resolved_target.result;
5060 const dg = f.object.dg;
5061 const target = &dg.mod.resolved_target.result;
50305062 return switch (constraint[0]) {
50315063 '{' => true,
50325064 'i', 'r' => false,
50335065 'I' => !target.cpu.arch.isArmOrThumb(),
50345066 else => switch (value) {
5035 .constant => |val| switch (f.object.dg.zcu.intern_pool.indexToKey(val.toIntern())) {
5067 .constant => |val| switch (dg.pt.zcu.intern_pool.indexToKey(val.toIntern())) {
50365068 .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
50375069 .decl => false,
50385070 else => true,
......@@ -5045,7 +5077,8 @@ fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool
50455077}
50465078
50475079fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
5048 const zcu = f.object.dg.zcu;
5080 const pt = f.object.dg.pt;
5081 const zcu = pt.zcu;
50495082 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
50505083 const extra = f.air.extraData(Air.Asm, ty_pl.payload);
50515084 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;
......@@ -5060,10 +5093,10 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50605093 const result = result: {
50615094 const writer = f.object.writer();
50625095 const inst_ty = f.typeOfIndex(inst);
5063 const inst_local = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) local: {
5096 const inst_local = if (inst_ty.hasRuntimeBitsIgnoreComptime(pt)) local: {
50645097 const inst_local = try f.allocLocalValue(.{
50655098 .ctype = try f.ctypeFromType(inst_ty, .complete),
5066 .alignas = CType.AlignAs.fromAbiAlignment(inst_ty.abiAlignment(zcu)),
5099 .alignas = CType.AlignAs.fromAbiAlignment(inst_ty.abiAlignment(pt)),
50675100 });
50685101 if (f.wantSafety()) {
50695102 try f.writeCValue(writer, inst_local, .Other);
......@@ -5096,7 +5129,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50965129 try writer.writeAll("register ");
50975130 const output_local = try f.allocLocalValue(.{
50985131 .ctype = try f.ctypeFromType(output_ty, .complete),
5099 .alignas = CType.AlignAs.fromAbiAlignment(output_ty.abiAlignment(zcu)),
5132 .alignas = CType.AlignAs.fromAbiAlignment(output_ty.abiAlignment(pt)),
51005133 });
51015134 try f.allocs.put(gpa, output_local.new_local, false);
51025135 try f.object.dg.renderTypeAndName(writer, output_ty, output_local, .{}, .none, .complete);
......@@ -5131,7 +5164,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
51315164 if (is_reg) try writer.writeAll("register ");
51325165 const input_local = try f.allocLocalValue(.{
51335166 .ctype = try f.ctypeFromType(input_ty, .complete),
5134 .alignas = CType.AlignAs.fromAbiAlignment(input_ty.abiAlignment(zcu)),
5167 .alignas = CType.AlignAs.fromAbiAlignment(input_ty.abiAlignment(pt)),
51355168 });
51365169 try f.allocs.put(gpa, input_local.new_local, false);
51375170 try f.object.dg.renderTypeAndName(writer, input_ty, input_local, Const, .none, .complete);
......@@ -5314,7 +5347,8 @@ fn airIsNull(
53145347 operator: std.math.CompareOperator,
53155348 is_ptr: bool,
53165349) !CValue {
5317 const zcu = f.object.dg.zcu;
5350 const pt = f.object.dg.pt;
5351 const zcu = pt.zcu;
53185352 const ctype_pool = &f.object.dg.ctype_pool;
53195353 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
53205354
......@@ -5369,7 +5403,8 @@ fn airIsNull(
53695403}
53705404
53715405fn airOptionalPayload(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
5372 const zcu = f.object.dg.zcu;
5406 const pt = f.object.dg.pt;
5407 const zcu = pt.zcu;
53735408 const ctype_pool = &f.object.dg.ctype_pool;
53745409 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53755410
......@@ -5404,7 +5439,8 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue
54045439}
54055440
54065441fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5407 const zcu = f.object.dg.zcu;
5442 const pt = f.object.dg.pt;
5443 const zcu = pt.zcu;
54085444 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54095445 const writer = f.object.writer();
54105446 const operand = try f.resolveInst(ty_op.operand);
......@@ -5458,21 +5494,22 @@ fn fieldLocation(
54585494 container_ptr_ty: Type,
54595495 field_ptr_ty: Type,
54605496 field_index: u32,
5461 zcu: *Zcu,
5497 pt: Zcu.PerThread,
54625498) union(enum) {
54635499 begin: void,
54645500 field: CValue,
54655501 byte_offset: u64,
54665502} {
5503 const zcu = pt.zcu;
54675504 const ip = &zcu.intern_pool;
54685505 const container_ty = Type.fromInterned(ip.indexToKey(container_ptr_ty.toIntern()).ptr_type.child);
54695506 switch (ip.indexToKey(container_ty.toIntern())) {
54705507 .struct_type => {
54715508 const loaded_struct = ip.loadStructType(container_ty.toIntern());
54725509 return switch (loaded_struct.layout) {
5473 .auto, .@"extern" => if (!container_ty.hasRuntimeBitsIgnoreComptime(zcu))
5510 .auto, .@"extern" => if (!container_ty.hasRuntimeBitsIgnoreComptime(pt))
54745511 .begin
5475 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu))
5512 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(pt))
54765513 .{ .byte_offset = loaded_struct.offsets.get(ip)[field_index] }
54775514 else
54785515 .{ .field = if (loaded_struct.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -5480,16 +5517,16 @@ fn fieldLocation(
54805517 else
54815518 .{ .field = field_index } },
54825519 .@"packed" => if (field_ptr_ty.ptrInfo(zcu).packed_offset.host_size == 0)
5483 .{ .byte_offset = @divExact(zcu.structPackedFieldBitOffset(loaded_struct, field_index) +
5520 .{ .byte_offset = @divExact(pt.structPackedFieldBitOffset(loaded_struct, field_index) +
54845521 container_ptr_ty.ptrInfo(zcu).packed_offset.bit_offset, 8) }
54855522 else
54865523 .begin,
54875524 };
54885525 },
5489 .anon_struct_type => |anon_struct_info| return if (!container_ty.hasRuntimeBitsIgnoreComptime(zcu))
5526 .anon_struct_type => |anon_struct_info| return if (!container_ty.hasRuntimeBitsIgnoreComptime(pt))
54905527 .begin
5491 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu))
5492 .{ .byte_offset = container_ty.structFieldOffset(field_index, zcu) }
5528 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(pt))
5529 .{ .byte_offset = container_ty.structFieldOffset(field_index, pt) }
54935530 else
54945531 .{ .field = if (anon_struct_info.fieldName(ip, field_index).unwrap()) |field_name|
54955532 .{ .identifier = field_name.toSlice(ip) }
......@@ -5500,8 +5537,8 @@ fn fieldLocation(
55005537 switch (loaded_union.getLayout(ip)) {
55015538 .auto, .@"extern" => {
55025539 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
5503 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu))
5504 return if (loaded_union.hasTag(ip) and !container_ty.unionHasAllZeroBitFieldTypes(zcu))
5540 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt))
5541 return if (loaded_union.hasTag(ip) and !container_ty.unionHasAllZeroBitFieldTypes(pt))
55055542 .{ .field = .{ .identifier = "payload" } }
55065543 else
55075544 .begin;
......@@ -5546,7 +5583,8 @@ fn airStructFieldPtrIndex(f: *Function, inst: Air.Inst.Index, index: u8) !CValue
55465583}
55475584
55485585fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5549 const zcu = f.object.dg.zcu;
5586 const pt = f.object.dg.pt;
5587 const zcu = pt.zcu;
55505588 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
55515589 const extra = f.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
55525590
......@@ -5564,10 +5602,10 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55645602 try f.renderType(writer, container_ptr_ty);
55655603 try writer.writeByte(')');
55665604
5567 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, zcu)) {
5605 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, pt)) {
55685606 .begin => try f.writeCValue(writer, field_ptr_val, .Initializer),
55695607 .field => |field| {
5570 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5608 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55715609
55725610 try writer.writeAll("((");
55735611 try f.renderType(writer, u8_ptr_ty);
......@@ -5580,14 +5618,14 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55805618 try writer.writeAll("))");
55815619 },
55825620 .byte_offset => |byte_offset| {
5583 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5621 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55845622
55855623 try writer.writeAll("((");
55865624 try f.renderType(writer, u8_ptr_ty);
55875625 try writer.writeByte(')');
55885626 try f.writeCValue(writer, field_ptr_val, .Other);
55895627 try writer.print(" - {})", .{
5590 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5628 try f.fmtIntLiteral(try pt.intValue(Type.usize, byte_offset)),
55915629 });
55925630 },
55935631 }
......@@ -5603,7 +5641,8 @@ fn fieldPtr(
56035641 container_ptr_val: CValue,
56045642 field_index: u32,
56055643) !CValue {
5606 const zcu = f.object.dg.zcu;
5644 const pt = f.object.dg.pt;
5645 const zcu = pt.zcu;
56075646 const container_ty = container_ptr_ty.childType(zcu);
56085647 const field_ptr_ty = f.typeOfIndex(inst);
56095648
......@@ -5617,21 +5656,21 @@ fn fieldPtr(
56175656 try f.renderType(writer, field_ptr_ty);
56185657 try writer.writeByte(')');
56195658
5620 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, zcu)) {
5659 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, pt)) {
56215660 .begin => try f.writeCValue(writer, container_ptr_val, .Initializer),
56225661 .field => |field| {
56235662 try writer.writeByte('&');
56245663 try f.writeCValueDerefMember(writer, container_ptr_val, field);
56255664 },
56265665 .byte_offset => |byte_offset| {
5627 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5666 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
56285667
56295668 try writer.writeAll("((");
56305669 try f.renderType(writer, u8_ptr_ty);
56315670 try writer.writeByte(')');
56325671 try f.writeCValue(writer, container_ptr_val, .Other);
56335672 try writer.print(" + {})", .{
5634 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5673 try f.fmtIntLiteral(try pt.intValue(Type.usize, byte_offset)),
56355674 });
56365675 },
56375676 }
......@@ -5641,13 +5680,14 @@ fn fieldPtr(
56415680}
56425681
56435682fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5644 const zcu = f.object.dg.zcu;
5683 const pt = f.object.dg.pt;
5684 const zcu = pt.zcu;
56455685 const ip = &zcu.intern_pool;
56465686 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
56475687 const extra = f.air.extraData(Air.StructField, ty_pl.payload).data;
56485688
56495689 const inst_ty = f.typeOfIndex(inst);
5650 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5690 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56515691 try reap(f, inst, &.{extra.struct_operand});
56525692 return .none;
56535693 }
......@@ -5671,15 +5711,15 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56715711 .@"packed" => {
56725712 const int_info = struct_ty.intInfo(zcu);
56735713
5674 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
5714 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
56755715
5676 const bit_offset = zcu.structPackedFieldBitOffset(loaded_struct, extra.field_index);
5716 const bit_offset = pt.structPackedFieldBitOffset(loaded_struct, extra.field_index);
56775717
56785718 const field_int_signedness = if (inst_ty.isAbiInt(zcu))
56795719 inst_ty.intInfo(zcu).signedness
56805720 else
56815721 .unsigned;
5682 const field_int_ty = try zcu.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(zcu))));
5722 const field_int_ty = try pt.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(pt))));
56835723
56845724 const temp_local = try f.allocLocal(inst, field_int_ty);
56855725 try f.writeCValue(writer, temp_local, .Other);
......@@ -5690,7 +5730,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56905730 try writer.writeByte(')');
56915731 const cant_cast = int_info.bits > 64;
56925732 if (cant_cast) {
5693 if (field_int_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
5733 if (field_int_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
56945734 try writer.writeAll("zig_lo_");
56955735 try f.object.dg.renderTypeForBuiltinFnName(writer, struct_ty);
56965736 try writer.writeByte('(');
......@@ -5702,12 +5742,12 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57025742 }
57035743 try f.writeCValue(writer, struct_byval, .Other);
57045744 if (bit_offset > 0) try writer.print(", {})", .{
5705 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
5745 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
57065746 });
57075747 if (cant_cast) try writer.writeByte(')');
57085748 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);
57095749 try writer.writeAll(");\n");
5710 if (inst_ty.eql(field_int_ty, f.object.dg.zcu)) return temp_local;
5750 if (inst_ty.eql(field_int_ty, zcu)) return temp_local;
57115751
57125752 const local = try f.allocLocal(inst, inst_ty);
57135753 if (local.new_local != temp_local.new_local) {
......@@ -5783,7 +5823,8 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57835823/// *(E!T) -> E
57845824/// Note that the result is never a pointer.
57855825fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5786 const zcu = f.object.dg.zcu;
5826 const pt = f.object.dg.pt;
5827 const zcu = pt.zcu;
57875828 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57885829
57895830 const inst_ty = f.typeOfIndex(inst);
......@@ -5797,7 +5838,7 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
57975838 const payload_ty = error_union_ty.errorUnionPayload(zcu);
57985839 const local = try f.allocLocal(inst, inst_ty);
57995840
5800 if (!payload_ty.hasRuntimeBits(zcu) and operand == .local and operand.local == local.new_local) {
5841 if (!payload_ty.hasRuntimeBits(pt) and operand == .local and operand.local == local.new_local) {
58015842 // The store will be 'x = x'; elide it.
58025843 return local;
58035844 }
......@@ -5806,11 +5847,11 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
58065847 try f.writeCValue(writer, local, .Other);
58075848 try writer.writeAll(" = ");
58085849
5809 if (!payload_ty.hasRuntimeBits(zcu))
5850 if (!payload_ty.hasRuntimeBits(pt))
58105851 try f.writeCValue(writer, operand, .Other)
58115852 else if (error_ty.errorSetIsEmpty(zcu))
58125853 try writer.print("{}", .{
5813 try f.fmtIntLiteral(try zcu.intValue(try zcu.errorIntType(), 0)),
5854 try f.fmtIntLiteral(try pt.intValue(try pt.errorIntType(), 0)),
58145855 })
58155856 else if (operand_is_ptr)
58165857 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
......@@ -5821,7 +5862,8 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
58215862}
58225863
58235864fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
5824 const zcu = f.object.dg.zcu;
5865 const pt = f.object.dg.pt;
5866 const zcu = pt.zcu;
58255867 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58265868
58275869 const inst_ty = f.typeOfIndex(inst);
......@@ -5831,7 +5873,7 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValu
58315873 const error_union_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
58325874
58335875 const writer = f.object.writer();
5834 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(zcu)) {
5876 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(pt)) {
58355877 if (!is_ptr) return .none;
58365878
58375879 const local = try f.allocLocal(inst, inst_ty);
......@@ -5896,12 +5938,13 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
58965938}
58975939
58985940fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5899 const zcu = f.object.dg.zcu;
5941 const pt = f.object.dg.pt;
5942 const zcu = pt.zcu;
59005943 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59015944
59025945 const inst_ty = f.typeOfIndex(inst);
59035946 const payload_ty = inst_ty.errorUnionPayload(zcu);
5904 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
5947 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(pt);
59055948 const err_ty = inst_ty.errorUnionSet(zcu);
59065949 const err = try f.resolveInst(ty_op.operand);
59075950 try reap(f, inst, &.{ty_op.operand});
......@@ -5935,7 +5978,8 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
59355978}
59365979
59375980fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5938 const zcu = f.object.dg.zcu;
5981 const pt = f.object.dg.pt;
5982 const zcu = pt.zcu;
59395983 const writer = f.object.writer();
59405984 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59415985 const inst_ty = f.typeOfIndex(inst);
......@@ -5944,12 +5988,12 @@ fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
59445988 const error_union_ty = operand_ty.childType(zcu);
59455989
59465990 const payload_ty = error_union_ty.errorUnionPayload(zcu);
5947 const err_int_ty = try zcu.errorIntType();
5948 const no_err = try zcu.intValue(err_int_ty, 0);
5991 const err_int_ty = try pt.errorIntType();
5992 const no_err = try pt.intValue(err_int_ty, 0);
59495993 try reap(f, inst, &.{ty_op.operand});
59505994
59515995 // First, set the non-error value.
5952 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5996 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
59535997 const a = try Assignment.start(f, writer, try f.ctypeFromType(operand_ty, .complete));
59545998 try f.writeCValueDeref(writer, operand);
59555999 try a.assign(f, writer);
......@@ -5994,13 +6038,14 @@ fn airSaveErrReturnTraceIndex(f: *Function, inst: Air.Inst.Index) !CValue {
59946038}
59956039
59966040fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
5997 const zcu = f.object.dg.zcu;
6041 const pt = f.object.dg.pt;
6042 const zcu = pt.zcu;
59986043 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59996044
60006045 const inst_ty = f.typeOfIndex(inst);
60016046 const payload_ty = inst_ty.errorUnionPayload(zcu);
60026047 const payload = try f.resolveInst(ty_op.operand);
6003 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
6048 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(pt);
60046049 const err_ty = inst_ty.errorUnionSet(zcu);
60056050 try reap(f, inst, &.{ty_op.operand});
60066051
......@@ -6020,14 +6065,15 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
60206065 else
60216066 try f.writeCValueMember(writer, local, .{ .identifier = "error" });
60226067 try a.assign(f, writer);
6023 try f.object.dg.renderValue(writer, try zcu.intValue(try zcu.errorIntType(), 0), .Other);
6068 try f.object.dg.renderValue(writer, try pt.intValue(try pt.errorIntType(), 0), .Other);
60246069 try a.end(f, writer);
60256070 }
60266071 return local;
60276072}
60286073
60296074fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const u8) !CValue {
6030 const zcu = f.object.dg.zcu;
6075 const pt = f.object.dg.pt;
6076 const zcu = pt.zcu;
60316077 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
60326078
60336079 const writer = f.object.writer();
......@@ -6042,9 +6088,9 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
60426088 const a = try Assignment.start(f, writer, CType.bool);
60436089 try f.writeCValue(writer, local, .Other);
60446090 try a.assign(f, writer);
6045 const err_int_ty = try zcu.errorIntType();
6091 const err_int_ty = try pt.errorIntType();
60466092 if (!error_ty.errorSetIsEmpty(zcu))
6047 if (payload_ty.hasRuntimeBits(zcu))
6093 if (payload_ty.hasRuntimeBits(pt))
60486094 if (is_ptr)
60496095 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
60506096 else
......@@ -6052,17 +6098,18 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
60526098 else
60536099 try f.writeCValue(writer, operand, .Other)
60546100 else
6055 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6101 try f.object.dg.renderValue(writer, try pt.intValue(err_int_ty, 0), .Other);
60566102 try writer.writeByte(' ');
60576103 try writer.writeAll(operator);
60586104 try writer.writeByte(' ');
6059 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6105 try f.object.dg.renderValue(writer, try pt.intValue(err_int_ty, 0), .Other);
60606106 try a.end(f, writer);
60616107 return local;
60626108}
60636109
60646110fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
6065 const zcu = f.object.dg.zcu;
6111 const pt = f.object.dg.pt;
6112 const zcu = pt.zcu;
60666113 const ctype_pool = &f.object.dg.ctype_pool;
60676114 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60686115
......@@ -6096,7 +6143,7 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
60966143 if (operand_child_ctype.info(ctype_pool) == .array) {
60976144 try writer.writeByte('&');
60986145 try f.writeCValueDeref(writer, operand);
6099 try writer.print("[{}]", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
6146 try writer.print("[{}]", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 0))});
61006147 } else try f.writeCValue(writer, operand, .Initializer);
61016148 }
61026149 try a.end(f, writer);
......@@ -6106,7 +6153,7 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
61066153 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
61076154 try a.assign(f, writer);
61086155 try writer.print("{}", .{
6109 try f.fmtIntLiteral(try zcu.intValue(Type.usize, array_ty.arrayLen(zcu))),
6156 try f.fmtIntLiteral(try pt.intValue(Type.usize, array_ty.arrayLen(zcu))),
61106157 });
61116158 try a.end(f, writer);
61126159 }
......@@ -6115,7 +6162,8 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
61156162}
61166163
61176164fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6118 const zcu = f.object.dg.zcu;
6165 const pt = f.object.dg.pt;
6166 const zcu = pt.zcu;
61196167 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61206168
61216169 const inst_ty = f.typeOfIndex(inst);
......@@ -6165,7 +6213,8 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
61656213}
61666214
61676215fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
6168 const zcu = f.object.dg.zcu;
6216 const pt = f.object.dg.pt;
6217 const zcu = pt.zcu;
61696218 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61706219
61716220 const operand = try f.resolveInst(un_op);
......@@ -6194,7 +6243,8 @@ fn airUnBuiltinCall(
61946243 operation: []const u8,
61956244 info: BuiltinInfo,
61966245) !CValue {
6197 const zcu = f.object.dg.zcu;
6246 const pt = f.object.dg.pt;
6247 const zcu = pt.zcu;
61986248
61996249 const operand = try f.resolveInst(operand_ref);
62006250 try reap(f, inst, &.{operand_ref});
......@@ -6237,7 +6287,8 @@ fn airBinBuiltinCall(
62376287 operation: []const u8,
62386288 info: BuiltinInfo,
62396289) !CValue {
6240 const zcu = f.object.dg.zcu;
6290 const pt = f.object.dg.pt;
6291 const zcu = pt.zcu;
62416292 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
62426293
62436294 const operand_ty = f.typeOf(bin_op.lhs);
......@@ -6292,7 +6343,8 @@ fn airCmpBuiltinCall(
62926343 operation: enum { cmp, operator },
62936344 info: BuiltinInfo,
62946345) !CValue {
6295 const zcu = f.object.dg.zcu;
6346 const pt = f.object.dg.pt;
6347 const zcu = pt.zcu;
62966348 const lhs = try f.resolveInst(data.lhs);
62976349 const rhs = try f.resolveInst(data.rhs);
62986350 try reap(f, inst, &.{ data.lhs, data.rhs });
......@@ -6333,7 +6385,7 @@ fn airCmpBuiltinCall(
63336385 try writer.writeByte(')');
63346386 if (!ref_ret) try writer.print("{s}{}", .{
63356387 compareOperatorC(operator),
6336 try f.fmtIntLiteral(try zcu.intValue(Type.i32, 0)),
6388 try f.fmtIntLiteral(try pt.intValue(Type.i32, 0)),
63376389 });
63386390 try writer.writeAll(";\n");
63396391 try v.end(f, inst, writer);
......@@ -6342,7 +6394,8 @@ fn airCmpBuiltinCall(
63426394}
63436395
63446396fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue {
6345 const zcu = f.object.dg.zcu;
6397 const pt = f.object.dg.pt;
6398 const zcu = pt.zcu;
63466399 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
63476400 const extra = f.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
63486401 const inst_ty = f.typeOfIndex(inst);
......@@ -6358,7 +6411,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63586411 try reap(f, inst, &.{ extra.ptr, extra.expected_value, extra.new_value });
63596412
63606413 const repr_ty = if (ty.isRuntimeFloat())
6361 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6414 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
63626415 else
63636416 ty;
63646417
......@@ -6448,7 +6501,8 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
64486501}
64496502
64506503fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6451 const zcu = f.object.dg.zcu;
6504 const pt = f.object.dg.pt;
6505 const zcu = pt.zcu;
64526506 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
64536507 const extra = f.air.extraData(Air.AtomicRmw, pl_op.payload).data;
64546508 const inst_ty = f.typeOfIndex(inst);
......@@ -6461,10 +6515,10 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64616515 const operand_mat = try Materialize.start(f, inst, ty, operand);
64626516 try reap(f, inst, &.{ pl_op.operand, extra.operand });
64636517
6464 const repr_bits = @as(u16, @intCast(ty.abiSize(zcu) * 8));
6518 const repr_bits = @as(u16, @intCast(ty.abiSize(pt) * 8));
64656519 const is_float = ty.isRuntimeFloat();
64666520 const is_128 = repr_bits == 128;
6467 const repr_ty = if (is_float) zcu.intType(.unsigned, repr_bits) catch unreachable else ty;
6521 const repr_ty = if (is_float) pt.intType(.unsigned, repr_bits) catch unreachable else ty;
64686522
64696523 const local = try f.allocLocal(inst, inst_ty);
64706524 try writer.print("zig_atomicrmw_{s}", .{toAtomicRmwSuffix(extra.op())});
......@@ -6503,7 +6557,8 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
65036557}
65046558
65056559fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6506 const zcu = f.object.dg.zcu;
6560 const pt = f.object.dg.pt;
6561 const zcu = pt.zcu;
65076562 const atomic_load = f.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
65086563 const ptr = try f.resolveInst(atomic_load.ptr);
65096564 try reap(f, inst, &.{atomic_load.ptr});
......@@ -6511,7 +6566,7 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
65116566 const ty = ptr_ty.childType(zcu);
65126567
65136568 const repr_ty = if (ty.isRuntimeFloat())
6514 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6569 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
65156570 else
65166571 ty;
65176572
......@@ -6539,7 +6594,8 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
65396594}
65406595
65416596fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CValue {
6542 const zcu = f.object.dg.zcu;
6597 const pt = f.object.dg.pt;
6598 const zcu = pt.zcu;
65436599 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
65446600 const ptr_ty = f.typeOf(bin_op.lhs);
65456601 const ty = ptr_ty.childType(zcu);
......@@ -6551,7 +6607,7 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65516607 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
65526608
65536609 const repr_ty = if (ty.isRuntimeFloat())
6554 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6610 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
65556611 else
65566612 ty;
65576613
......@@ -6574,7 +6630,8 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65746630}
65756631
65766632fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !void {
6577 const zcu = f.object.dg.zcu;
6633 const pt = f.object.dg.pt;
6634 const zcu = pt.zcu;
65786635 if (ptr_ty.isSlice(zcu)) {
65796636 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" });
65806637 } else {
......@@ -6583,14 +6640,15 @@ fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !vo
65836640}
65846641
65856642fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6586 const zcu = f.object.dg.zcu;
6643 const pt = f.object.dg.pt;
6644 const zcu = pt.zcu;
65876645 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
65886646 const dest_ty = f.typeOf(bin_op.lhs);
65896647 const dest_slice = try f.resolveInst(bin_op.lhs);
65906648 const value = try f.resolveInst(bin_op.rhs);
65916649 const elem_ty = f.typeOf(bin_op.rhs);
6592 const elem_abi_size = elem_ty.abiSize(zcu);
6593 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |val| val.isUndefDeep(zcu) else false;
6650 const elem_abi_size = elem_ty.abiSize(pt);
6651 const val_is_undef = if (try f.air.value(bin_op.rhs, pt)) |val| val.isUndefDeep(zcu) else false;
65946652 const writer = f.object.writer();
65956653
65966654 if (val_is_undef) {
......@@ -6628,7 +6686,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66286686 // For the assignment in this loop, the array pointer needs to get
66296687 // casted to a regular pointer, otherwise an error like this occurs:
66306688 // error: array type 'uint32_t[20]' (aka 'unsigned int[20]') is not assignable
6631 const elem_ptr_ty = try zcu.ptrType(.{
6689 const elem_ptr_ty = try pt.ptrType(.{
66326690 .child = elem_ty.toIntern(),
66336691 .flags = .{
66346692 .size = .C,
......@@ -6640,7 +6698,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66406698 try writer.writeAll("for (");
66416699 try f.writeCValue(writer, index, .Other);
66426700 try writer.writeAll(" = ");
6643 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, 0), .Initializer);
6701 try f.object.dg.renderValue(writer, try pt.intValue(Type.usize, 0), .Initializer);
66446702 try writer.writeAll("; ");
66456703 try f.writeCValue(writer, index, .Other);
66466704 try writer.writeAll(" != ");
......@@ -6705,7 +6763,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
67056763}
67066764
67076765fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6708 const zcu = f.object.dg.zcu;
6766 const pt = f.object.dg.pt;
6767 const zcu = pt.zcu;
67096768 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67106769 const dest_ptr = try f.resolveInst(bin_op.lhs);
67116770 const src_ptr = try f.resolveInst(bin_op.rhs);
......@@ -6733,10 +6792,11 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
67336792}
67346793
67356794fn writeArrayLen(f: *Function, writer: ArrayListWriter, dest_ptr: CValue, dest_ty: Type) !void {
6736 const zcu = f.object.dg.zcu;
6795 const pt = f.object.dg.pt;
6796 const zcu = pt.zcu;
67376797 switch (dest_ty.ptrSize(zcu)) {
67386798 .One => try writer.print("{}", .{
6739 try f.fmtIntLiteral(try zcu.intValue(Type.usize, dest_ty.childType(zcu).arrayLen(zcu))),
6799 try f.fmtIntLiteral(try pt.intValue(Type.usize, dest_ty.childType(zcu).arrayLen(zcu))),
67406800 }),
67416801 .Many, .C => unreachable,
67426802 .Slice => try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" }),
......@@ -6744,14 +6804,15 @@ fn writeArrayLen(f: *Function, writer: ArrayListWriter, dest_ptr: CValue, dest_t
67446804}
67456805
67466806fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6747 const zcu = f.object.dg.zcu;
6807 const pt = f.object.dg.pt;
6808 const zcu = pt.zcu;
67486809 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67496810 const union_ptr = try f.resolveInst(bin_op.lhs);
67506811 const new_tag = try f.resolveInst(bin_op.rhs);
67516812 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
67526813
67536814 const union_ty = f.typeOf(bin_op.lhs).childType(zcu);
6754 const layout = union_ty.unionGetLayout(zcu);
6815 const layout = union_ty.unionGetLayout(pt);
67556816 if (layout.tag_size == 0) return .none;
67566817 const tag_ty = union_ty.unionTagTypeSafety(zcu).?;
67576818
......@@ -6765,14 +6826,14 @@ fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67656826}
67666827
67676828fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6768 const zcu = f.object.dg.zcu;
6829 const pt = f.object.dg.pt;
67696830 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67706831
67716832 const operand = try f.resolveInst(ty_op.operand);
67726833 try reap(f, inst, &.{ty_op.operand});
67736834
67746835 const union_ty = f.typeOf(ty_op.operand);
6775 const layout = union_ty.unionGetLayout(zcu);
6836 const layout = union_ty.unionGetLayout(pt);
67766837 if (layout.tag_size == 0) return .none;
67776838
67786839 const inst_ty = f.typeOfIndex(inst);
......@@ -6787,7 +6848,8 @@ fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67876848}
67886849
67896850fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
6790 const zcu = f.object.dg.zcu;
6851 const pt = f.object.dg.pt;
6852 const zcu = pt.zcu;
67916853 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
67926854
67936855 const inst_ty = f.typeOfIndex(inst);
......@@ -6824,7 +6886,8 @@ fn airErrorName(f: *Function, inst: Air.Inst.Index) !CValue {
68246886}
68256887
68266888fn airSplat(f: *Function, inst: Air.Inst.Index) !CValue {
6827 const zcu = f.object.dg.zcu;
6889 const pt = f.object.dg.pt;
6890 const zcu = pt.zcu;
68286891 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
68296892
68306893 const operand = try f.resolveInst(ty_op.operand);
......@@ -6879,7 +6942,7 @@ fn airSelect(f: *Function, inst: Air.Inst.Index) !CValue {
68796942}
68806943
68816944fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6882 const zcu = f.object.dg.zcu;
6945 const pt = f.object.dg.pt;
68836946 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
68846947 const extra = f.air.extraData(Air.Shuffle, ty_pl.payload).data;
68856948
......@@ -6895,11 +6958,11 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
68956958 for (0..extra.mask_len) |index| {
68966959 try f.writeCValue(writer, local, .Other);
68976960 try writer.writeByte('[');
6898 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, index), .Other);
6961 try f.object.dg.renderValue(writer, try pt.intValue(Type.usize, index), .Other);
68996962 try writer.writeAll("] = ");
69006963
6901 const mask_elem = (try mask.elemValue(zcu, index)).toSignedInt(zcu);
6902 const src_val = try zcu.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
6964 const mask_elem = (try mask.elemValue(pt, index)).toSignedInt(pt);
6965 const src_val = try pt.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
69036966
69046967 try f.writeCValue(writer, if (mask_elem >= 0) lhs else rhs, .Other);
69056968 try writer.writeByte('[');
......@@ -6911,7 +6974,8 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
69116974}
69126975
69136976fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6914 const zcu = f.object.dg.zcu;
6977 const pt = f.object.dg.pt;
6978 const zcu = pt.zcu;
69156979 const reduce = f.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
69166980
69176981 const scalar_ty = f.typeOfIndex(inst);
......@@ -6920,7 +6984,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69206984 const operand_ty = f.typeOf(reduce.operand);
69216985 const writer = f.object.writer();
69226986
6923 const use_operator = scalar_ty.bitSize(zcu) <= 64;
6987 const use_operator = scalar_ty.bitSize(pt) <= 64;
69246988 const op: union(enum) {
69256989 const Func = struct { operation: []const u8, info: BuiltinInfo = .none };
69266990 builtin: Func,
......@@ -6971,37 +7035,37 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69717035 try f.object.dg.renderValue(writer, switch (reduce.operation) {
69727036 .Or, .Xor => switch (scalar_ty.zigTypeTag(zcu)) {
69737037 .Bool => Value.false,
6974 .Int => try zcu.intValue(scalar_ty, 0),
7038 .Int => try pt.intValue(scalar_ty, 0),
69757039 else => unreachable,
69767040 },
69777041 .And => switch (scalar_ty.zigTypeTag(zcu)) {
69787042 .Bool => Value.true,
69797043 .Int => switch (scalar_ty.intInfo(zcu).signedness) {
6980 .unsigned => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6981 .signed => try zcu.intValue(scalar_ty, -1),
7044 .unsigned => try scalar_ty.maxIntScalar(pt, scalar_ty),
7045 .signed => try pt.intValue(scalar_ty, -1),
69827046 },
69837047 else => unreachable,
69847048 },
69857049 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
6986 .Int => try zcu.intValue(scalar_ty, 0),
6987 .Float => try zcu.floatValue(scalar_ty, 0.0),
7050 .Int => try pt.intValue(scalar_ty, 0),
7051 .Float => try pt.floatValue(scalar_ty, 0.0),
69887052 else => unreachable,
69897053 },
69907054 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
6991 .Int => try zcu.intValue(scalar_ty, 1),
6992 .Float => try zcu.floatValue(scalar_ty, 1.0),
7055 .Int => try pt.intValue(scalar_ty, 1),
7056 .Float => try pt.floatValue(scalar_ty, 1.0),
69937057 else => unreachable,
69947058 },
69957059 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
69967060 .Bool => Value.true,
6997 .Int => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6998 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
7061 .Int => try scalar_ty.maxIntScalar(pt, scalar_ty),
7062 .Float => try pt.floatValue(scalar_ty, std.math.nan(f128)),
69997063 else => unreachable,
70007064 },
70017065 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
70027066 .Bool => Value.false,
7003 .Int => try scalar_ty.minIntScalar(zcu, scalar_ty),
7004 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
7067 .Int => try scalar_ty.minIntScalar(pt, scalar_ty),
7068 .Float => try pt.floatValue(scalar_ty, std.math.nan(f128)),
70057069 else => unreachable,
70067070 },
70077071 }, .Initializer);
......@@ -7046,7 +7110,8 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
70467110}
70477111
70487112fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7049 const zcu = f.object.dg.zcu;
7113 const pt = f.object.dg.pt;
7114 const zcu = pt.zcu;
70507115 const ip = &zcu.intern_pool;
70517116 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
70527117 const inst_ty = f.typeOfIndex(inst);
......@@ -7096,7 +7161,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70967161 var field_it = loaded_struct.iterateRuntimeOrder(ip);
70977162 while (field_it.next()) |field_index| {
70987163 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
7099 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7164 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71007165
71017166 const a = try Assignment.start(f, writer, try f.ctypeFromType(field_ty, .complete));
71027167 try f.writeCValueMember(writer, local, if (loaded_struct.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -7113,7 +7178,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71137178 try writer.writeAll(" = ");
71147179 const int_info = inst_ty.intInfo(zcu);
71157180
7116 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
7181 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
71177182
71187183 var bit_offset: u64 = 0;
71197184
......@@ -7121,7 +7186,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71217186 for (0..elements.len) |field_index| {
71227187 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
71237188 const field_ty = inst_ty.structFieldType(field_index, zcu);
7124 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7189 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71257190
71267191 if (!empty) {
71277192 try writer.writeAll("zig_or_");
......@@ -7134,7 +7199,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71347199 for (resolved_elements, 0..) |element, field_index| {
71357200 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
71367201 const field_ty = inst_ty.structFieldType(field_index, zcu);
7137 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7202 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71387203
71397204 if (!empty) try writer.writeAll(", ");
71407205 // TODO: Skip this entire shift if val is 0?
......@@ -7160,13 +7225,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71607225 }
71617226
71627227 try writer.print(", {}", .{
7163 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
7228 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
71647229 });
71657230 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);
71667231 try writer.writeByte(')');
71677232 if (!empty) try writer.writeByte(')');
71687233
7169 bit_offset += field_ty.bitSize(zcu);
7234 bit_offset += field_ty.bitSize(pt);
71707235 empty = false;
71717236 }
71727237 try writer.writeAll(";\n");
......@@ -7176,7 +7241,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71767241 .anon_struct_type => |anon_struct_info| for (0..anon_struct_info.types.len) |field_index| {
71777242 if (anon_struct_info.values.get(ip)[field_index] != .none) continue;
71787243 const field_ty = Type.fromInterned(anon_struct_info.types.get(ip)[field_index]);
7179 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7244 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71807245
71817246 const a = try Assignment.start(f, writer, try f.ctypeFromType(field_ty, .complete));
71827247 try f.writeCValueMember(writer, local, if (anon_struct_info.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -7194,7 +7259,8 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71947259}
71957260
71967261fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7197 const zcu = f.object.dg.zcu;
7262 const pt = f.object.dg.pt;
7263 const zcu = pt.zcu;
71987264 const ip = &zcu.intern_pool;
71997265 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
72007266 const extra = f.air.extraData(Air.UnionInit, ty_pl.payload).data;
......@@ -7211,15 +7277,15 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
72117277 if (loaded_union.getLayout(ip) == .@"packed") return f.moveCValue(inst, union_ty, payload);
72127278
72137279 const field: CValue = if (union_ty.unionTagTypeSafety(zcu)) |tag_ty| field: {
7214 const layout = union_ty.unionGetLayout(zcu);
7280 const layout = union_ty.unionGetLayout(pt);
72157281 if (layout.tag_size != 0) {
72167282 const field_index = tag_ty.enumFieldIndex(field_name, zcu).?;
7217 const tag_val = try zcu.enumValueFieldIndex(tag_ty, field_index);
7283 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
72187284
72197285 const a = try Assignment.start(f, writer, try f.ctypeFromType(tag_ty, .complete));
72207286 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });
72217287 try a.assign(f, writer);
7222 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, zcu))});
7288 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, pt))});
72237289 try a.end(f, writer);
72247290 }
72257291 break :field .{ .payload_identifier = field_name.toSlice(ip) };
......@@ -7234,7 +7300,8 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
72347300}
72357301
72367302fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
7237 const zcu = f.object.dg.zcu;
7303 const pt = f.object.dg.pt;
7304 const zcu = pt.zcu;
72387305 const prefetch = f.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
72397306
72407307 const ptr_ty = f.typeOf(prefetch.ptr);
......@@ -7291,7 +7358,8 @@ fn airWasmMemoryGrow(f: *Function, inst: Air.Inst.Index) !CValue {
72917358}
72927359
72937360fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7294 const zcu = f.object.dg.zcu;
7361 const pt = f.object.dg.pt;
7362 const zcu = pt.zcu;
72957363 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
72967364 const bin_op = f.air.extraData(Air.Bin, pl_op.payload).data;
72977365
......@@ -7326,7 +7394,8 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
73267394}
73277395
73287396fn airCVaStart(f: *Function, inst: Air.Inst.Index) !CValue {
7329 const zcu = f.object.dg.zcu;
7397 const pt = f.object.dg.pt;
7398 const zcu = pt.zcu;
73307399 const inst_ty = f.typeOfIndex(inst);
73317400 const decl_index = f.object.dg.pass.decl;
73327401 const decl = zcu.declPtr(decl_index);
......@@ -7699,7 +7768,8 @@ fn formatIntLiteral(
76997768 options: std.fmt.FormatOptions,
77007769 writer: anytype,
77017770) @TypeOf(writer).Error!void {
7702 const zcu = data.dg.zcu;
7771 const pt = data.dg.pt;
7772 const zcu = pt.zcu;
77037773 const target = &data.dg.mod.resolved_target.result;
77047774 const ctype_pool = &data.dg.ctype_pool;
77057775
......@@ -7732,7 +7802,7 @@ fn formatIntLiteral(
77327802 };
77337803 undef_int.truncate(undef_int.toConst(), data.int_info.signedness, data.int_info.bits);
77347804 break :blk undef_int.toConst();
7735 } else data.val.toBigInt(&int_buf, zcu);
7805 } else data.val.toBigInt(&int_buf, pt);
77367806 assert(int.fitsInTwosComp(data.int_info.signedness, data.int_info.bits));
77377807
77387808 const c_bits: usize = @intCast(data.ctype.byteSize(ctype_pool, data.dg.mod) * 8);
......@@ -7866,7 +7936,7 @@ fn formatIntLiteral(
78667936 .int_info = c_limb_int_info,
78677937 .kind = data.kind,
78687938 .ctype = c_limb_ctype,
7869 .val = try zcu.intValue_big(Type.comptime_int, c_limb_mut.toConst()),
7939 .val = try pt.intValue_big(Type.comptime_int, c_limb_mut.toConst()),
78707940 }, fmt, options, writer);
78717941 }
78727942 }
......@@ -7940,17 +8010,18 @@ const Vectorize = struct {
79408010 index: CValue = .none,
79418011
79428012 pub fn start(f: *Function, inst: Air.Inst.Index, writer: anytype, ty: Type) !Vectorize {
7943 const zcu = f.object.dg.zcu;
8013 const pt = f.object.dg.pt;
8014 const zcu = pt.zcu;
79448015 return if (ty.zigTypeTag(zcu) == .Vector) index: {
79458016 const local = try f.allocLocal(inst, Type.usize);
79468017
79478018 try writer.writeAll("for (");
79488019 try f.writeCValue(writer, local, .Other);
7949 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
8020 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 0))});
79508021 try f.writeCValue(writer, local, .Other);
7951 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, ty.vectorLen(zcu)))});
8022 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, ty.vectorLen(zcu)))});
79528023 try f.writeCValue(writer, local, .Other);
7953 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 1))});
8024 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 1))});
79548025 f.object.indent_writer.pushIndent();
79558026
79568027 break :index .{ .index = local };
......@@ -7974,10 +8045,10 @@ const Vectorize = struct {
79748045 }
79758046};
79768047
7977fn lowersToArray(ty: Type, zcu: *Zcu) bool {
7978 return switch (ty.zigTypeTag(zcu)) {
8048fn lowersToArray(ty: Type, pt: Zcu.PerThread) bool {
8049 return switch (ty.zigTypeTag(pt.zcu)) {
79798050 .Array, .Vector => return true,
7980 else => return ty.isAbiInt(zcu) and toCIntBits(@as(u32, @intCast(ty.bitSize(zcu)))) == null,
8051 else => return ty.isAbiInt(pt.zcu) and toCIntBits(@as(u32, @intCast(ty.bitSize(pt)))) == null,
79818052 };
79828053}
79838054
src/codegen/c/Type.zig+33-33
......@@ -1339,11 +1339,11 @@ pub const Pool = struct {
13391339 allocator: std.mem.Allocator,
13401340 scratch: *std.ArrayListUnmanaged(u32),
13411341 ty: Type,
1342 zcu: *Zcu,
1342 pt: Zcu.PerThread,
13431343 mod: *Module,
13441344 kind: Kind,
13451345 ) !CType {
1346 const ip = &zcu.intern_pool;
1346 const ip = &pt.zcu.intern_pool;
13471347 switch (ty.toIntern()) {
13481348 .u0_type,
13491349 .i0_type,
......@@ -1400,7 +1400,7 @@ pub const Pool = struct {
14001400 allocator,
14011401 scratch,
14021402 Type.fromInterned(ip.loadEnumType(ip_index).tag_ty),
1403 zcu,
1403 pt,
14041404 mod,
14051405 kind,
14061406 ),
......@@ -1409,7 +1409,7 @@ pub const Pool = struct {
14091409 .adhoc_inferred_error_set_type,
14101410 => return pool.fromIntInfo(allocator, .{
14111411 .signedness = .unsigned,
1412 .bits = zcu.errorSetBits(),
1412 .bits = pt.zcu.errorSetBits(),
14131413 }, mod, kind),
14141414 .manyptr_u8_type,
14151415 => return pool.getPointer(allocator, .{
......@@ -1492,13 +1492,13 @@ pub const Pool = struct {
14921492 allocator,
14931493 scratch,
14941494 Type.fromInterned(ptr_info.child),
1495 zcu,
1495 pt,
14961496 mod,
14971497 .forward,
14981498 ),
14991499 .alignas = AlignAs.fromAlignment(.{
15001500 .@"align" = ptr_info.flags.alignment,
1501 .abi = Type.fromInterned(ptr_info.child).abiAlignment(zcu),
1501 .abi = Type.fromInterned(ptr_info.child).abiAlignment(pt),
15021502 }),
15031503 };
15041504 break :elem_ctype if (elem.alignas.abiOrder().compare(.gte))
......@@ -1535,7 +1535,7 @@ pub const Pool = struct {
15351535 allocator,
15361536 scratch,
15371537 Type.fromInterned(ip.slicePtrType(ip_index)),
1538 zcu,
1538 pt,
15391539 mod,
15401540 kind,
15411541 ),
......@@ -1560,7 +1560,7 @@ pub const Pool = struct {
15601560 allocator,
15611561 scratch,
15621562 elem_type,
1563 zcu,
1563 pt,
15641564 mod,
15651565 kind.noParameter(),
15661566 );
......@@ -1574,7 +1574,7 @@ pub const Pool = struct {
15741574 .{
15751575 .name = .{ .index = .array },
15761576 .ctype = array_ctype,
1577 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(zcu)),
1577 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(pt)),
15781578 },
15791579 };
15801580 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1586,7 +1586,7 @@ pub const Pool = struct {
15861586 allocator,
15871587 scratch,
15881588 elem_type,
1589 zcu,
1589 pt,
15901590 mod,
15911591 kind.noParameter(),
15921592 );
......@@ -1600,7 +1600,7 @@ pub const Pool = struct {
16001600 .{
16011601 .name = .{ .index = .array },
16021602 .ctype = vector_ctype,
1603 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(zcu)),
1603 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(pt)),
16041604 },
16051605 };
16061606 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1611,7 +1611,7 @@ pub const Pool = struct {
16111611 allocator,
16121612 scratch,
16131613 Type.fromInterned(payload_type),
1614 zcu,
1614 pt,
16151615 mod,
16161616 kind.noParameter(),
16171617 );
......@@ -1635,7 +1635,7 @@ pub const Pool = struct {
16351635 .name = .{ .index = .payload },
16361636 .ctype = payload_ctype,
16371637 .alignas = AlignAs.fromAbiAlignment(
1638 Type.fromInterned(payload_type).abiAlignment(zcu),
1638 Type.fromInterned(payload_type).abiAlignment(pt),
16391639 ),
16401640 },
16411641 };
......@@ -1643,7 +1643,7 @@ pub const Pool = struct {
16431643 },
16441644 .anyframe_type => unreachable,
16451645 .error_union_type => |error_union_info| {
1646 const error_set_bits = zcu.errorSetBits();
1646 const error_set_bits = pt.zcu.errorSetBits();
16471647 const error_set_ctype = try pool.fromIntInfo(allocator, .{
16481648 .signedness = .unsigned,
16491649 .bits = error_set_bits,
......@@ -1654,7 +1654,7 @@ pub const Pool = struct {
16541654 allocator,
16551655 scratch,
16561656 payload_type,
1657 zcu,
1657 pt,
16581658 mod,
16591659 kind.noParameter(),
16601660 );
......@@ -1671,7 +1671,7 @@ pub const Pool = struct {
16711671 .{
16721672 .name = .{ .index = .payload },
16731673 .ctype = payload_ctype,
1674 .alignas = AlignAs.fromAbiAlignment(payload_type.abiAlignment(zcu)),
1674 .alignas = AlignAs.fromAbiAlignment(payload_type.abiAlignment(pt)),
16751675 },
16761676 };
16771677 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1685,7 +1685,7 @@ pub const Pool = struct {
16851685 .tag = .@"struct",
16861686 .name = .{ .owner_decl = loaded_struct.decl.unwrap().? },
16871687 });
1688 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(zcu))
1688 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(pt))
16891689 fwd_decl
16901690 else
16911691 CType.void;
......@@ -1706,7 +1706,7 @@ pub const Pool = struct {
17061706 allocator,
17071707 scratch,
17081708 field_type,
1709 zcu,
1709 pt,
17101710 mod,
17111711 kind.noParameter(),
17121712 );
......@@ -1718,7 +1718,7 @@ pub const Pool = struct {
17181718 String.fromUnnamed(@intCast(field_index));
17191719 const field_alignas = AlignAs.fromAlignment(.{
17201720 .@"align" = loaded_struct.fieldAlign(ip, field_index),
1721 .abi = field_type.abiAlignment(zcu),
1721 .abi = field_type.abiAlignment(pt),
17221722 });
17231723 pool.addHashedExtraAssumeCapacityTo(scratch, &hasher, Field, .{
17241724 .name = field_name.index,
......@@ -1745,7 +1745,7 @@ pub const Pool = struct {
17451745 allocator,
17461746 scratch,
17471747 Type.fromInterned(loaded_struct.backingIntType(ip).*),
1748 zcu,
1748 pt,
17491749 mod,
17501750 kind,
17511751 ),
......@@ -1766,7 +1766,7 @@ pub const Pool = struct {
17661766 allocator,
17671767 scratch,
17681768 field_type,
1769 zcu,
1769 pt,
17701770 mod,
17711771 kind.noParameter(),
17721772 );
......@@ -1780,7 +1780,7 @@ pub const Pool = struct {
17801780 .name = field_name.index,
17811781 .ctype = field_ctype.index,
17821782 .flags = .{ .alignas = AlignAs.fromAbiAlignment(
1783 field_type.abiAlignment(zcu),
1783 field_type.abiAlignment(pt),
17841784 ) },
17851785 });
17861786 }
......@@ -1806,7 +1806,7 @@ pub const Pool = struct {
18061806 extra_index,
18071807 );
18081808 }
1809 const fwd_decl = try pool.fromType(allocator, scratch, ty, zcu, mod, .forward);
1809 const fwd_decl = try pool.fromType(allocator, scratch, ty, pt, mod, .forward);
18101810 try pool.ensureUnusedCapacity(allocator, 1);
18111811 const extra_index = try pool.addHashedExtra(allocator, &hasher, Aggregate, .{
18121812 .fwd_decl = fwd_decl.index,
......@@ -1824,7 +1824,7 @@ pub const Pool = struct {
18241824 .tag = if (has_tag) .@"struct" else .@"union",
18251825 .name = .{ .owner_decl = loaded_union.decl },
18261826 });
1827 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(zcu))
1827 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(pt))
18281828 fwd_decl
18291829 else
18301830 CType.void;
......@@ -1847,7 +1847,7 @@ pub const Pool = struct {
18471847 allocator,
18481848 scratch,
18491849 field_type,
1850 zcu,
1850 pt,
18511851 mod,
18521852 kind.noParameter(),
18531853 );
......@@ -1858,7 +1858,7 @@ pub const Pool = struct {
18581858 );
18591859 const field_alignas = AlignAs.fromAlignment(.{
18601860 .@"align" = loaded_union.fieldAlign(ip, field_index),
1861 .abi = field_type.abiAlignment(zcu),
1861 .abi = field_type.abiAlignment(pt),
18621862 });
18631863 pool.addHashedExtraAssumeCapacityTo(scratch, &hasher, Field, .{
18641864 .name = field_name.index,
......@@ -1895,7 +1895,7 @@ pub const Pool = struct {
18951895 allocator,
18961896 scratch,
18971897 tag_type,
1898 zcu,
1898 pt,
18991899 mod,
19001900 kind.noParameter(),
19011901 );
......@@ -1903,7 +1903,7 @@ pub const Pool = struct {
19031903 struct_fields[struct_fields_len] = .{
19041904 .name = .{ .index = .tag },
19051905 .ctype = tag_ctype,
1906 .alignas = AlignAs.fromAbiAlignment(tag_type.abiAlignment(zcu)),
1906 .alignas = AlignAs.fromAbiAlignment(tag_type.abiAlignment(pt)),
19071907 };
19081908 struct_fields_len += 1;
19091909 }
......@@ -1951,7 +1951,7 @@ pub const Pool = struct {
19511951 },
19521952 .@"packed" => return pool.fromIntInfo(allocator, .{
19531953 .signedness = .unsigned,
1954 .bits = @intCast(ty.bitSize(zcu)),
1954 .bits = @intCast(ty.bitSize(pt)),
19551955 }, mod, kind),
19561956 }
19571957 },
......@@ -1960,7 +1960,7 @@ pub const Pool = struct {
19601960 allocator,
19611961 scratch,
19621962 Type.fromInterned(ip.loadEnumType(ip_index).tag_ty),
1963 zcu,
1963 pt,
19641964 mod,
19651965 kind,
19661966 ),
......@@ -1975,7 +1975,7 @@ pub const Pool = struct {
19751975 allocator,
19761976 scratch,
19771977 return_type,
1978 zcu,
1978 pt,
19791979 mod,
19801980 kind.asParameter(),
19811981 ) else CType.void;
......@@ -1987,7 +1987,7 @@ pub const Pool = struct {
19871987 allocator,
19881988 scratch,
19891989 param_type,
1990 zcu,
1990 pt,
19911991 mod,
19921992 kind.asParameter(),
19931993 );
......@@ -2011,7 +2011,7 @@ pub const Pool = struct {
20112011 .inferred_error_set_type,
20122012 => return pool.fromIntInfo(allocator, .{
20132013 .signedness = .unsigned,
2014 .bits = zcu.errorSetBits(),
2014 .bits = pt.zcu.errorSetBits(),
20152015 }, mod, kind),
20162016
20172017 .undef,
src/codegen/llvm.zig+751-680
......@@ -15,8 +15,6 @@ const link = @import("../link.zig");
1515const Compilation = @import("../Compilation.zig");
1616const build_options = @import("build_options");
1717const Zcu = @import("../Zcu.zig");
18/// Deprecated.
19const Module = Zcu;
2018const InternPool = @import("../InternPool.zig");
2119const Package = @import("../Package.zig");
2220const Air = @import("../Air.zig");
......@@ -810,7 +808,7 @@ pub const Object = struct {
810808 gpa: Allocator,
811809 builder: Builder,
812810
813 module: *Module,
811 pt: Zcu.PerThread,
814812
815813 debug_compile_unit: Builder.Metadata,
816814
......@@ -820,7 +818,7 @@ pub const Object = struct {
820818 debug_enums: std.ArrayListUnmanaged(Builder.Metadata),
821819 debug_globals: std.ArrayListUnmanaged(Builder.Metadata),
822820
823 debug_file_map: std.AutoHashMapUnmanaged(*const Module.File, Builder.Metadata),
821 debug_file_map: std.AutoHashMapUnmanaged(*const Zcu.File, Builder.Metadata),
824822 debug_type_map: std.AutoHashMapUnmanaged(Type, Builder.Metadata),
825823
826824 debug_unresolved_namespace_scopes: std.AutoArrayHashMapUnmanaged(InternPool.NamespaceIndex, Builder.Metadata),
......@@ -992,7 +990,10 @@ pub const Object = struct {
992990 obj.* = .{
993991 .gpa = gpa,
994992 .builder = builder,
995 .module = comp.module.?,
993 .pt = .{
994 .zcu = comp.module.?,
995 .tid = .main,
996 },
996997 .debug_compile_unit = debug_compile_unit,
997998 .debug_enums_fwd_ref = debug_enums_fwd_ref,
998999 .debug_globals_fwd_ref = debug_globals_fwd_ref,
......@@ -1033,7 +1034,8 @@ pub const Object = struct {
10331034 // If o.error_name_table is null, then it was not referenced by any instructions.
10341035 if (o.error_name_table == .none) return;
10351036
1036 const mod = o.module;
1037 const pt = o.pt;
1038 const mod = pt.zcu;
10371039
10381040 const error_name_list = mod.global_error_set.keys();
10391041 const llvm_errors = try mod.gpa.alloc(Builder.Constant, error_name_list.len);
......@@ -1072,7 +1074,7 @@ pub const Object = struct {
10721074 table_variable_index.setMutability(.constant, &o.builder);
10731075 table_variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
10741076 table_variable_index.setAlignment(
1075 slice_ty.abiAlignment(mod).toLlvm(),
1077 slice_ty.abiAlignment(pt).toLlvm(),
10761078 &o.builder,
10771079 );
10781080
......@@ -1083,8 +1085,7 @@ pub const Object = struct {
10831085 // If there is no such function in the module, it means the source code does not need it.
10841086 const name = o.builder.strtabStringIfExists(lt_errors_fn_name) orelse return;
10851087 const llvm_fn = o.builder.getGlobal(name) orelse return;
1086 const mod = o.module;
1087 const errors_len = mod.global_error_set.count();
1088 const errors_len = o.pt.zcu.global_error_set.count();
10881089
10891090 var wip = try Builder.WipFunction.init(&o.builder, .{
10901091 .function = llvm_fn.ptrConst(&o.builder).kind.function,
......@@ -1106,10 +1107,8 @@ pub const Object = struct {
11061107 }
11071108
11081109 fn genModuleLevelAssembly(object: *Object) !void {
1109 const mod = object.module;
1110
11111110 const writer = object.builder.setModuleAsm();
1112 for (mod.global_assembly.values()) |assembly| {
1111 for (object.pt.zcu.global_assembly.values()) |assembly| {
11131112 try writer.print("{s}\n", .{assembly});
11141113 }
11151114 try object.builder.finishModuleAsm();
......@@ -1131,6 +1130,9 @@ pub const Object = struct {
11311130 };
11321131
11331132 pub fn emit(self: *Object, options: EmitOptions) !void {
1133 const zcu = self.pt.zcu;
1134 const comp = zcu.comp;
1135
11341136 {
11351137 try self.genErrorNameTable();
11361138 try self.genCmpLtErrorsLenFunction();
......@@ -1143,8 +1145,8 @@ pub const Object = struct {
11431145 const namespace_index = self.debug_unresolved_namespace_scopes.keys()[i];
11441146 const fwd_ref = self.debug_unresolved_namespace_scopes.values()[i];
11451147
1146 const namespace = self.module.namespacePtr(namespace_index);
1147 const debug_type = try self.lowerDebugType(namespace.getType(self.module));
1148 const namespace = zcu.namespacePtr(namespace_index);
1149 const debug_type = try self.lowerDebugType(namespace.getType(zcu));
11481150
11491151 self.builder.debugForwardReferenceSetType(fwd_ref, debug_type);
11501152 }
......@@ -1206,12 +1208,12 @@ pub const Object = struct {
12061208 try file.writeAll(ptr[0..(bitcode.len * 4)]);
12071209 }
12081210
1209 if (!build_options.have_llvm or !self.module.comp.config.use_lib_llvm) {
1211 if (!build_options.have_llvm or !comp.config.use_lib_llvm) {
12101212 log.err("emitting without libllvm not implemented", .{});
12111213 return error.FailedToEmit;
12121214 }
12131215
1214 initializeLLVMTarget(self.module.comp.root_mod.resolved_target.result.cpu.arch);
1216 initializeLLVMTarget(comp.root_mod.resolved_target.result.cpu.arch);
12151217
12161218 const context: *llvm.Context = llvm.Context.create();
12171219 errdefer context.dispose();
......@@ -1247,8 +1249,8 @@ pub const Object = struct {
12471249 @panic("Invalid LLVM triple");
12481250 }
12491251
1250 const optimize_mode = self.module.comp.root_mod.optimize_mode;
1251 const pic = self.module.comp.root_mod.pic;
1252 const optimize_mode = comp.root_mod.optimize_mode;
1253 const pic = comp.root_mod.pic;
12521254
12531255 const opt_level: llvm.CodeGenOptLevel = if (optimize_mode == .Debug)
12541256 .None
......@@ -1257,12 +1259,12 @@ pub const Object = struct {
12571259
12581260 const reloc_mode: llvm.RelocMode = if (pic)
12591261 .PIC
1260 else if (self.module.comp.config.link_mode == .dynamic)
1262 else if (comp.config.link_mode == .dynamic)
12611263 llvm.RelocMode.DynamicNoPIC
12621264 else
12631265 .Static;
12641266
1265 const code_model: llvm.CodeModel = switch (self.module.comp.root_mod.code_model) {
1267 const code_model: llvm.CodeModel = switch (comp.root_mod.code_model) {
12661268 .default => .Default,
12671269 .tiny => .Tiny,
12681270 .small => .Small,
......@@ -1277,24 +1279,24 @@ pub const Object = struct {
12771279 var target_machine = llvm.TargetMachine.create(
12781280 target,
12791281 target_triple_sentinel,
1280 if (self.module.comp.root_mod.resolved_target.result.cpu.model.llvm_name) |s| s.ptr else null,
1281 self.module.comp.root_mod.resolved_target.llvm_cpu_features.?,
1282 if (comp.root_mod.resolved_target.result.cpu.model.llvm_name) |s| s.ptr else null,
1283 comp.root_mod.resolved_target.llvm_cpu_features.?,
12821284 opt_level,
12831285 reloc_mode,
12841286 code_model,
1285 self.module.comp.function_sections,
1286 self.module.comp.data_sections,
1287 comp.function_sections,
1288 comp.data_sections,
12871289 float_abi,
1288 if (target_util.llvmMachineAbi(self.module.comp.root_mod.resolved_target.result)) |s| s.ptr else null,
1290 if (target_util.llvmMachineAbi(comp.root_mod.resolved_target.result)) |s| s.ptr else null,
12891291 );
12901292 errdefer target_machine.dispose();
12911293
12921294 if (pic) module.setModulePICLevel();
1293 if (self.module.comp.config.pie) module.setModulePIELevel();
1295 if (comp.config.pie) module.setModulePIELevel();
12941296 if (code_model != .Default) module.setModuleCodeModel(code_model);
12951297
1296 if (self.module.comp.llvm_opt_bisect_limit >= 0) {
1297 context.setOptBisectLimit(self.module.comp.llvm_opt_bisect_limit);
1298 if (comp.llvm_opt_bisect_limit >= 0) {
1299 context.setOptBisectLimit(comp.llvm_opt_bisect_limit);
12981300 }
12991301
13001302 // Unfortunately, LLVM shits the bed when we ask for both binary and assembly.
......@@ -1352,11 +1354,13 @@ pub const Object = struct {
13521354
13531355 pub fn updateFunc(
13541356 o: *Object,
1355 zcu: *Module,
1357 pt: Zcu.PerThread,
13561358 func_index: InternPool.Index,
13571359 air: Air,
13581360 liveness: Liveness,
13591361 ) !void {
1362 assert(std.meta.eql(pt, o.pt));
1363 const zcu = pt.zcu;
13601364 const comp = zcu.comp;
13611365 const func = zcu.funcInfo(func_index);
13621366 const decl_index = func.owner_decl;
......@@ -1437,7 +1441,7 @@ pub const Object = struct {
14371441 var llvm_arg_i: u32 = 0;
14381442
14391443 // This gets the LLVM values from the function and stores them in `dg.args`.
1440 const sret = firstParamSRet(fn_info, zcu, target);
1444 const sret = firstParamSRet(fn_info, pt, target);
14411445 const ret_ptr: Builder.Value = if (sret) param: {
14421446 const param = wip.arg(llvm_arg_i);
14431447 llvm_arg_i += 1;
......@@ -1478,8 +1482,8 @@ pub const Object = struct {
14781482 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
14791483 const param = wip.arg(llvm_arg_i);
14801484
1481 if (isByRef(param_ty, zcu)) {
1482 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1485 if (isByRef(param_ty, pt)) {
1486 const alignment = param_ty.abiAlignment(pt).toLlvm();
14831487 const param_llvm_ty = param.typeOfWip(&wip);
14841488 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
14851489 _ = try wip.store(.normal, param, arg_ptr, alignment);
......@@ -1495,12 +1499,12 @@ pub const Object = struct {
14951499 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
14961500 const param_llvm_ty = try o.lowerType(param_ty);
14971501 const param = wip.arg(llvm_arg_i);
1498 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1502 const alignment = param_ty.abiAlignment(pt).toLlvm();
14991503
15001504 try o.addByRefParamAttrs(&attributes, llvm_arg_i, alignment, it.byval_attr, param_llvm_ty);
15011505 llvm_arg_i += 1;
15021506
1503 if (isByRef(param_ty, zcu)) {
1507 if (isByRef(param_ty, pt)) {
15041508 args.appendAssumeCapacity(param);
15051509 } else {
15061510 args.appendAssumeCapacity(try wip.load(.normal, param_llvm_ty, param, alignment, ""));
......@@ -1510,12 +1514,12 @@ pub const Object = struct {
15101514 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
15111515 const param_llvm_ty = try o.lowerType(param_ty);
15121516 const param = wip.arg(llvm_arg_i);
1513 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1517 const alignment = param_ty.abiAlignment(pt).toLlvm();
15141518
15151519 try attributes.addParamAttr(llvm_arg_i, .noundef, &o.builder);
15161520 llvm_arg_i += 1;
15171521
1518 if (isByRef(param_ty, zcu)) {
1522 if (isByRef(param_ty, pt)) {
15191523 args.appendAssumeCapacity(param);
15201524 } else {
15211525 args.appendAssumeCapacity(try wip.load(.normal, param_llvm_ty, param, alignment, ""));
......@@ -1528,11 +1532,11 @@ pub const Object = struct {
15281532 llvm_arg_i += 1;
15291533
15301534 const param_llvm_ty = try o.lowerType(param_ty);
1531 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1535 const alignment = param_ty.abiAlignment(pt).toLlvm();
15321536 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
15331537 _ = try wip.store(.normal, param, arg_ptr, alignment);
15341538
1535 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1539 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
15361540 arg_ptr
15371541 else
15381542 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1556,7 +1560,7 @@ pub const Object = struct {
15561560 const elem_align = (if (ptr_info.flags.alignment != .none)
15571561 @as(InternPool.Alignment, ptr_info.flags.alignment)
15581562 else
1559 Type.fromInterned(ptr_info.child).abiAlignment(zcu).max(.@"1")).toLlvm();
1563 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1")).toLlvm();
15601564 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align }, &o.builder);
15611565 const ptr_param = wip.arg(llvm_arg_i);
15621566 llvm_arg_i += 1;
......@@ -1573,7 +1577,7 @@ pub const Object = struct {
15731577 const field_types = it.types_buffer[0..it.types_len];
15741578 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
15751579 const param_llvm_ty = try o.lowerType(param_ty);
1576 const param_alignment = param_ty.abiAlignment(zcu).toLlvm();
1580 const param_alignment = param_ty.abiAlignment(pt).toLlvm();
15771581 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, param_alignment, target);
15781582 const llvm_ty = try o.builder.structType(.normal, field_types);
15791583 for (0..field_types.len) |field_i| {
......@@ -1585,7 +1589,7 @@ pub const Object = struct {
15851589 _ = try wip.store(.normal, param, field_ptr, alignment);
15861590 }
15871591
1588 const is_by_ref = isByRef(param_ty, zcu);
1592 const is_by_ref = isByRef(param_ty, pt);
15891593 args.appendAssumeCapacity(if (is_by_ref)
15901594 arg_ptr
15911595 else
......@@ -1603,11 +1607,11 @@ pub const Object = struct {
16031607 const param = wip.arg(llvm_arg_i);
16041608 llvm_arg_i += 1;
16051609
1606 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1610 const alignment = param_ty.abiAlignment(pt).toLlvm();
16071611 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
16081612 _ = try wip.store(.normal, param, arg_ptr, alignment);
16091613
1610 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1614 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
16111615 arg_ptr
16121616 else
16131617 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1618,11 +1622,11 @@ pub const Object = struct {
16181622 const param = wip.arg(llvm_arg_i);
16191623 llvm_arg_i += 1;
16201624
1621 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1625 const alignment = param_ty.abiAlignment(pt).toLlvm();
16221626 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
16231627 _ = try wip.store(.normal, param, arg_ptr, alignment);
16241628
1625 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1629 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
16261630 arg_ptr
16271631 else
16281632 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1700,8 +1704,9 @@ pub const Object = struct {
17001704 try fg.wip.finish();
17011705 }
17021706
1703 pub fn updateDecl(self: *Object, module: *Module, decl_index: InternPool.DeclIndex) !void {
1704 const decl = module.declPtr(decl_index);
1707 pub fn updateDecl(self: *Object, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
1708 assert(std.meta.eql(pt, self.pt));
1709 const decl = pt.zcu.declPtr(decl_index);
17051710 var dg: DeclGen = .{
17061711 .object = self,
17071712 .decl = decl,
......@@ -1711,7 +1716,7 @@ pub const Object = struct {
17111716 dg.genDecl() catch |err| switch (err) {
17121717 error.CodegenFail => {
17131718 decl.analysis = .codegen_failure;
1714 try module.failed_analysis.put(module.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), dg.err_msg.?);
1719 try pt.zcu.failed_analysis.put(pt.zcu.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), dg.err_msg.?);
17151720 dg.err_msg = null;
17161721 return;
17171722 },
......@@ -1721,10 +1726,12 @@ pub const Object = struct {
17211726
17221727 pub fn updateExports(
17231728 self: *Object,
1724 zcu: *Zcu,
1725 exported: Module.Exported,
1729 pt: Zcu.PerThread,
1730 exported: Zcu.Exported,
17261731 export_indices: []const u32,
17271732 ) link.File.UpdateExportsError!void {
1733 assert(std.meta.eql(pt, self.pt));
1734 const zcu = pt.zcu;
17281735 const decl_index = switch (exported) {
17291736 .decl_index => |i| i,
17301737 .value => |val| return updateExportedValue(self, zcu, val, export_indices),
......@@ -1748,7 +1755,7 @@ pub const Object = struct {
17481755
17491756 fn updateExportedValue(
17501757 o: *Object,
1751 mod: *Module,
1758 mod: *Zcu,
17521759 exported_value: InternPool.Index,
17531760 export_indices: []const u32,
17541761 ) link.File.UpdateExportsError!void {
......@@ -1783,7 +1790,7 @@ pub const Object = struct {
17831790
17841791 fn updateExportedGlobal(
17851792 o: *Object,
1786 mod: *Module,
1793 mod: *Zcu,
17871794 global_index: Builder.Global.Index,
17881795 export_indices: []const u32,
17891796 ) link.File.UpdateExportsError!void {
......@@ -1879,7 +1886,7 @@ pub const Object = struct {
18791886 global.delete(&self.builder);
18801887 }
18811888
1882 fn getDebugFile(o: *Object, file: *const Module.File) Allocator.Error!Builder.Metadata {
1889 fn getDebugFile(o: *Object, file: *const Zcu.File) Allocator.Error!Builder.Metadata {
18831890 const gpa = o.gpa;
18841891 const gop = try o.debug_file_map.getOrPut(gpa, file);
18851892 errdefer assert(o.debug_file_map.remove(file));
......@@ -1909,7 +1916,8 @@ pub const Object = struct {
19091916
19101917 const gpa = o.gpa;
19111918 const target = o.target;
1912 const zcu = o.module;
1919 const pt = o.pt;
1920 const zcu = pt.zcu;
19131921 const ip = &zcu.intern_pool;
19141922
19151923 if (o.debug_type_map.get(ty)) |debug_type| return debug_type;
......@@ -1931,7 +1939,7 @@ pub const Object = struct {
19311939 const name = try o.allocTypeName(ty);
19321940 defer gpa.free(name);
19331941 const builder_name = try o.builder.metadataString(name);
1934 const debug_bits = ty.abiSize(zcu) * 8; // lldb cannot handle non-byte sized types
1942 const debug_bits = ty.abiSize(pt) * 8; // lldb cannot handle non-byte sized types
19351943 const debug_int_type = switch (info.signedness) {
19361944 .signed => try o.builder.debugSignedType(builder_name, debug_bits),
19371945 .unsigned => try o.builder.debugUnsignedType(builder_name, debug_bits),
......@@ -1941,9 +1949,9 @@ pub const Object = struct {
19411949 },
19421950 .Enum => {
19431951 const owner_decl_index = ty.getOwnerDecl(zcu);
1944 const owner_decl = o.module.declPtr(owner_decl_index);
1952 const owner_decl = zcu.declPtr(owner_decl_index);
19451953
1946 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1954 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
19471955 const debug_enum_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
19481956 try o.debug_type_map.put(gpa, ty, debug_enum_type);
19491957 return debug_enum_type;
......@@ -1961,7 +1969,7 @@ pub const Object = struct {
19611969 for (enum_type.names.get(ip), 0..) |field_name_ip, i| {
19621970 var bigint_space: Value.BigIntSpace = undefined;
19631971 const bigint = if (enum_type.values.len != 0)
1964 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, zcu)
1972 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, pt)
19651973 else
19661974 std.math.big.int.Mutable.init(&bigint_space.limbs, i).toConst();
19671975
......@@ -1986,8 +1994,8 @@ pub const Object = struct {
19861994 scope,
19871995 owner_decl.typeSrcLine(zcu) + 1, // Line
19881996 try o.lowerDebugType(int_ty),
1989 ty.abiSize(zcu) * 8,
1990 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
1997 ty.abiSize(pt) * 8,
1998 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
19911999 try o.builder.debugTuple(enumerators),
19922000 );
19932001
......@@ -2027,10 +2035,10 @@ pub const Object = struct {
20272035 ptr_info.flags.is_const or
20282036 ptr_info.flags.is_volatile or
20292037 ptr_info.flags.size == .Many or ptr_info.flags.size == .C or
2030 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
2038 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(pt))
20312039 {
2032 const bland_ptr_ty = try zcu.ptrType(.{
2033 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
2040 const bland_ptr_ty = try pt.ptrType(.{
2041 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(pt))
20342042 .anyopaque_type
20352043 else
20362044 ptr_info.child,
......@@ -2060,10 +2068,10 @@ pub const Object = struct {
20602068 defer gpa.free(name);
20612069 const line = 0;
20622070
2063 const ptr_size = ptr_ty.abiSize(zcu);
2064 const ptr_align = ptr_ty.abiAlignment(zcu);
2065 const len_size = len_ty.abiSize(zcu);
2066 const len_align = len_ty.abiAlignment(zcu);
2071 const ptr_size = ptr_ty.abiSize(pt);
2072 const ptr_align = ptr_ty.abiAlignment(pt);
2073 const len_size = len_ty.abiSize(pt);
2074 const len_align = len_ty.abiAlignment(pt);
20672075
20682076 const len_offset = len_align.forward(ptr_size);
20692077
......@@ -2095,8 +2103,8 @@ pub const Object = struct {
20952103 o.debug_compile_unit, // Scope
20962104 line,
20972105 .none, // Underlying type
2098 ty.abiSize(zcu) * 8,
2099 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2106 ty.abiSize(pt) * 8,
2107 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
21002108 try o.builder.debugTuple(&.{
21012109 debug_ptr_type,
21022110 debug_len_type,
......@@ -2124,7 +2132,7 @@ pub const Object = struct {
21242132 0, // Line
21252133 debug_elem_ty,
21262134 target.ptrBitWidth(),
2127 (ty.ptrAlignment(zcu).toByteUnits() orelse 0) * 8,
2135 (ty.ptrAlignment(pt).toByteUnits() orelse 0) * 8,
21282136 0, // Offset
21292137 );
21302138
......@@ -2149,7 +2157,7 @@ pub const Object = struct {
21492157 const name = try o.allocTypeName(ty);
21502158 defer gpa.free(name);
21512159 const owner_decl_index = ty.getOwnerDecl(zcu);
2152 const owner_decl = o.module.declPtr(owner_decl_index);
2160 const owner_decl = zcu.declPtr(owner_decl_index);
21532161 const file_scope = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu);
21542162 const debug_opaque_type = try o.builder.debugStructType(
21552163 try o.builder.metadataString(name),
......@@ -2171,8 +2179,8 @@ pub const Object = struct {
21712179 .none, // Scope
21722180 0, // Line
21732181 try o.lowerDebugType(ty.childType(zcu)),
2174 ty.abiSize(zcu) * 8,
2175 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2182 ty.abiSize(pt) * 8,
2183 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
21762184 try o.builder.debugTuple(&.{
21772185 try o.builder.debugSubrange(
21782186 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
......@@ -2214,8 +2222,8 @@ pub const Object = struct {
22142222 .none, // Scope
22152223 0, // Line
22162224 debug_elem_type,
2217 ty.abiSize(zcu) * 8,
2218 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2225 ty.abiSize(pt) * 8,
2226 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
22192227 try o.builder.debugTuple(&.{
22202228 try o.builder.debugSubrange(
22212229 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
......@@ -2231,7 +2239,7 @@ pub const Object = struct {
22312239 const name = try o.allocTypeName(ty);
22322240 defer gpa.free(name);
22332241 const child_ty = ty.optionalChild(zcu);
2234 if (!child_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2242 if (!child_ty.hasRuntimeBitsIgnoreComptime(pt)) {
22352243 const debug_bool_type = try o.builder.debugBoolType(
22362244 try o.builder.metadataString(name),
22372245 8,
......@@ -2258,10 +2266,10 @@ pub const Object = struct {
22582266 }
22592267
22602268 const non_null_ty = Type.u8;
2261 const payload_size = child_ty.abiSize(zcu);
2262 const payload_align = child_ty.abiAlignment(zcu);
2263 const non_null_size = non_null_ty.abiSize(zcu);
2264 const non_null_align = non_null_ty.abiAlignment(zcu);
2269 const payload_size = child_ty.abiSize(pt);
2270 const payload_align = child_ty.abiAlignment(pt);
2271 const non_null_size = non_null_ty.abiSize(pt);
2272 const non_null_align = non_null_ty.abiAlignment(pt);
22652273 const non_null_offset = non_null_align.forward(payload_size);
22662274
22672275 const debug_data_type = try o.builder.debugMemberType(
......@@ -2292,8 +2300,8 @@ pub const Object = struct {
22922300 o.debug_compile_unit, // Scope
22932301 0, // Line
22942302 .none, // Underlying type
2295 ty.abiSize(zcu) * 8,
2296 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2303 ty.abiSize(pt) * 8,
2304 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
22972305 try o.builder.debugTuple(&.{
22982306 debug_data_type,
22992307 debug_some_type,
......@@ -2310,7 +2318,7 @@ pub const Object = struct {
23102318 },
23112319 .ErrorUnion => {
23122320 const payload_ty = ty.errorUnionPayload(zcu);
2313 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2321 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23142322 // TODO: Maybe remove?
23152323 const debug_error_union_type = try o.lowerDebugType(Type.anyerror);
23162324 try o.debug_type_map.put(gpa, ty, debug_error_union_type);
......@@ -2320,10 +2328,10 @@ pub const Object = struct {
23202328 const name = try o.allocTypeName(ty);
23212329 defer gpa.free(name);
23222330
2323 const error_size = Type.anyerror.abiSize(zcu);
2324 const error_align = Type.anyerror.abiAlignment(zcu);
2325 const payload_size = payload_ty.abiSize(zcu);
2326 const payload_align = payload_ty.abiAlignment(zcu);
2331 const error_size = Type.anyerror.abiSize(pt);
2332 const error_align = Type.anyerror.abiAlignment(pt);
2333 const payload_size = payload_ty.abiSize(pt);
2334 const payload_align = payload_ty.abiAlignment(pt);
23272335
23282336 var error_index: u32 = undefined;
23292337 var payload_index: u32 = undefined;
......@@ -2371,8 +2379,8 @@ pub const Object = struct {
23712379 o.debug_compile_unit, // Sope
23722380 0, // Line
23732381 .none, // Underlying type
2374 ty.abiSize(zcu) * 8,
2375 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2382 ty.abiSize(pt) * 8,
2383 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
23762384 try o.builder.debugTuple(&fields),
23772385 );
23782386
......@@ -2399,8 +2407,8 @@ pub const Object = struct {
23992407 const info = Type.fromInterned(backing_int_ty).intInfo(zcu);
24002408 const builder_name = try o.builder.metadataString(name);
24012409 const debug_int_type = switch (info.signedness) {
2402 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(zcu) * 8),
2403 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(zcu) * 8),
2410 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(pt) * 8),
2411 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(pt) * 8),
24042412 };
24052413 try o.debug_type_map.put(gpa, ty, debug_int_type);
24062414 return debug_int_type;
......@@ -2420,10 +2428,10 @@ pub const Object = struct {
24202428 const debug_fwd_ref = try o.builder.debugForwardReference();
24212429
24222430 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
2423 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(zcu)) continue;
2431 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
24242432
2425 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2426 const field_align = Type.fromInterned(field_ty).abiAlignment(zcu);
2433 const field_size = Type.fromInterned(field_ty).abiSize(pt);
2434 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
24272435 const field_offset = field_align.forward(offset);
24282436 offset = field_offset + field_size;
24292437
......@@ -2451,8 +2459,8 @@ pub const Object = struct {
24512459 o.debug_compile_unit, // Scope
24522460 0, // Line
24532461 .none, // Underlying type
2454 ty.abiSize(zcu) * 8,
2455 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2462 ty.abiSize(pt) * 8,
2463 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
24562464 try o.builder.debugTuple(fields.items),
24572465 );
24582466
......@@ -2479,7 +2487,7 @@ pub const Object = struct {
24792487 else => {},
24802488 }
24812489
2482 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2490 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
24832491 const owner_decl_index = ty.getOwnerDecl(zcu);
24842492 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
24852493 try o.debug_type_map.put(gpa, ty, debug_struct_type);
......@@ -2502,14 +2510,14 @@ pub const Object = struct {
25022510 var it = struct_type.iterateRuntimeOrder(ip);
25032511 while (it.next()) |field_index| {
25042512 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
2505 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2506 const field_size = field_ty.abiSize(zcu);
2507 const field_align = zcu.structFieldAlignment(
2513 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
2514 const field_size = field_ty.abiSize(pt);
2515 const field_align = pt.structFieldAlignment(
25082516 struct_type.fieldAlign(ip, field_index),
25092517 field_ty,
25102518 struct_type.layout,
25112519 );
2512 const field_offset = ty.structFieldOffset(field_index, zcu);
2520 const field_offset = ty.structFieldOffset(field_index, pt);
25132521
25142522 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse
25152523 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
......@@ -2532,8 +2540,8 @@ pub const Object = struct {
25322540 o.debug_compile_unit, // Scope
25332541 0, // Line
25342542 .none, // Underlying type
2535 ty.abiSize(zcu) * 8,
2536 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2543 ty.abiSize(pt) * 8,
2544 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
25372545 try o.builder.debugTuple(fields.items),
25382546 );
25392547
......@@ -2553,7 +2561,7 @@ pub const Object = struct {
25532561
25542562 const union_type = ip.loadUnionType(ty.toIntern());
25552563 if (!union_type.haveFieldTypes(ip) or
2556 !ty.hasRuntimeBitsIgnoreComptime(zcu) or
2564 !ty.hasRuntimeBitsIgnoreComptime(pt) or
25572565 !union_type.haveLayout(ip))
25582566 {
25592567 const debug_union_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
......@@ -2561,7 +2569,7 @@ pub const Object = struct {
25612569 return debug_union_type;
25622570 }
25632571
2564 const layout = zcu.getUnionLayout(union_type);
2572 const layout = pt.getUnionLayout(union_type);
25652573
25662574 const debug_fwd_ref = try o.builder.debugForwardReference();
25672575
......@@ -2575,8 +2583,8 @@ pub const Object = struct {
25752583 o.debug_compile_unit, // Scope
25762584 0, // Line
25772585 .none, // Underlying type
2578 ty.abiSize(zcu) * 8,
2579 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2586 ty.abiSize(pt) * 8,
2587 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
25802588 try o.builder.debugTuple(
25812589 &.{try o.lowerDebugType(Type.fromInterned(union_type.enum_tag_ty))},
25822590 ),
......@@ -2603,12 +2611,12 @@ pub const Object = struct {
26032611
26042612 for (0..tag_type.names.len) |field_index| {
26052613 const field_ty = union_type.field_types.get(ip)[field_index];
2606 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2614 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
26072615
2608 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2616 const field_size = Type.fromInterned(field_ty).abiSize(pt);
26092617 const field_align: InternPool.Alignment = switch (union_type.flagsPtr(ip).layout) {
26102618 .@"packed" => .none,
2611 .auto, .@"extern" => zcu.unionFieldNormalAlignment(union_type, @intCast(field_index)),
2619 .auto, .@"extern" => pt.unionFieldNormalAlignment(union_type, @intCast(field_index)),
26122620 };
26132621
26142622 const field_name = tag_type.names.get(ip)[field_index];
......@@ -2637,8 +2645,8 @@ pub const Object = struct {
26372645 o.debug_compile_unit, // Scope
26382646 0, // Line
26392647 .none, // Underlying type
2640 ty.abiSize(zcu) * 8,
2641 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2648 ty.abiSize(pt) * 8,
2649 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
26422650 try o.builder.debugTuple(fields.items),
26432651 );
26442652
......@@ -2696,8 +2704,8 @@ pub const Object = struct {
26962704 o.debug_compile_unit, // Scope
26972705 0, // Line
26982706 .none, // Underlying type
2699 ty.abiSize(zcu) * 8,
2700 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2707 ty.abiSize(pt) * 8,
2708 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
27012709 try o.builder.debugTuple(&full_fields),
27022710 );
27032711
......@@ -2718,13 +2726,13 @@ pub const Object = struct {
27182726 try debug_param_types.ensureUnusedCapacity(3 + fn_info.param_types.len);
27192727
27202728 // Return type goes first.
2721 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(zcu)) {
2722 const sret = firstParamSRet(fn_info, zcu, target);
2729 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(pt)) {
2730 const sret = firstParamSRet(fn_info, pt, target);
27232731 const ret_ty = if (sret) Type.void else Type.fromInterned(fn_info.return_type);
27242732 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ret_ty));
27252733
27262734 if (sret) {
2727 const ptr_ty = try zcu.singleMutPtrType(Type.fromInterned(fn_info.return_type));
2735 const ptr_ty = try pt.singleMutPtrType(Type.fromInterned(fn_info.return_type));
27282736 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27292737 }
27302738 } else {
......@@ -2732,18 +2740,18 @@ pub const Object = struct {
27322740 }
27332741
27342742 if (Type.fromInterned(fn_info.return_type).isError(zcu) and
2735 o.module.comp.config.any_error_tracing)
2743 zcu.comp.config.any_error_tracing)
27362744 {
2737 const ptr_ty = try zcu.singleMutPtrType(try o.getStackTraceType());
2745 const ptr_ty = try pt.singleMutPtrType(try o.getStackTraceType());
27382746 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27392747 }
27402748
27412749 for (0..fn_info.param_types.len) |i| {
27422750 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[i]);
2743 if (!param_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2751 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
27442752
2745 if (isByRef(param_ty, zcu)) {
2746 const ptr_ty = try zcu.singleMutPtrType(param_ty);
2753 if (isByRef(param_ty, pt)) {
2754 const ptr_ty = try pt.singleMutPtrType(param_ty);
27472755 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27482756 } else {
27492757 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(param_ty));
......@@ -2770,7 +2778,7 @@ pub const Object = struct {
27702778 }
27712779
27722780 fn namespaceToDebugScope(o: *Object, namespace_index: InternPool.NamespaceIndex) !Builder.Metadata {
2773 const zcu = o.module;
2781 const zcu = o.pt.zcu;
27742782 const namespace = zcu.namespacePtr(namespace_index);
27752783 const file_scope = namespace.fileScope(zcu);
27762784 if (namespace.parent == .none) return try o.getDebugFile(file_scope);
......@@ -2783,7 +2791,7 @@ pub const Object = struct {
27832791 }
27842792
27852793 fn makeEmptyNamespaceDebugType(o: *Object, decl_index: InternPool.DeclIndex) !Builder.Metadata {
2786 const zcu = o.module;
2794 const zcu = o.pt.zcu;
27872795 const decl = zcu.declPtr(decl_index);
27882796 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
27892797 return o.builder.debugStructType(
......@@ -2799,7 +2807,7 @@ pub const Object = struct {
27992807 }
28002808
28012809 fn getStackTraceType(o: *Object) Allocator.Error!Type {
2802 const zcu = o.module;
2810 const zcu = o.pt.zcu;
28032811
28042812 const std_mod = zcu.std_mod;
28052813 const std_file_imported = zcu.importPkg(std_mod) catch unreachable;
......@@ -2807,13 +2815,13 @@ pub const Object = struct {
28072815 const builtin_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "builtin", .no_embedded_nulls);
28082816 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index);
28092817 const std_namespace = zcu.namespacePtr(zcu.declPtr(std_file_root_decl.unwrap().?).src_namespace);
2810 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Module.DeclAdapter{ .zcu = zcu }).?;
2818 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }).?;
28112819
28122820 const stack_trace_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "StackTrace", .no_embedded_nulls);
28132821 // buffer is only used for int_type, `builtin` is a struct.
28142822 const builtin_ty = zcu.declPtr(builtin_decl).val.toType();
28152823 const builtin_namespace = zcu.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(zcu)).?;
2816 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = zcu }).?;
2824 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Zcu.DeclAdapter{ .zcu = zcu }).?;
28172825 const stack_trace_decl = zcu.declPtr(stack_trace_decl_index);
28182826
28192827 // Sema should have ensured that StackTrace was analyzed.
......@@ -2824,7 +2832,7 @@ pub const Object = struct {
28242832 fn allocTypeName(o: *Object, ty: Type) Allocator.Error![:0]const u8 {
28252833 var buffer = std.ArrayList(u8).init(o.gpa);
28262834 errdefer buffer.deinit();
2827 try ty.print(buffer.writer(), o.module);
2835 try ty.print(buffer.writer(), o.pt);
28282836 return buffer.toOwnedSliceSentinel(0);
28292837 }
28302838
......@@ -2835,7 +2843,8 @@ pub const Object = struct {
28352843 o: *Object,
28362844 decl_index: InternPool.DeclIndex,
28372845 ) Allocator.Error!Builder.Function.Index {
2838 const zcu = o.module;
2846 const pt = o.pt;
2847 const zcu = pt.zcu;
28392848 const ip = &zcu.intern_pool;
28402849 const gpa = o.gpa;
28412850 const decl = zcu.declPtr(decl_index);
......@@ -2848,7 +2857,7 @@ pub const Object = struct {
28482857 assert(decl.has_tv);
28492858 const fn_info = zcu.typeToFunc(zig_fn_type).?;
28502859 const target = owner_mod.resolved_target.result;
2851 const sret = firstParamSRet(fn_info, zcu, target);
2860 const sret = firstParamSRet(fn_info, pt, target);
28522861
28532862 const is_extern = decl.isExtern(zcu);
28542863 const function_index = try o.builder.addFunction(
......@@ -2929,14 +2938,14 @@ pub const Object = struct {
29292938 .byval => {
29302939 const param_index = it.zig_index - 1;
29312940 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
2932 if (!isByRef(param_ty, zcu)) {
2941 if (!isByRef(param_ty, pt)) {
29332942 try o.addByValParamAttrs(&attributes, param_ty, param_index, fn_info, it.llvm_index - 1);
29342943 }
29352944 },
29362945 .byref => {
29372946 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
29382947 const param_llvm_ty = try o.lowerType(param_ty);
2939 const alignment = param_ty.abiAlignment(zcu);
2948 const alignment = param_ty.abiAlignment(pt);
29402949 try o.addByRefParamAttrs(&attributes, it.llvm_index - 1, alignment.toLlvm(), it.byval_attr, param_llvm_ty);
29412950 },
29422951 .byref_mut => try attributes.addParamAttr(it.llvm_index - 1, .noundef, &o.builder),
......@@ -2964,7 +2973,7 @@ pub const Object = struct {
29642973 attributes: *Builder.FunctionAttributes.Wip,
29652974 owner_mod: *Package.Module,
29662975 ) Allocator.Error!void {
2967 const comp = o.module.comp;
2976 const comp = o.pt.zcu.comp;
29682977
29692978 if (!owner_mod.red_zone) {
29702979 try attributes.addFnAttr(.noredzone, &o.builder);
......@@ -3039,7 +3048,7 @@ pub const Object = struct {
30393048 }
30403049 errdefer assert(o.anon_decl_map.remove(decl_val));
30413050
3042 const mod = o.module;
3051 const mod = o.pt.zcu;
30433052 const decl_ty = mod.intern_pool.typeOf(decl_val);
30443053
30453054 const variable_index = try o.builder.addVariable(
......@@ -3065,7 +3074,7 @@ pub const Object = struct {
30653074 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.variable;
30663075 errdefer assert(o.decl_map.remove(decl_index));
30673076
3068 const zcu = o.module;
3077 const zcu = o.pt.zcu;
30693078 const decl = zcu.declPtr(decl_index);
30703079 const is_extern = decl.isExtern(zcu);
30713080
......@@ -3100,11 +3109,12 @@ pub const Object = struct {
31003109 }
31013110
31023111 fn errorIntType(o: *Object) Allocator.Error!Builder.Type {
3103 return o.builder.intType(o.module.errorSetBits());
3112 return o.builder.intType(o.pt.zcu.errorSetBits());
31043113 }
31053114
31063115 fn lowerType(o: *Object, t: Type) Allocator.Error!Builder.Type {
3107 const mod = o.module;
3116 const pt = o.pt;
3117 const mod = pt.zcu;
31083118 const target = mod.getTarget();
31093119 const ip = &mod.intern_pool;
31103120 return switch (t.toIntern()) {
......@@ -3230,7 +3240,7 @@ pub const Object = struct {
32303240 ),
32313241 .opt_type => |child_ty| {
32323242 // Must stay in sync with `opt_payload` logic in `lowerPtr`.
3233 if (!Type.fromInterned(child_ty).hasRuntimeBitsIgnoreComptime(mod)) return .i8;
3243 if (!Type.fromInterned(child_ty).hasRuntimeBitsIgnoreComptime(pt)) return .i8;
32343244
32353245 const payload_ty = try o.lowerType(Type.fromInterned(child_ty));
32363246 if (t.optionalReprIsPayload(mod)) return payload_ty;
......@@ -3238,8 +3248,8 @@ pub const Object = struct {
32383248 comptime assert(optional_layout_version == 3);
32393249 var fields: [3]Builder.Type = .{ payload_ty, .i8, undefined };
32403250 var fields_len: usize = 2;
3241 const offset = Type.fromInterned(child_ty).abiSize(mod) + 1;
3242 const abi_size = t.abiSize(mod);
3251 const offset = Type.fromInterned(child_ty).abiSize(pt) + 1;
3252 const abi_size = t.abiSize(pt);
32433253 const padding_len = abi_size - offset;
32443254 if (padding_len > 0) {
32453255 fields[2] = try o.builder.arrayType(padding_len, .i8);
......@@ -3252,16 +3262,16 @@ pub const Object = struct {
32523262 // Must stay in sync with `codegen.errUnionPayloadOffset`.
32533263 // See logic in `lowerPtr`.
32543264 const error_type = try o.errorIntType();
3255 if (!Type.fromInterned(error_union_type.payload_type).hasRuntimeBitsIgnoreComptime(mod))
3265 if (!Type.fromInterned(error_union_type.payload_type).hasRuntimeBitsIgnoreComptime(pt))
32563266 return error_type;
32573267 const payload_type = try o.lowerType(Type.fromInterned(error_union_type.payload_type));
3258 const err_int_ty = try mod.errorIntType();
3268 const err_int_ty = try o.pt.errorIntType();
32593269
3260 const payload_align = Type.fromInterned(error_union_type.payload_type).abiAlignment(mod);
3261 const error_align = err_int_ty.abiAlignment(mod);
3270 const payload_align = Type.fromInterned(error_union_type.payload_type).abiAlignment(pt);
3271 const error_align = err_int_ty.abiAlignment(pt);
32623272
3263 const payload_size = Type.fromInterned(error_union_type.payload_type).abiSize(mod);
3264 const error_size = err_int_ty.abiSize(mod);
3273 const payload_size = Type.fromInterned(error_union_type.payload_type).abiSize(pt);
3274 const error_size = err_int_ty.abiSize(pt);
32653275
32663276 var fields: [3]Builder.Type = undefined;
32673277 var fields_len: usize = 2;
......@@ -3317,12 +3327,12 @@ pub const Object = struct {
33173327 var it = struct_type.iterateRuntimeOrder(ip);
33183328 while (it.next()) |field_index| {
33193329 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
3320 const field_align = mod.structFieldAlignment(
3330 const field_align = pt.structFieldAlignment(
33213331 struct_type.fieldAlign(ip, field_index),
33223332 field_ty,
33233333 struct_type.layout,
33243334 );
3325 const field_ty_align = field_ty.abiAlignment(mod);
3335 const field_ty_align = field_ty.abiAlignment(pt);
33263336 if (field_align.compare(.lt, field_ty_align)) struct_kind = .@"packed";
33273337 big_align = big_align.max(field_align);
33283338 const prev_offset = offset;
......@@ -3334,7 +3344,7 @@ pub const Object = struct {
33343344 try o.builder.arrayType(padding_len, .i8),
33353345 );
33363346
3337 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3347 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
33383348 // This is a zero-bit field. If there are runtime bits after this field,
33393349 // map to the next LLVM field (which we know exists): otherwise, don't
33403350 // map the field, indicating it's at the end of the struct.
......@@ -3353,7 +3363,7 @@ pub const Object = struct {
33533363 }, @intCast(llvm_field_types.items.len));
33543364 try llvm_field_types.append(o.gpa, try o.lowerType(field_ty));
33553365
3356 offset += field_ty.abiSize(mod);
3366 offset += field_ty.abiSize(pt);
33573367 }
33583368 {
33593369 const prev_offset = offset;
......@@ -3386,7 +3396,7 @@ pub const Object = struct {
33863396 var offset: u64 = 0;
33873397 var big_align: InternPool.Alignment = .none;
33883398
3389 const struct_size = t.abiSize(mod);
3399 const struct_size = t.abiSize(pt);
33903400
33913401 for (
33923402 anon_struct_type.types.get(ip),
......@@ -3395,7 +3405,7 @@ pub const Object = struct {
33953405 ) |field_ty, field_val, field_index| {
33963406 if (field_val != .none) continue;
33973407
3398 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
3408 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
33993409 big_align = big_align.max(field_align);
34003410 const prev_offset = offset;
34013411 offset = field_align.forward(offset);
......@@ -3405,7 +3415,7 @@ pub const Object = struct {
34053415 o.gpa,
34063416 try o.builder.arrayType(padding_len, .i8),
34073417 );
3408 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) {
3418 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) {
34093419 // This is a zero-bit field. If there are runtime bits after this field,
34103420 // map to the next LLVM field (which we know exists): otherwise, don't
34113421 // map the field, indicating it's at the end of the struct.
......@@ -3423,7 +3433,7 @@ pub const Object = struct {
34233433 }, @intCast(llvm_field_types.items.len));
34243434 try llvm_field_types.append(o.gpa, try o.lowerType(Type.fromInterned(field_ty)));
34253435
3426 offset += Type.fromInterned(field_ty).abiSize(mod);
3436 offset += Type.fromInterned(field_ty).abiSize(pt);
34273437 }
34283438 {
34293439 const prev_offset = offset;
......@@ -3440,10 +3450,10 @@ pub const Object = struct {
34403450 if (o.type_map.get(t.toIntern())) |value| return value;
34413451
34423452 const union_obj = ip.loadUnionType(t.toIntern());
3443 const layout = mod.getUnionLayout(union_obj);
3453 const layout = pt.getUnionLayout(union_obj);
34443454
34453455 if (union_obj.flagsPtr(ip).layout == .@"packed") {
3446 const int_ty = try o.builder.intType(@intCast(t.bitSize(mod)));
3456 const int_ty = try o.builder.intType(@intCast(t.bitSize(pt)));
34473457 try o.type_map.put(o.gpa, t.toIntern(), int_ty);
34483458 return int_ty;
34493459 }
......@@ -3552,18 +3562,20 @@ pub const Object = struct {
35523562 /// being a zero bit type, but it should still be lowered as an i8 in such case.
35533563 /// There are other similar cases handled here as well.
35543564 fn lowerPtrElemTy(o: *Object, elem_ty: Type) Allocator.Error!Builder.Type {
3555 const mod = o.module;
3565 const pt = o.pt;
3566 const mod = pt.zcu;
35563567 const lower_elem_ty = switch (elem_ty.zigTypeTag(mod)) {
35573568 .Opaque => true,
35583569 .Fn => !mod.typeToFunc(elem_ty).?.is_generic,
3559 .Array => elem_ty.childType(mod).hasRuntimeBitsIgnoreComptime(mod),
3560 else => elem_ty.hasRuntimeBitsIgnoreComptime(mod),
3570 .Array => elem_ty.childType(mod).hasRuntimeBitsIgnoreComptime(pt),
3571 else => elem_ty.hasRuntimeBitsIgnoreComptime(pt),
35613572 };
35623573 return if (lower_elem_ty) try o.lowerType(elem_ty) else .i8;
35633574 }
35643575
35653576 fn lowerTypeFn(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
3566 const mod = o.module;
3577 const pt = o.pt;
3578 const mod = pt.zcu;
35673579 const ip = &mod.intern_pool;
35683580 const target = mod.getTarget();
35693581 const ret_ty = try lowerFnRetTy(o, fn_info);
......@@ -3571,14 +3583,14 @@ pub const Object = struct {
35713583 var llvm_params = std.ArrayListUnmanaged(Builder.Type){};
35723584 defer llvm_params.deinit(o.gpa);
35733585
3574 if (firstParamSRet(fn_info, mod, target)) {
3586 if (firstParamSRet(fn_info, pt, target)) {
35753587 try llvm_params.append(o.gpa, .ptr);
35763588 }
35773589
35783590 if (Type.fromInterned(fn_info.return_type).isError(mod) and
35793591 mod.comp.config.any_error_tracing)
35803592 {
3581 const ptr_ty = try mod.singleMutPtrType(try o.getStackTraceType());
3593 const ptr_ty = try pt.singleMutPtrType(try o.getStackTraceType());
35823594 try llvm_params.append(o.gpa, try o.lowerType(ptr_ty));
35833595 }
35843596
......@@ -3595,7 +3607,7 @@ pub const Object = struct {
35953607 .abi_sized_int => {
35963608 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
35973609 try llvm_params.append(o.gpa, try o.builder.intType(
3598 @intCast(param_ty.abiSize(mod) * 8),
3610 @intCast(param_ty.abiSize(pt) * 8),
35993611 ));
36003612 },
36013613 .slice => {
......@@ -3633,7 +3645,8 @@ pub const Object = struct {
36333645 }
36343646
36353647 fn lowerValueToInt(o: *Object, llvm_int_ty: Builder.Type, arg_val: InternPool.Index) Error!Builder.Constant {
3636 const mod = o.module;
3648 const pt = o.pt;
3649 const mod = pt.zcu;
36373650 const ip = &mod.intern_pool;
36383651 const target = mod.getTarget();
36393652
......@@ -3666,15 +3679,15 @@ pub const Object = struct {
36663679 var running_int = try o.builder.intConst(llvm_int_ty, 0);
36673680 var running_bits: u16 = 0;
36683681 for (struct_type.field_types.get(ip), 0..) |field_ty, field_index| {
3669 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
3682 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
36703683
36713684 const shift_rhs = try o.builder.intConst(llvm_int_ty, running_bits);
3672 const field_val = try o.lowerValueToInt(llvm_int_ty, (try val.fieldValue(mod, field_index)).toIntern());
3685 const field_val = try o.lowerValueToInt(llvm_int_ty, (try val.fieldValue(pt, field_index)).toIntern());
36733686 const shifted = try o.builder.binConst(.shl, field_val, shift_rhs);
36743687
36753688 running_int = try o.builder.binConst(.xor, running_int, shifted);
36763689
3677 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(mod));
3690 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(pt));
36783691 running_bits += ty_bit_size;
36793692 }
36803693 return running_int;
......@@ -3683,7 +3696,7 @@ pub const Object = struct {
36833696 else => unreachable,
36843697 },
36853698 .un => |un| {
3686 const layout = ty.unionGetLayout(mod);
3699 const layout = ty.unionGetLayout(pt);
36873700 if (layout.payload_size == 0) return o.lowerValue(un.tag);
36883701
36893702 const union_obj = mod.typeToUnion(ty).?;
......@@ -3701,7 +3714,7 @@ pub const Object = struct {
37013714 }
37023715 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
37033716 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
3704 if (!field_ty.hasRuntimeBits(mod)) return o.builder.intConst(llvm_int_ty, 0);
3717 if (!field_ty.hasRuntimeBits(pt)) return o.builder.intConst(llvm_int_ty, 0);
37053718 return o.lowerValueToInt(llvm_int_ty, un.val);
37063719 },
37073720 .simple_value => |simple_value| switch (simple_value) {
......@@ -3715,7 +3728,7 @@ pub const Object = struct {
37153728 .opt => {}, // pointer like optional expected
37163729 else => unreachable,
37173730 }
3718 const bits = ty.bitSize(mod);
3731 const bits = ty.bitSize(pt);
37193732 const bytes: usize = @intCast(std.mem.alignForward(u64, bits, 8) / 8);
37203733
37213734 var stack = std.heap.stackFallback(32, o.gpa);
......@@ -3729,12 +3742,7 @@ pub const Object = struct {
37293742 defer allocator.free(limbs);
37303743 @memset(limbs, 0);
37313744
3732 val.writeToPackedMemory(
3733 ty,
3734 mod,
3735 std.mem.sliceAsBytes(limbs)[0..bytes],
3736 0,
3737 ) catch unreachable;
3745 val.writeToPackedMemory(ty, pt, std.mem.sliceAsBytes(limbs)[0..bytes], 0) catch unreachable;
37383746
37393747 if (builtin.target.cpu.arch.endian() == .little) {
37403748 if (target.cpu.arch.endian() == .big)
......@@ -3752,7 +3760,8 @@ pub const Object = struct {
37523760 }
37533761
37543762 fn lowerValue(o: *Object, arg_val: InternPool.Index) Error!Builder.Constant {
3755 const mod = o.module;
3763 const pt = o.pt;
3764 const mod = pt.zcu;
37563765 const ip = &mod.intern_pool;
37573766 const target = mod.getTarget();
37583767
......@@ -3811,7 +3820,7 @@ pub const Object = struct {
38113820 },
38123821 .int => {
38133822 var bigint_space: Value.BigIntSpace = undefined;
3814 const bigint = val.toBigInt(&bigint_space, mod);
3823 const bigint = val.toBigInt(&bigint_space, pt);
38153824 return lowerBigInt(o, ty, bigint);
38163825 },
38173826 .err => |err| {
......@@ -3821,24 +3830,24 @@ pub const Object = struct {
38213830 },
38223831 .error_union => |error_union| {
38233832 const err_val = switch (error_union.val) {
3824 .err_name => |err_name| try mod.intern(.{ .err = .{
3833 .err_name => |err_name| try pt.intern(.{ .err = .{
38253834 .ty = ty.errorUnionSet(mod).toIntern(),
38263835 .name = err_name,
38273836 } }),
3828 .payload => (try mod.intValue(try mod.errorIntType(), 0)).toIntern(),
3837 .payload => (try pt.intValue(try pt.errorIntType(), 0)).toIntern(),
38293838 };
3830 const err_int_ty = try mod.errorIntType();
3839 const err_int_ty = try pt.errorIntType();
38313840 const payload_type = ty.errorUnionPayload(mod);
3832 if (!payload_type.hasRuntimeBitsIgnoreComptime(mod)) {
3841 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
38333842 // We use the error type directly as the type.
38343843 return o.lowerValue(err_val);
38353844 }
38363845
3837 const payload_align = payload_type.abiAlignment(mod);
3838 const error_align = err_int_ty.abiAlignment(mod);
3846 const payload_align = payload_type.abiAlignment(pt);
3847 const error_align = err_int_ty.abiAlignment(pt);
38393848 const llvm_error_value = try o.lowerValue(err_val);
38403849 const llvm_payload_value = try o.lowerValue(switch (error_union.val) {
3841 .err_name => try mod.intern(.{ .undef = payload_type.toIntern() }),
3850 .err_name => try pt.intern(.{ .undef = payload_type.toIntern() }),
38423851 .payload => |payload| payload,
38433852 });
38443853
......@@ -3869,16 +3878,16 @@ pub const Object = struct {
38693878 .enum_tag => |enum_tag| o.lowerValue(enum_tag.int),
38703879 .float => switch (ty.floatBits(target)) {
38713880 16 => if (backendSupportsF16(target))
3872 try o.builder.halfConst(val.toFloat(f16, mod))
3881 try o.builder.halfConst(val.toFloat(f16, pt))
38733882 else
3874 try o.builder.intConst(.i16, @as(i16, @bitCast(val.toFloat(f16, mod)))),
3875 32 => try o.builder.floatConst(val.toFloat(f32, mod)),
3876 64 => try o.builder.doubleConst(val.toFloat(f64, mod)),
3883 try o.builder.intConst(.i16, @as(i16, @bitCast(val.toFloat(f16, pt)))),
3884 32 => try o.builder.floatConst(val.toFloat(f32, pt)),
3885 64 => try o.builder.doubleConst(val.toFloat(f64, pt)),
38773886 80 => if (backendSupportsF80(target))
3878 try o.builder.x86_fp80Const(val.toFloat(f80, mod))
3887 try o.builder.x86_fp80Const(val.toFloat(f80, pt))
38793888 else
3880 try o.builder.intConst(.i80, @as(i80, @bitCast(val.toFloat(f80, mod)))),
3881 128 => try o.builder.fp128Const(val.toFloat(f128, mod)),
3889 try o.builder.intConst(.i80, @as(i80, @bitCast(val.toFloat(f80, pt)))),
3890 128 => try o.builder.fp128Const(val.toFloat(f128, pt)),
38823891 else => unreachable,
38833892 },
38843893 .ptr => try o.lowerPtr(arg_val, 0),
......@@ -3891,7 +3900,7 @@ pub const Object = struct {
38913900 const payload_ty = ty.optionalChild(mod);
38923901
38933902 const non_null_bit = try o.builder.intConst(.i8, @intFromBool(opt.val != .none));
3894 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3903 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
38953904 return non_null_bit;
38963905 }
38973906 const llvm_ty = try o.lowerType(ty);
......@@ -3909,7 +3918,7 @@ pub const Object = struct {
39093918 var fields: [3]Builder.Type = undefined;
39103919 var vals: [3]Builder.Constant = undefined;
39113920 vals[0] = try o.lowerValue(switch (opt.val) {
3912 .none => try mod.intern(.{ .undef = payload_ty.toIntern() }),
3921 .none => try pt.intern(.{ .undef = payload_ty.toIntern() }),
39133922 else => |payload| payload,
39143923 });
39153924 vals[1] = non_null_bit;
......@@ -4058,9 +4067,9 @@ pub const Object = struct {
40584067 0..,
40594068 ) |field_ty, field_val, field_index| {
40604069 if (field_val != .none) continue;
4061 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
4070 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
40624071
4063 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
4072 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
40644073 big_align = big_align.max(field_align);
40654074 const prev_offset = offset;
40664075 offset = field_align.forward(offset);
......@@ -4076,13 +4085,13 @@ pub const Object = struct {
40764085 }
40774086
40784087 vals[llvm_index] =
4079 try o.lowerValue((try val.fieldValue(mod, field_index)).toIntern());
4088 try o.lowerValue((try val.fieldValue(pt, field_index)).toIntern());
40804089 fields[llvm_index] = vals[llvm_index].typeOf(&o.builder);
40814090 if (fields[llvm_index] != struct_ty.structFields(&o.builder)[llvm_index])
40824091 need_unnamed = true;
40834092 llvm_index += 1;
40844093
4085 offset += Type.fromInterned(field_ty).abiSize(mod);
4094 offset += Type.fromInterned(field_ty).abiSize(pt);
40864095 }
40874096 {
40884097 const prev_offset = offset;
......@@ -4109,7 +4118,7 @@ pub const Object = struct {
41094118 if (struct_type.layout == .@"packed") {
41104119 comptime assert(Type.packed_struct_layout_version == 2);
41114120
4112 const bits = ty.bitSize(mod);
4121 const bits = ty.bitSize(pt);
41134122 const llvm_int_ty = try o.builder.intType(@intCast(bits));
41144123
41154124 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4138,7 +4147,7 @@ pub const Object = struct {
41384147 var field_it = struct_type.iterateRuntimeOrder(ip);
41394148 while (field_it.next()) |field_index| {
41404149 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
4141 const field_align = mod.structFieldAlignment(
4150 const field_align = pt.structFieldAlignment(
41424151 struct_type.fieldAlign(ip, field_index),
41434152 field_ty,
41444153 struct_type.layout,
......@@ -4158,20 +4167,20 @@ pub const Object = struct {
41584167 llvm_index += 1;
41594168 }
41604169
4161 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4170 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
41624171 // This is a zero-bit field - we only needed it for the alignment.
41634172 continue;
41644173 }
41654174
41664175 vals[llvm_index] = try o.lowerValue(
4167 (try val.fieldValue(mod, field_index)).toIntern(),
4176 (try val.fieldValue(pt, field_index)).toIntern(),
41684177 );
41694178 fields[llvm_index] = vals[llvm_index].typeOf(&o.builder);
41704179 if (fields[llvm_index] != struct_ty.structFields(&o.builder)[llvm_index])
41714180 need_unnamed = true;
41724181 llvm_index += 1;
41734182
4174 offset += field_ty.abiSize(mod);
4183 offset += field_ty.abiSize(pt);
41754184 }
41764185 {
41774186 const prev_offset = offset;
......@@ -4195,7 +4204,7 @@ pub const Object = struct {
41954204 },
41964205 .un => |un| {
41974206 const union_ty = try o.lowerType(ty);
4198 const layout = ty.unionGetLayout(mod);
4207 const layout = ty.unionGetLayout(pt);
41994208 if (layout.payload_size == 0) return o.lowerValue(un.tag);
42004209
42014210 const union_obj = mod.typeToUnion(ty).?;
......@@ -4206,8 +4215,8 @@ pub const Object = struct {
42064215 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
42074216 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
42084217 if (container_layout == .@"packed") {
4209 if (!field_ty.hasRuntimeBits(mod)) return o.builder.intConst(union_ty, 0);
4210 const bits = ty.bitSize(mod);
4218 if (!field_ty.hasRuntimeBits(pt)) return o.builder.intConst(union_ty, 0);
4219 const bits = ty.bitSize(pt);
42114220 const llvm_int_ty = try o.builder.intType(@intCast(bits));
42124221
42134222 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4219,7 +4228,7 @@ pub const Object = struct {
42194228 // must pointer cast to the expected type before accessing the union.
42204229 need_unnamed = layout.most_aligned_field != field_index;
42214230
4222 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4231 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42234232 const padding_len = layout.payload_size;
42244233 break :p try o.builder.undefConst(try o.builder.arrayType(padding_len, .i8));
42254234 }
......@@ -4228,7 +4237,7 @@ pub const Object = struct {
42284237 if (payload_ty != union_ty.structFields(&o.builder)[
42294238 @intFromBool(layout.tag_align.compare(.gte, layout.payload_align))
42304239 ]) need_unnamed = true;
4231 const field_size = field_ty.abiSize(mod);
4240 const field_size = field_ty.abiSize(pt);
42324241 if (field_size == layout.payload_size) break :p payload;
42334242 const padding_len = layout.payload_size - field_size;
42344243 const padding_ty = try o.builder.arrayType(padding_len, .i8);
......@@ -4239,7 +4248,7 @@ pub const Object = struct {
42394248 } else p: {
42404249 assert(layout.tag_size == 0);
42414250 if (container_layout == .@"packed") {
4242 const bits = ty.bitSize(mod);
4251 const bits = ty.bitSize(pt);
42434252 const llvm_int_ty = try o.builder.intType(@intCast(bits));
42444253
42454254 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4286,7 +4295,7 @@ pub const Object = struct {
42864295 ty: Type,
42874296 bigint: std.math.big.int.Const,
42884297 ) Allocator.Error!Builder.Constant {
4289 const mod = o.module;
4298 const mod = o.pt.zcu;
42904299 return o.builder.bigIntConst(try o.builder.intType(ty.intInfo(mod).bits), bigint);
42914300 }
42924301
......@@ -4295,7 +4304,8 @@ pub const Object = struct {
42954304 ptr_val: InternPool.Index,
42964305 prev_offset: u64,
42974306 ) Error!Builder.Constant {
4298 const zcu = o.module;
4307 const pt = o.pt;
4308 const zcu = pt.zcu;
42994309 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
43004310 const offset: u64 = prev_offset + ptr.byte_offset;
43014311 return switch (ptr.base_addr) {
......@@ -4320,7 +4330,7 @@ pub const Object = struct {
43204330 eu_ptr,
43214331 offset + @import("../codegen.zig").errUnionPayloadOffset(
43224332 Value.fromInterned(eu_ptr).typeOf(zcu).childType(zcu),
4323 zcu,
4333 pt,
43244334 ),
43254335 ),
43264336 .opt_payload => |opt_ptr| try o.lowerPtr(opt_ptr, offset),
......@@ -4336,7 +4346,7 @@ pub const Object = struct {
43364346 };
43374347 },
43384348 .Struct, .Union => switch (agg_ty.containerLayout(zcu)) {
4339 .auto => agg_ty.structFieldOffset(@intCast(field.index), zcu),
4349 .auto => agg_ty.structFieldOffset(@intCast(field.index), pt),
43404350 .@"extern", .@"packed" => unreachable,
43414351 },
43424352 else => unreachable,
......@@ -4353,7 +4363,8 @@ pub const Object = struct {
43534363 o: *Object,
43544364 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
43554365 ) Error!Builder.Constant {
4356 const mod = o.module;
4366 const pt = o.pt;
4367 const mod = pt.zcu;
43574368 const ip = &mod.intern_pool;
43584369 const decl_val = anon_decl.val;
43594370 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));
......@@ -4370,14 +4381,14 @@ pub const Object = struct {
43704381 const ptr_ty = Type.fromInterned(anon_decl.orig_ty);
43714382
43724383 const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
4373 if ((!is_fn_body and !decl_ty.hasRuntimeBits(mod)) or
4384 if ((!is_fn_body and !decl_ty.hasRuntimeBits(pt)) or
43744385 (is_fn_body and mod.typeToFunc(decl_ty).?.is_generic)) return o.lowerPtrToVoid(ptr_ty);
43754386
43764387 if (is_fn_body)
43774388 @panic("TODO");
43784389
43794390 const llvm_addr_space = toLlvmAddressSpace(ptr_ty.ptrAddressSpace(mod), target);
4380 const alignment = ptr_ty.ptrAlignment(mod);
4391 const alignment = ptr_ty.ptrAlignment(pt);
43814392 const llvm_global = (try o.resolveGlobalAnonDecl(decl_val, llvm_addr_space, alignment)).ptrConst(&o.builder).global;
43824393
43834394 const llvm_val = try o.builder.convConst(
......@@ -4389,7 +4400,8 @@ pub const Object = struct {
43894400 }
43904401
43914402 fn lowerDeclRefValue(o: *Object, decl_index: InternPool.DeclIndex) Allocator.Error!Builder.Constant {
4392 const mod = o.module;
4403 const pt = o.pt;
4404 const mod = pt.zcu;
43934405
43944406 // In the case of something like:
43954407 // fn foo() void {}
......@@ -4408,10 +4420,10 @@ pub const Object = struct {
44084420 }
44094421
44104422 const decl_ty = decl.typeOf(mod);
4411 const ptr_ty = try decl.declPtrType(mod);
4423 const ptr_ty = try decl.declPtrType(pt);
44124424
44134425 const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
4414 if ((!is_fn_body and !decl_ty.hasRuntimeBits(mod)) or
4426 if ((!is_fn_body and !decl_ty.hasRuntimeBits(pt)) or
44154427 (is_fn_body and mod.typeToFunc(decl_ty).?.is_generic))
44164428 {
44174429 return o.lowerPtrToVoid(ptr_ty);
......@@ -4431,7 +4443,7 @@ pub const Object = struct {
44314443 }
44324444
44334445 fn lowerPtrToVoid(o: *Object, ptr_ty: Type) Allocator.Error!Builder.Constant {
4434 const mod = o.module;
4446 const mod = o.pt.zcu;
44354447 // Even though we are pointing at something which has zero bits (e.g. `void`),
44364448 // Pointers are defined to have bits. So we must return something here.
44374449 // The value cannot be undefined, because we use the `nonnull` annotation
......@@ -4459,20 +4471,21 @@ pub const Object = struct {
44594471 /// RMW exchange of floating-point values is bitcasted to same-sized integer
44604472 /// types to work around a LLVM deficiency when targeting ARM/AArch64.
44614473 fn getAtomicAbiType(o: *Object, ty: Type, is_rmw_xchg: bool) Allocator.Error!Builder.Type {
4462 const mod = o.module;
4474 const pt = o.pt;
4475 const mod = pt.zcu;
44634476 const int_ty = switch (ty.zigTypeTag(mod)) {
44644477 .Int => ty,
44654478 .Enum => ty.intTagType(mod),
44664479 .Float => {
44674480 if (!is_rmw_xchg) return .none;
4468 return o.builder.intType(@intCast(ty.abiSize(mod) * 8));
4481 return o.builder.intType(@intCast(ty.abiSize(pt) * 8));
44694482 },
44704483 .Bool => return .i8,
44714484 else => return .none,
44724485 };
44734486 const bit_count = int_ty.intInfo(mod).bits;
44744487 if (!std.math.isPowerOfTwo(bit_count) or (bit_count % 8) != 0) {
4475 return o.builder.intType(@intCast(int_ty.abiSize(mod) * 8));
4488 return o.builder.intType(@intCast(int_ty.abiSize(pt) * 8));
44764489 } else {
44774490 return .none;
44784491 }
......@@ -4486,7 +4499,8 @@ pub const Object = struct {
44864499 fn_info: InternPool.Key.FuncType,
44874500 llvm_arg_i: u32,
44884501 ) Allocator.Error!void {
4489 const mod = o.module;
4502 const pt = o.pt;
4503 const mod = pt.zcu;
44904504 if (param_ty.isPtrAtRuntime(mod)) {
44914505 const ptr_info = param_ty.ptrInfo(mod);
44924506 if (math.cast(u5, param_index)) |i| {
......@@ -4507,7 +4521,7 @@ pub const Object = struct {
45074521 const elem_align = if (ptr_info.flags.alignment != .none)
45084522 ptr_info.flags.alignment
45094523 else
4510 Type.fromInterned(ptr_info.child).abiAlignment(mod).max(.@"1");
4524 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1");
45114525 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align.toLlvm() }, &o.builder);
45124526 } else if (ccAbiPromoteInt(fn_info.cc, mod, param_ty)) |s| switch (s) {
45134527 .signed => try attributes.addParamAttr(llvm_arg_i, .signext, &o.builder),
......@@ -4540,7 +4554,7 @@ pub const Object = struct {
45404554 const name = try o.builder.strtabString(lt_errors_fn_name);
45414555 if (o.builder.getGlobal(name)) |llvm_fn| return llvm_fn.ptrConst(&o.builder).kind.function;
45424556
4543 const zcu = o.module;
4557 const zcu = o.pt.zcu;
45444558 const target = zcu.root_mod.resolved_target.result;
45454559 const function_index = try o.builder.addFunction(
45464560 try o.builder.fnType(.i1, &.{try o.errorIntType()}, .normal),
......@@ -4559,7 +4573,8 @@ pub const Object = struct {
45594573 }
45604574
45614575 fn getEnumTagNameFunction(o: *Object, enum_ty: Type) !Builder.Function.Index {
4562 const zcu = o.module;
4576 const pt = o.pt;
4577 const zcu = pt.zcu;
45634578 const ip = &zcu.intern_pool;
45644579 const enum_type = ip.loadEnumType(enum_ty.toIntern());
45654580
......@@ -4618,7 +4633,7 @@ pub const Object = struct {
46184633
46194634 const return_block = try wip.block(1, "Name");
46204635 const this_tag_int_value = try o.lowerValue(
4621 (try zcu.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
4636 (try pt.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
46224637 );
46234638 try wip_switch.addCase(this_tag_int_value, return_block, &wip);
46244639
......@@ -4636,13 +4651,13 @@ pub const Object = struct {
46364651
46374652pub const DeclGen = struct {
46384653 object: *Object,
4639 decl: *Module.Decl,
4654 decl: *Zcu.Decl,
46404655 decl_index: InternPool.DeclIndex,
4641 err_msg: ?*Module.ErrorMsg,
4656 err_msg: ?*Zcu.ErrorMsg,
46424657
46434658 fn ownerModule(dg: DeclGen) *Package.Module {
46444659 const o = dg.object;
4645 const zcu = o.module;
4660 const zcu = o.pt.zcu;
46464661 const namespace = zcu.namespacePtr(dg.decl.src_namespace);
46474662 const file_scope = namespace.fileScope(zcu);
46484663 return file_scope.mod;
......@@ -4653,15 +4668,15 @@ pub const DeclGen = struct {
46534668 assert(dg.err_msg == null);
46544669 const o = dg.object;
46554670 const gpa = o.gpa;
4656 const mod = o.module;
4657 const src_loc = dg.decl.navSrcLoc(mod);
4658 dg.err_msg = try Module.ErrorMsg.create(gpa, src_loc, "TODO (LLVM): " ++ format, args);
4671 const src_loc = dg.decl.navSrcLoc(o.pt.zcu);
4672 dg.err_msg = try Zcu.ErrorMsg.create(gpa, src_loc, "TODO (LLVM): " ++ format, args);
46594673 return error.CodegenFail;
46604674 }
46614675
46624676 fn genDecl(dg: *DeclGen) !void {
46634677 const o = dg.object;
4664 const zcu = o.module;
4678 const pt = o.pt;
4679 const zcu = pt.zcu;
46654680 const ip = &zcu.intern_pool;
46664681 const decl = dg.decl;
46674682 const decl_index = dg.decl_index;
......@@ -4672,7 +4687,7 @@ pub const DeclGen = struct {
46724687 } else {
46734688 const variable_index = try o.resolveGlobalDecl(decl_index);
46744689 variable_index.setAlignment(
4675 decl.getAlignment(zcu).toLlvm(),
4690 decl.getAlignment(pt).toLlvm(),
46764691 &o.builder,
46774692 );
46784693 if (decl.@"linksection".toSlice(ip)) |section|
......@@ -4833,23 +4848,21 @@ pub const FuncGen = struct {
48334848 const gop = try self.func_inst_table.getOrPut(gpa, inst);
48344849 if (gop.found_existing) return gop.value_ptr.*;
48354850
4836 const o = self.dg.object;
4837 const mod = o.module;
4838 const llvm_val = try self.resolveValue((try self.air.value(inst, mod)).?);
4851 const llvm_val = try self.resolveValue((try self.air.value(inst, self.dg.object.pt)).?);
48394852 gop.value_ptr.* = llvm_val.toValue();
48404853 return llvm_val.toValue();
48414854 }
48424855
48434856 fn resolveValue(self: *FuncGen, val: Value) Error!Builder.Constant {
48444857 const o = self.dg.object;
4845 const mod = o.module;
4846 const ty = val.typeOf(mod);
4858 const pt = o.pt;
4859 const ty = val.typeOf(pt.zcu);
48474860 const llvm_val = try o.lowerValue(val.toIntern());
4848 if (!isByRef(ty, mod)) return llvm_val;
4861 if (!isByRef(ty, pt)) return llvm_val;
48494862
48504863 // We have an LLVM value but we need to create a global constant and
48514864 // set the value as its initializer, and then return a pointer to the global.
4852 const target = mod.getTarget();
4865 const target = pt.zcu.getTarget();
48534866 const variable_index = try o.builder.addVariable(
48544867 .empty,
48554868 llvm_val.typeOf(&o.builder),
......@@ -4859,7 +4872,7 @@ pub const FuncGen = struct {
48594872 variable_index.setLinkage(.private, &o.builder);
48604873 variable_index.setMutability(.constant, &o.builder);
48614874 variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
4862 variable_index.setAlignment(ty.abiAlignment(mod).toLlvm(), &o.builder);
4875 variable_index.setAlignment(ty.abiAlignment(pt).toLlvm(), &o.builder);
48634876 return o.builder.convConst(
48644877 variable_index.toConst(&o.builder),
48654878 try o.builder.ptrType(toLlvmAddressSpace(.generic, target)),
......@@ -4868,10 +4881,10 @@ pub const FuncGen = struct {
48684881
48694882 fn resolveNullOptUsize(self: *FuncGen) Error!Builder.Constant {
48704883 const o = self.dg.object;
4871 const mod = o.module;
4884 const pt = o.pt;
48724885 if (o.null_opt_usize == .no_init) {
4873 o.null_opt_usize = try self.resolveValue(Value.fromInterned(try mod.intern(.{ .opt = .{
4874 .ty = try mod.intern(.{ .opt_type = .usize_type }),
4886 o.null_opt_usize = try self.resolveValue(Value.fromInterned(try pt.intern(.{ .opt = .{
4887 .ty = try pt.intern(.{ .opt_type = .usize_type }),
48754888 .val = .none,
48764889 } })));
48774890 }
......@@ -4880,7 +4893,7 @@ pub const FuncGen = struct {
48804893
48814894 fn genBody(self: *FuncGen, body: []const Air.Inst.Index) Error!void {
48824895 const o = self.dg.object;
4883 const mod = o.module;
4896 const mod = o.pt.zcu;
48844897 const ip = &mod.intern_pool;
48854898 const air_tags = self.air.instructions.items(.tag);
48864899 for (body, 0..) |inst, i| {
......@@ -5145,7 +5158,8 @@ pub const FuncGen = struct {
51455158
51465159 if (maybe_inline_func) |inline_func| {
51475160 const o = self.dg.object;
5148 const zcu = o.module;
5161 const pt = o.pt;
5162 const zcu = pt.zcu;
51495163
51505164 const func = zcu.funcInfo(inline_func);
51515165 const decl_index = func.owner_decl;
......@@ -5161,7 +5175,7 @@ pub const FuncGen = struct {
51615175
51625176 const fqn = try decl.fullyQualifiedName(zcu);
51635177
5164 const fn_ty = try zcu.funcType(.{
5178 const fn_ty = try pt.funcType(.{
51655179 .param_types = &.{},
51665180 .return_type = .void_type,
51675181 });
......@@ -5228,7 +5242,8 @@ pub const FuncGen = struct {
52285242 const extra = self.air.extraData(Air.Call, pl_op.payload);
52295243 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
52305244 const o = self.dg.object;
5231 const mod = o.module;
5245 const pt = o.pt;
5246 const mod = pt.zcu;
52325247 const ip = &mod.intern_pool;
52335248 const callee_ty = self.typeOf(pl_op.operand);
52345249 const zig_fn_ty = switch (callee_ty.zigTypeTag(mod)) {
......@@ -5240,7 +5255,7 @@ pub const FuncGen = struct {
52405255 const return_type = Type.fromInterned(fn_info.return_type);
52415256 const llvm_fn = try self.resolveInst(pl_op.operand);
52425257 const target = mod.getTarget();
5243 const sret = firstParamSRet(fn_info, mod, target);
5258 const sret = firstParamSRet(fn_info, pt, target);
52445259
52455260 var llvm_args = std.ArrayList(Builder.Value).init(self.gpa);
52465261 defer llvm_args.deinit();
......@@ -5258,14 +5273,13 @@ pub const FuncGen = struct {
52585273 const llvm_ret_ty = try o.lowerType(return_type);
52595274 try attributes.addParamAttr(0, .{ .sret = llvm_ret_ty }, &o.builder);
52605275
5261 const alignment = return_type.abiAlignment(mod).toLlvm();
5276 const alignment = return_type.abiAlignment(pt).toLlvm();
52625277 const ret_ptr = try self.buildAllocaWorkaround(return_type, alignment);
52635278 try llvm_args.append(ret_ptr);
52645279 break :blk ret_ptr;
52655280 };
52665281
5267 const err_return_tracing = return_type.isError(mod) and
5268 o.module.comp.config.any_error_tracing;
5282 const err_return_tracing = return_type.isError(mod) and mod.comp.config.any_error_tracing;
52695283 if (err_return_tracing) {
52705284 assert(self.err_ret_trace != .none);
52715285 try llvm_args.append(self.err_ret_trace);
......@@ -5279,8 +5293,8 @@ pub const FuncGen = struct {
52795293 const param_ty = self.typeOf(arg);
52805294 const llvm_arg = try self.resolveInst(arg);
52815295 const llvm_param_ty = try o.lowerType(param_ty);
5282 if (isByRef(param_ty, mod)) {
5283 const alignment = param_ty.abiAlignment(mod).toLlvm();
5296 if (isByRef(param_ty, pt)) {
5297 const alignment = param_ty.abiAlignment(pt).toLlvm();
52845298 const loaded = try self.wip.load(.normal, llvm_param_ty, llvm_arg, alignment, "");
52855299 try llvm_args.append(loaded);
52865300 } else {
......@@ -5291,10 +5305,10 @@ pub const FuncGen = struct {
52915305 const arg = args[it.zig_index - 1];
52925306 const param_ty = self.typeOf(arg);
52935307 const llvm_arg = try self.resolveInst(arg);
5294 if (isByRef(param_ty, mod)) {
5308 if (isByRef(param_ty, pt)) {
52955309 try llvm_args.append(llvm_arg);
52965310 } else {
5297 const alignment = param_ty.abiAlignment(mod).toLlvm();
5311 const alignment = param_ty.abiAlignment(pt).toLlvm();
52985312 const param_llvm_ty = llvm_arg.typeOfWip(&self.wip);
52995313 const arg_ptr = try self.buildAlloca(param_llvm_ty, alignment);
53005314 _ = try self.wip.store(.normal, llvm_arg, arg_ptr, alignment);
......@@ -5306,10 +5320,10 @@ pub const FuncGen = struct {
53065320 const param_ty = self.typeOf(arg);
53075321 const llvm_arg = try self.resolveInst(arg);
53085322
5309 const alignment = param_ty.abiAlignment(mod).toLlvm();
5323 const alignment = param_ty.abiAlignment(pt).toLlvm();
53105324 const param_llvm_ty = try o.lowerType(param_ty);
53115325 const arg_ptr = try self.buildAllocaWorkaround(param_ty, alignment);
5312 if (isByRef(param_ty, mod)) {
5326 if (isByRef(param_ty, pt)) {
53135327 const loaded = try self.wip.load(.normal, param_llvm_ty, llvm_arg, alignment, "");
53145328 _ = try self.wip.store(.normal, loaded, arg_ptr, alignment);
53155329 } else {
......@@ -5321,16 +5335,16 @@ pub const FuncGen = struct {
53215335 const arg = args[it.zig_index - 1];
53225336 const param_ty = self.typeOf(arg);
53235337 const llvm_arg = try self.resolveInst(arg);
5324 const int_llvm_ty = try o.builder.intType(@intCast(param_ty.abiSize(mod) * 8));
5338 const int_llvm_ty = try o.builder.intType(@intCast(param_ty.abiSize(pt) * 8));
53255339
5326 if (isByRef(param_ty, mod)) {
5327 const alignment = param_ty.abiAlignment(mod).toLlvm();
5340 if (isByRef(param_ty, pt)) {
5341 const alignment = param_ty.abiAlignment(pt).toLlvm();
53285342 const loaded = try self.wip.load(.normal, int_llvm_ty, llvm_arg, alignment, "");
53295343 try llvm_args.append(loaded);
53305344 } else {
53315345 // LLVM does not allow bitcasting structs so we must allocate
53325346 // a local, store as one type, and then load as another type.
5333 const alignment = param_ty.abiAlignment(mod).toLlvm();
5347 const alignment = param_ty.abiAlignment(pt).toLlvm();
53345348 const int_ptr = try self.buildAllocaWorkaround(param_ty, alignment);
53355349 _ = try self.wip.store(.normal, llvm_arg, int_ptr, alignment);
53365350 const loaded = try self.wip.load(.normal, int_llvm_ty, int_ptr, alignment, "");
......@@ -5349,9 +5363,9 @@ pub const FuncGen = struct {
53495363 const param_ty = self.typeOf(arg);
53505364 const llvm_types = it.types_buffer[0..it.types_len];
53515365 const llvm_arg = try self.resolveInst(arg);
5352 const is_by_ref = isByRef(param_ty, mod);
5366 const is_by_ref = isByRef(param_ty, pt);
53535367 const arg_ptr = if (is_by_ref) llvm_arg else ptr: {
5354 const alignment = param_ty.abiAlignment(mod).toLlvm();
5368 const alignment = param_ty.abiAlignment(pt).toLlvm();
53555369 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
53565370 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
53575371 break :ptr ptr;
......@@ -5377,8 +5391,8 @@ pub const FuncGen = struct {
53775391 const arg = args[it.zig_index - 1];
53785392 const arg_ty = self.typeOf(arg);
53795393 var llvm_arg = try self.resolveInst(arg);
5380 const alignment = arg_ty.abiAlignment(mod).toLlvm();
5381 if (!isByRef(arg_ty, mod)) {
5394 const alignment = arg_ty.abiAlignment(pt).toLlvm();
5395 if (!isByRef(arg_ty, pt)) {
53825396 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
53835397 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
53845398 llvm_arg = ptr;
......@@ -5395,8 +5409,8 @@ pub const FuncGen = struct {
53955409 const arg = args[it.zig_index - 1];
53965410 const arg_ty = self.typeOf(arg);
53975411 var llvm_arg = try self.resolveInst(arg);
5398 const alignment = arg_ty.abiAlignment(mod).toLlvm();
5399 if (!isByRef(arg_ty, mod)) {
5412 const alignment = arg_ty.abiAlignment(pt).toLlvm();
5413 if (!isByRef(arg_ty, pt)) {
54005414 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
54015415 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
54025416 llvm_arg = ptr;
......@@ -5418,7 +5432,7 @@ pub const FuncGen = struct {
54185432 .byval => {
54195433 const param_index = it.zig_index - 1;
54205434 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
5421 if (!isByRef(param_ty, mod)) {
5435 if (!isByRef(param_ty, pt)) {
54225436 try o.addByValParamAttrs(&attributes, param_ty, param_index, fn_info, it.llvm_index - 1);
54235437 }
54245438 },
......@@ -5426,7 +5440,7 @@ pub const FuncGen = struct {
54265440 const param_index = it.zig_index - 1;
54275441 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
54285442 const param_llvm_ty = try o.lowerType(param_ty);
5429 const alignment = param_ty.abiAlignment(mod).toLlvm();
5443 const alignment = param_ty.abiAlignment(pt).toLlvm();
54305444 try o.addByRefParamAttrs(&attributes, it.llvm_index - 1, alignment, it.byval_attr, param_llvm_ty);
54315445 },
54325446 .byref_mut => try attributes.addParamAttr(it.llvm_index - 1, .noundef, &o.builder),
......@@ -5460,7 +5474,7 @@ pub const FuncGen = struct {
54605474 const elem_align = (if (ptr_info.flags.alignment != .none)
54615475 @as(InternPool.Alignment, ptr_info.flags.alignment)
54625476 else
5463 Type.fromInterned(ptr_info.child).abiAlignment(mod).max(.@"1")).toLlvm();
5477 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1")).toLlvm();
54645478 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align }, &o.builder);
54655479 },
54665480 };
......@@ -5485,17 +5499,17 @@ pub const FuncGen = struct {
54855499 return .none;
54865500 }
54875501
5488 if (self.liveness.isUnused(inst) or !return_type.hasRuntimeBitsIgnoreComptime(mod)) {
5502 if (self.liveness.isUnused(inst) or !return_type.hasRuntimeBitsIgnoreComptime(pt)) {
54895503 return .none;
54905504 }
54915505
54925506 const llvm_ret_ty = try o.lowerType(return_type);
54935507 if (ret_ptr) |rp| {
5494 if (isByRef(return_type, mod)) {
5508 if (isByRef(return_type, pt)) {
54955509 return rp;
54965510 } else {
54975511 // our by-ref status disagrees with sret so we must load.
5498 const return_alignment = return_type.abiAlignment(mod).toLlvm();
5512 const return_alignment = return_type.abiAlignment(pt).toLlvm();
54995513 return self.wip.load(.normal, llvm_ret_ty, rp, return_alignment, "");
55005514 }
55015515 }
......@@ -5506,19 +5520,19 @@ pub const FuncGen = struct {
55065520 // In this case the function return type is honoring the calling convention by having
55075521 // a different LLVM type than the usual one. We solve this here at the callsite
55085522 // by using our canonical type, then loading it if necessary.
5509 const alignment = return_type.abiAlignment(mod).toLlvm();
5523 const alignment = return_type.abiAlignment(pt).toLlvm();
55105524 const rp = try self.buildAlloca(abi_ret_ty, alignment);
55115525 _ = try self.wip.store(.normal, call, rp, alignment);
5512 return if (isByRef(return_type, mod))
5526 return if (isByRef(return_type, pt))
55135527 rp
55145528 else
55155529 try self.wip.load(.normal, llvm_ret_ty, rp, alignment, "");
55165530 }
55175531
5518 if (isByRef(return_type, mod)) {
5532 if (isByRef(return_type, pt)) {
55195533 // our by-ref status disagrees with sret so we must allocate, store,
55205534 // and return the allocation pointer.
5521 const alignment = return_type.abiAlignment(mod).toLlvm();
5535 const alignment = return_type.abiAlignment(pt).toLlvm();
55225536 const rp = try self.buildAlloca(llvm_ret_ty, alignment);
55235537 _ = try self.wip.store(.normal, call, rp, alignment);
55245538 return rp;
......@@ -5527,9 +5541,9 @@ pub const FuncGen = struct {
55275541 }
55285542 }
55295543
5530 fn buildSimplePanic(fg: *FuncGen, panic_id: Module.PanicId) !void {
5544 fn buildSimplePanic(fg: *FuncGen, panic_id: Zcu.PanicId) !void {
55315545 const o = fg.dg.object;
5532 const mod = o.module;
5546 const mod = o.pt.zcu;
55335547 const msg_decl_index = mod.panic_messages[@intFromEnum(panic_id)].unwrap().?;
55345548 const msg_decl = mod.declPtr(msg_decl_index);
55355549 const msg_len = msg_decl.typeOf(mod).childType(mod).arrayLen(mod);
......@@ -5567,15 +5581,16 @@ pub const FuncGen = struct {
55675581
55685582 fn airRet(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
55695583 const o = self.dg.object;
5570 const mod = o.module;
5584 const pt = o.pt;
5585 const mod = pt.zcu;
55715586 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
55725587 const ret_ty = self.typeOf(un_op);
55735588
55745589 if (self.ret_ptr != .none) {
5575 const ptr_ty = try mod.singleMutPtrType(ret_ty);
5590 const ptr_ty = try pt.singleMutPtrType(ret_ty);
55765591
55775592 const operand = try self.resolveInst(un_op);
5578 const val_is_undef = if (try self.air.value(un_op, mod)) |val| val.isUndefDeep(mod) else false;
5593 const val_is_undef = if (try self.air.value(un_op, pt)) |val| val.isUndefDeep(mod) else false;
55795594 if (val_is_undef and safety) undef: {
55805595 const ptr_info = ptr_ty.ptrInfo(mod);
55815596 const needs_bitmask = (ptr_info.packed_offset.host_size != 0);
......@@ -5585,10 +5600,10 @@ pub const FuncGen = struct {
55855600 // https://github.com/ziglang/zig/issues/15337
55865601 break :undef;
55875602 }
5588 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(mod));
5603 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(pt));
55895604 _ = try self.wip.callMemSet(
55905605 self.ret_ptr,
5591 ptr_ty.ptrAlignment(mod).toLlvm(),
5606 ptr_ty.ptrAlignment(pt).toLlvm(),
55925607 try o.builder.intValue(.i8, 0xaa),
55935608 len,
55945609 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal,
......@@ -5615,7 +5630,7 @@ pub const FuncGen = struct {
56155630 return .none;
56165631 }
56175632 const fn_info = mod.typeToFunc(self.dg.decl.typeOf(mod)).?;
5618 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5633 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56195634 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
56205635 // Functions with an empty error set are emitted with an error code
56215636 // return type and return zero so they can be function pointers coerced
......@@ -5629,13 +5644,13 @@ pub const FuncGen = struct {
56295644
56305645 const abi_ret_ty = try lowerFnRetTy(o, fn_info);
56315646 const operand = try self.resolveInst(un_op);
5632 const val_is_undef = if (try self.air.value(un_op, mod)) |val| val.isUndefDeep(mod) else false;
5633 const alignment = ret_ty.abiAlignment(mod).toLlvm();
5647 const val_is_undef = if (try self.air.value(un_op, pt)) |val| val.isUndefDeep(mod) else false;
5648 const alignment = ret_ty.abiAlignment(pt).toLlvm();
56345649
56355650 if (val_is_undef and safety) {
56365651 const llvm_ret_ty = operand.typeOfWip(&self.wip);
56375652 const rp = try self.buildAlloca(llvm_ret_ty, alignment);
5638 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(mod));
5653 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(pt));
56395654 _ = try self.wip.callMemSet(
56405655 rp,
56415656 alignment,
......@@ -5651,7 +5666,7 @@ pub const FuncGen = struct {
56515666 return .none;
56525667 }
56535668
5654 if (isByRef(ret_ty, mod)) {
5669 if (isByRef(ret_ty, pt)) {
56555670 // operand is a pointer however self.ret_ptr is null so that means
56565671 // we need to return a value.
56575672 _ = try self.wip.ret(try self.wip.load(.normal, abi_ret_ty, operand, alignment, ""));
......@@ -5672,12 +5687,13 @@ pub const FuncGen = struct {
56725687
56735688 fn airRetLoad(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
56745689 const o = self.dg.object;
5675 const mod = o.module;
5690 const pt = o.pt;
5691 const mod = pt.zcu;
56765692 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
56775693 const ptr_ty = self.typeOf(un_op);
56785694 const ret_ty = ptr_ty.childType(mod);
56795695 const fn_info = mod.typeToFunc(self.dg.decl.typeOf(mod)).?;
5680 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5696 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56815697 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
56825698 // Functions with an empty error set are emitted with an error code
56835699 // return type and return zero so they can be function pointers coerced
......@@ -5694,7 +5710,7 @@ pub const FuncGen = struct {
56945710 }
56955711 const ptr = try self.resolveInst(un_op);
56965712 const abi_ret_ty = try lowerFnRetTy(o, fn_info);
5697 const alignment = ret_ty.abiAlignment(mod).toLlvm();
5713 const alignment = ret_ty.abiAlignment(pt).toLlvm();
56985714 _ = try self.wip.ret(try self.wip.load(.normal, abi_ret_ty, ptr, alignment, ""));
56995715 return .none;
57005716 }
......@@ -5711,17 +5727,17 @@ pub const FuncGen = struct {
57115727
57125728 fn airCVaCopy(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
57135729 const o = self.dg.object;
5730 const pt = o.pt;
57145731 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57155732 const src_list = try self.resolveInst(ty_op.operand);
57165733 const va_list_ty = ty_op.ty.toType();
57175734 const llvm_va_list_ty = try o.lowerType(va_list_ty);
5718 const mod = o.module;
57195735
5720 const result_alignment = va_list_ty.abiAlignment(mod).toLlvm();
5736 const result_alignment = va_list_ty.abiAlignment(pt).toLlvm();
57215737 const dest_list = try self.buildAllocaWorkaround(va_list_ty, result_alignment);
57225738
57235739 _ = try self.wip.callIntrinsic(.normal, .none, .va_copy, &.{}, &.{ dest_list, src_list }, "");
5724 return if (isByRef(va_list_ty, mod))
5740 return if (isByRef(va_list_ty, pt))
57255741 dest_list
57265742 else
57275743 try self.wip.load(.normal, llvm_va_list_ty, dest_list, result_alignment, "");
......@@ -5737,15 +5753,15 @@ pub const FuncGen = struct {
57375753
57385754 fn airCVaStart(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
57395755 const o = self.dg.object;
5740 const mod = o.module;
5756 const pt = o.pt;
57415757 const va_list_ty = self.typeOfIndex(inst);
57425758 const llvm_va_list_ty = try o.lowerType(va_list_ty);
57435759
5744 const result_alignment = va_list_ty.abiAlignment(mod).toLlvm();
5760 const result_alignment = va_list_ty.abiAlignment(pt).toLlvm();
57455761 const dest_list = try self.buildAllocaWorkaround(va_list_ty, result_alignment);
57465762
57475763 _ = try self.wip.callIntrinsic(.normal, .none, .va_start, &.{}, &.{dest_list}, "");
5748 return if (isByRef(va_list_ty, mod))
5764 return if (isByRef(va_list_ty, pt))
57495765 dest_list
57505766 else
57515767 try self.wip.load(.normal, llvm_va_list_ty, dest_list, result_alignment, "");
......@@ -5802,21 +5818,22 @@ pub const FuncGen = struct {
58025818 rhs: Builder.Value,
58035819 ) Allocator.Error!Builder.Value {
58045820 const o = self.dg.object;
5805 const mod = o.module;
5821 const pt = o.pt;
5822 const mod = pt.zcu;
58065823 const scalar_ty = operand_ty.scalarType(mod);
58075824 const int_ty = switch (scalar_ty.zigTypeTag(mod)) {
58085825 .Enum => scalar_ty.intTagType(mod),
58095826 .Int, .Bool, .Pointer, .ErrorSet => scalar_ty,
58105827 .Optional => blk: {
58115828 const payload_ty = operand_ty.optionalChild(mod);
5812 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod) or
5829 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt) or
58135830 operand_ty.optionalReprIsPayload(mod))
58145831 {
58155832 break :blk operand_ty;
58165833 }
58175834 // We need to emit instructions to check for equality/inequality
58185835 // of optionals that are not pointers.
5819 const is_by_ref = isByRef(scalar_ty, mod);
5836 const is_by_ref = isByRef(scalar_ty, pt);
58205837 const opt_llvm_ty = try o.lowerType(scalar_ty);
58215838 const lhs_non_null = try self.optCmpNull(.ne, opt_llvm_ty, lhs, is_by_ref);
58225839 const rhs_non_null = try self.optCmpNull(.ne, opt_llvm_ty, rhs, is_by_ref);
......@@ -5908,7 +5925,8 @@ pub const FuncGen = struct {
59085925 body: []const Air.Inst.Index,
59095926 ) !Builder.Value {
59105927 const o = self.dg.object;
5911 const mod = o.module;
5928 const pt = o.pt;
5929 const mod = pt.zcu;
59125930 const inst_ty = self.typeOfIndex(inst);
59135931
59145932 if (inst_ty.isNoReturn(mod)) {
......@@ -5916,7 +5934,7 @@ pub const FuncGen = struct {
59165934 return .none;
59175935 }
59185936
5919 const have_block_result = inst_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod);
5937 const have_block_result = inst_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt);
59205938
59215939 var breaks: BreakList = if (have_block_result) .{ .list = .{} } else .{ .len = 0 };
59225940 defer if (have_block_result) breaks.list.deinit(self.gpa);
......@@ -5940,7 +5958,7 @@ pub const FuncGen = struct {
59405958 // a pointer to it. LLVM IR allows the call instruction to use function bodies instead
59415959 // of function pointers, however the phi makes it a runtime value and therefore
59425960 // the LLVM type has to be wrapped in a pointer.
5943 if (inst_ty.zigTypeTag(mod) == .Fn or isByRef(inst_ty, mod)) {
5961 if (inst_ty.zigTypeTag(mod) == .Fn or isByRef(inst_ty, pt)) {
59445962 break :ty .ptr;
59455963 }
59465964 break :ty raw_llvm_ty;
......@@ -5958,13 +5976,13 @@ pub const FuncGen = struct {
59585976
59595977 fn airBr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
59605978 const o = self.dg.object;
5979 const pt = o.pt;
59615980 const branch = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
59625981 const block = self.blocks.get(branch.block_inst).?;
59635982
59645983 // Add the values to the lists only if the break provides a value.
59655984 const operand_ty = self.typeOf(branch.operand);
5966 const mod = o.module;
5967 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5985 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
59685986 const val = try self.resolveInst(branch.operand);
59695987
59705988 // For the phi node, we need the basic blocks and the values of the
......@@ -5998,7 +6016,7 @@ pub const FuncGen = struct {
59986016
59996017 fn airTry(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
60006018 const o = self.dg.object;
6001 const mod = o.module;
6019 const pt = o.pt;
60026020 const inst = body_tail[0];
60036021 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
60046022 const err_union = try self.resolveInst(pl_op.operand);
......@@ -6006,14 +6024,14 @@ pub const FuncGen = struct {
60066024 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
60076025 const err_union_ty = self.typeOf(pl_op.operand);
60086026 const payload_ty = self.typeOfIndex(inst);
6009 const can_elide_load = if (isByRef(payload_ty, mod)) self.canElideLoad(body_tail) else false;
6027 const can_elide_load = if (isByRef(payload_ty, pt)) self.canElideLoad(body_tail) else false;
60106028 const is_unused = self.liveness.isUnused(inst);
60116029 return lowerTry(self, err_union, body, err_union_ty, false, can_elide_load, is_unused);
60126030 }
60136031
60146032 fn airTryPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
60156033 const o = self.dg.object;
6016 const mod = o.module;
6034 const mod = o.pt.zcu;
60176035 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
60186036 const extra = self.air.extraData(Air.TryPtr, ty_pl.payload);
60196037 const err_union_ptr = try self.resolveInst(extra.data.ptr);
......@@ -6033,9 +6051,10 @@ pub const FuncGen = struct {
60336051 is_unused: bool,
60346052 ) !Builder.Value {
60356053 const o = fg.dg.object;
6036 const mod = o.module;
6054 const pt = o.pt;
6055 const mod = pt.zcu;
60376056 const payload_ty = err_union_ty.errorUnionPayload(mod);
6038 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod);
6057 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt);
60396058 const err_union_llvm_ty = try o.lowerType(err_union_ty);
60406059 const error_type = try o.errorIntType();
60416060
......@@ -6048,8 +6067,8 @@ pub const FuncGen = struct {
60486067 else
60496068 err_union;
60506069 }
6051 const err_field_index = try errUnionErrorOffset(payload_ty, mod);
6052 if (operand_is_ptr or isByRef(err_union_ty, mod)) {
6070 const err_field_index = try errUnionErrorOffset(payload_ty, pt);
6071 if (operand_is_ptr or isByRef(err_union_ty, pt)) {
60536072 const err_field_ptr =
60546073 try fg.wip.gepStruct(err_union_llvm_ty, err_union, err_field_index, "");
60556074 // TODO add alignment to this load
......@@ -6077,13 +6096,13 @@ pub const FuncGen = struct {
60776096 }
60786097 if (is_unused) return .none;
60796098 if (!payload_has_bits) return if (operand_is_ptr) err_union else .none;
6080 const offset = try errUnionPayloadOffset(payload_ty, mod);
6099 const offset = try errUnionPayloadOffset(payload_ty, pt);
60816100 if (operand_is_ptr) {
60826101 return fg.wip.gepStruct(err_union_llvm_ty, err_union, offset, "");
6083 } else if (isByRef(err_union_ty, mod)) {
6102 } else if (isByRef(err_union_ty, pt)) {
60846103 const payload_ptr = try fg.wip.gepStruct(err_union_llvm_ty, err_union, offset, "");
6085 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
6086 if (isByRef(payload_ty, mod)) {
6104 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
6105 if (isByRef(payload_ty, pt)) {
60876106 if (can_elide_load)
60886107 return payload_ptr;
60896108
......@@ -6161,7 +6180,7 @@ pub const FuncGen = struct {
61616180
61626181 fn airLoop(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
61636182 const o = self.dg.object;
6164 const mod = o.module;
6183 const mod = o.pt.zcu;
61656184 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
61666185 const loop = self.air.extraData(Air.Block, ty_pl.payload);
61676186 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[loop.end..][0..loop.data.body_len]);
......@@ -6185,7 +6204,8 @@ pub const FuncGen = struct {
61856204
61866205 fn airArrayToSlice(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
61876206 const o = self.dg.object;
6188 const mod = o.module;
6207 const pt = o.pt;
6208 const mod = pt.zcu;
61896209 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61906210 const operand_ty = self.typeOf(ty_op.operand);
61916211 const array_ty = operand_ty.childType(mod);
......@@ -6193,7 +6213,7 @@ pub const FuncGen = struct {
61936213 const len = try o.builder.intValue(llvm_usize, array_ty.arrayLen(mod));
61946214 const slice_llvm_ty = try o.lowerType(self.typeOfIndex(inst));
61956215 const operand = try self.resolveInst(ty_op.operand);
6196 if (!array_ty.hasRuntimeBitsIgnoreComptime(mod))
6216 if (!array_ty.hasRuntimeBitsIgnoreComptime(pt))
61976217 return self.wip.buildAggregate(slice_llvm_ty, &.{ operand, len }, "");
61986218 const ptr = try self.wip.gep(.inbounds, try o.lowerType(array_ty), operand, &.{
61996219 try o.builder.intValue(llvm_usize, 0), try o.builder.intValue(llvm_usize, 0),
......@@ -6203,7 +6223,8 @@ pub const FuncGen = struct {
62036223
62046224 fn airFloatFromInt(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
62056225 const o = self.dg.object;
6206 const mod = o.module;
6226 const pt = o.pt;
6227 const mod = pt.zcu;
62076228 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
62086229
62096230 const workaround_operand = try self.resolveInst(ty_op.operand);
......@@ -6213,7 +6234,7 @@ pub const FuncGen = struct {
62136234
62146235 const operand = o: {
62156236 // Work around LLVM bug. See https://github.com/ziglang/zig/issues/17381.
6216 const bit_size = operand_scalar_ty.bitSize(mod);
6237 const bit_size = operand_scalar_ty.bitSize(pt);
62176238 for ([_]u8{ 8, 16, 32, 64, 128 }) |b| {
62186239 if (bit_size < b) {
62196240 break :o try self.wip.cast(
......@@ -6241,7 +6262,7 @@ pub const FuncGen = struct {
62416262 "",
62426263 );
62436264
6244 const rt_int_bits = compilerRtIntBits(@intCast(operand_scalar_ty.bitSize(mod)));
6265 const rt_int_bits = compilerRtIntBits(@intCast(operand_scalar_ty.bitSize(pt)));
62456266 const rt_int_ty = try o.builder.intType(rt_int_bits);
62466267 var extended = try self.wip.conv(
62476268 if (is_signed_int) .signed else .unsigned,
......@@ -6287,7 +6308,8 @@ pub const FuncGen = struct {
62876308 _ = fast;
62886309
62896310 const o = self.dg.object;
6290 const mod = o.module;
6311 const pt = o.pt;
6312 const mod = pt.zcu;
62916313 const target = mod.getTarget();
62926314 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
62936315
......@@ -6309,7 +6331,7 @@ pub const FuncGen = struct {
63096331 );
63106332 }
63116333
6312 const rt_int_bits = compilerRtIntBits(@intCast(dest_scalar_ty.bitSize(mod)));
6334 const rt_int_bits = compilerRtIntBits(@intCast(dest_scalar_ty.bitSize(pt)));
63136335 const ret_ty = try o.builder.intType(rt_int_bits);
63146336 const libc_ret_ty = if (rt_int_bits == 128 and (target.os.tag == .windows and target.cpu.arch == .x86_64)) b: {
63156337 // On Windows x86-64, "ti" functions must use Vector(2, u64) instead of the standard
......@@ -6348,19 +6370,20 @@ pub const FuncGen = struct {
63486370
63496371 fn sliceOrArrayPtr(fg: *FuncGen, ptr: Builder.Value, ty: Type) Allocator.Error!Builder.Value {
63506372 const o = fg.dg.object;
6351 const mod = o.module;
6373 const mod = o.pt.zcu;
63526374 return if (ty.isSlice(mod)) fg.wip.extractValue(ptr, &.{0}, "") else ptr;
63536375 }
63546376
63556377 fn sliceOrArrayLenInBytes(fg: *FuncGen, ptr: Builder.Value, ty: Type) Allocator.Error!Builder.Value {
63566378 const o = fg.dg.object;
6357 const mod = o.module;
6379 const pt = o.pt;
6380 const mod = pt.zcu;
63586381 const llvm_usize = try o.lowerType(Type.usize);
63596382 switch (ty.ptrSize(mod)) {
63606383 .Slice => {
63616384 const len = try fg.wip.extractValue(ptr, &.{1}, "");
63626385 const elem_ty = ty.childType(mod);
6363 const abi_size = elem_ty.abiSize(mod);
6386 const abi_size = elem_ty.abiSize(pt);
63646387 if (abi_size == 1) return len;
63656388 const abi_size_llvm_val = try o.builder.intValue(llvm_usize, abi_size);
63666389 return fg.wip.bin(.@"mul nuw", len, abi_size_llvm_val, "");
......@@ -6368,7 +6391,7 @@ pub const FuncGen = struct {
63686391 .One => {
63696392 const array_ty = ty.childType(mod);
63706393 const elem_ty = array_ty.childType(mod);
6371 const abi_size = elem_ty.abiSize(mod);
6394 const abi_size = elem_ty.abiSize(pt);
63726395 return o.builder.intValue(llvm_usize, array_ty.arrayLen(mod) * abi_size);
63736396 },
63746397 .Many, .C => unreachable,
......@@ -6383,7 +6406,7 @@ pub const FuncGen = struct {
63836406
63846407 fn airPtrSliceFieldPtr(self: *FuncGen, inst: Air.Inst.Index, index: c_uint) !Builder.Value {
63856408 const o = self.dg.object;
6386 const mod = o.module;
6409 const mod = o.pt.zcu;
63876410 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
63886411 const slice_ptr = try self.resolveInst(ty_op.operand);
63896412 const slice_ptr_ty = self.typeOf(ty_op.operand);
......@@ -6394,7 +6417,8 @@ pub const FuncGen = struct {
63946417
63956418 fn airSliceElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
63966419 const o = self.dg.object;
6397 const mod = o.module;
6420 const pt = o.pt;
6421 const mod = pt.zcu;
63986422 const inst = body_tail[0];
63996423 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
64006424 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -6404,11 +6428,11 @@ pub const FuncGen = struct {
64046428 const llvm_elem_ty = try o.lowerPtrElemTy(elem_ty);
64056429 const base_ptr = try self.wip.extractValue(slice, &.{0}, "");
64066430 const ptr = try self.wip.gep(.inbounds, llvm_elem_ty, base_ptr, &.{index}, "");
6407 if (isByRef(elem_ty, mod)) {
6431 if (isByRef(elem_ty, pt)) {
64086432 if (self.canElideLoad(body_tail))
64096433 return ptr;
64106434
6411 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6435 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64126436 return self.loadByRef(ptr, elem_ty, elem_alignment, .normal);
64136437 }
64146438
......@@ -6417,7 +6441,7 @@ pub const FuncGen = struct {
64176441
64186442 fn airSliceElemPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
64196443 const o = self.dg.object;
6420 const mod = o.module;
6444 const mod = o.pt.zcu;
64216445 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
64226446 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
64236447 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -6431,7 +6455,8 @@ pub const FuncGen = struct {
64316455
64326456 fn airArrayElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
64336457 const o = self.dg.object;
6434 const mod = o.module;
6458 const pt = o.pt;
6459 const mod = pt.zcu;
64356460 const inst = body_tail[0];
64366461
64376462 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
......@@ -6440,15 +6465,15 @@ pub const FuncGen = struct {
64406465 const rhs = try self.resolveInst(bin_op.rhs);
64416466 const array_llvm_ty = try o.lowerType(array_ty);
64426467 const elem_ty = array_ty.childType(mod);
6443 if (isByRef(array_ty, mod)) {
6468 if (isByRef(array_ty, pt)) {
64446469 const indices: [2]Builder.Value = .{
64456470 try o.builder.intValue(try o.lowerType(Type.usize), 0), rhs,
64466471 };
6447 if (isByRef(elem_ty, mod)) {
6472 if (isByRef(elem_ty, pt)) {
64486473 const elem_ptr =
64496474 try self.wip.gep(.inbounds, array_llvm_ty, array_llvm_val, &indices, "");
64506475 if (canElideLoad(self, body_tail)) return elem_ptr;
6451 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6476 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64526477 return self.loadByRef(elem_ptr, elem_ty, elem_alignment, .normal);
64536478 } else {
64546479 const elem_ptr =
......@@ -6463,7 +6488,8 @@ pub const FuncGen = struct {
64636488
64646489 fn airPtrElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
64656490 const o = self.dg.object;
6466 const mod = o.module;
6491 const pt = o.pt;
6492 const mod = pt.zcu;
64676493 const inst = body_tail[0];
64686494 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
64696495 const ptr_ty = self.typeOf(bin_op.lhs);
......@@ -6477,9 +6503,9 @@ pub const FuncGen = struct {
64776503 &.{ try o.builder.intValue(try o.lowerType(Type.usize), 0), rhs }
64786504 else
64796505 &.{rhs}, "");
6480 if (isByRef(elem_ty, mod)) {
6506 if (isByRef(elem_ty, pt)) {
64816507 if (self.canElideLoad(body_tail)) return ptr;
6482 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6508 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64836509 return self.loadByRef(ptr, elem_ty, elem_alignment, .normal);
64846510 }
64856511
......@@ -6488,12 +6514,13 @@ pub const FuncGen = struct {
64886514
64896515 fn airPtrElemPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
64906516 const o = self.dg.object;
6491 const mod = o.module;
6517 const pt = o.pt;
6518 const mod = pt.zcu;
64926519 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
64936520 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
64946521 const ptr_ty = self.typeOf(bin_op.lhs);
64956522 const elem_ty = ptr_ty.childType(mod);
6496 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return self.resolveInst(bin_op.lhs);
6523 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return self.resolveInst(bin_op.lhs);
64976524
64986525 const base_ptr = try self.resolveInst(bin_op.lhs);
64996526 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -6530,7 +6557,8 @@ pub const FuncGen = struct {
65306557
65316558 fn airStructFieldVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
65326559 const o = self.dg.object;
6533 const mod = o.module;
6560 const pt = o.pt;
6561 const mod = pt.zcu;
65346562 const inst = body_tail[0];
65356563 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
65366564 const struct_field = self.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -6538,27 +6566,27 @@ pub const FuncGen = struct {
65386566 const struct_llvm_val = try self.resolveInst(struct_field.struct_operand);
65396567 const field_index = struct_field.field_index;
65406568 const field_ty = struct_ty.structFieldType(field_index, mod);
6541 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
6569 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
65426570
6543 if (!isByRef(struct_ty, mod)) {
6544 assert(!isByRef(field_ty, mod));
6571 if (!isByRef(struct_ty, pt)) {
6572 assert(!isByRef(field_ty, pt));
65456573 switch (struct_ty.zigTypeTag(mod)) {
65466574 .Struct => switch (struct_ty.containerLayout(mod)) {
65476575 .@"packed" => {
65486576 const struct_type = mod.typeToStruct(struct_ty).?;
6549 const bit_offset = mod.structPackedFieldBitOffset(struct_type, field_index);
6577 const bit_offset = pt.structPackedFieldBitOffset(struct_type, field_index);
65506578 const containing_int = struct_llvm_val;
65516579 const shift_amt =
65526580 try o.builder.intValue(containing_int.typeOfWip(&self.wip), bit_offset);
65536581 const shifted_value = try self.wip.bin(.lshr, containing_int, shift_amt, "");
65546582 const elem_llvm_ty = try o.lowerType(field_ty);
65556583 if (field_ty.zigTypeTag(mod) == .Float or field_ty.zigTypeTag(mod) == .Vector) {
6556 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6584 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65576585 const truncated_int =
65586586 try self.wip.cast(.trunc, shifted_value, same_size_int, "");
65596587 return self.wip.cast(.bitcast, truncated_int, elem_llvm_ty, "");
65606588 } else if (field_ty.isPtrAtRuntime(mod)) {
6561 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6589 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65626590 const truncated_int =
65636591 try self.wip.cast(.trunc, shifted_value, same_size_int, "");
65646592 return self.wip.cast(.inttoptr, truncated_int, elem_llvm_ty, "");
......@@ -6575,12 +6603,12 @@ pub const FuncGen = struct {
65756603 const containing_int = struct_llvm_val;
65766604 const elem_llvm_ty = try o.lowerType(field_ty);
65776605 if (field_ty.zigTypeTag(mod) == .Float or field_ty.zigTypeTag(mod) == .Vector) {
6578 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6606 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65796607 const truncated_int =
65806608 try self.wip.cast(.trunc, containing_int, same_size_int, "");
65816609 return self.wip.cast(.bitcast, truncated_int, elem_llvm_ty, "");
65826610 } else if (field_ty.isPtrAtRuntime(mod)) {
6583 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6611 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65846612 const truncated_int =
65856613 try self.wip.cast(.trunc, containing_int, same_size_int, "");
65866614 return self.wip.cast(.inttoptr, truncated_int, elem_llvm_ty, "");
......@@ -6599,12 +6627,12 @@ pub const FuncGen = struct {
65996627 const llvm_field_index = o.llvmFieldIndex(struct_ty, field_index).?;
66006628 const field_ptr =
66016629 try self.wip.gepStruct(struct_llvm_ty, struct_llvm_val, llvm_field_index, "");
6602 const alignment = struct_ty.structFieldAlign(field_index, mod);
6603 const field_ptr_ty = try mod.ptrType(.{
6630 const alignment = struct_ty.structFieldAlign(field_index, pt);
6631 const field_ptr_ty = try pt.ptrType(.{
66046632 .child = field_ty.toIntern(),
66056633 .flags = .{ .alignment = alignment },
66066634 });
6607 if (isByRef(field_ty, mod)) {
6635 if (isByRef(field_ty, pt)) {
66086636 if (canElideLoad(self, body_tail))
66096637 return field_ptr;
66106638
......@@ -6617,12 +6645,12 @@ pub const FuncGen = struct {
66176645 },
66186646 .Union => {
66196647 const union_llvm_ty = try o.lowerType(struct_ty);
6620 const layout = struct_ty.unionGetLayout(mod);
6648 const layout = struct_ty.unionGetLayout(pt);
66216649 const payload_index = @intFromBool(layout.tag_align.compare(.gte, layout.payload_align));
66226650 const field_ptr =
66236651 try self.wip.gepStruct(union_llvm_ty, struct_llvm_val, payload_index, "");
66246652 const payload_alignment = layout.payload_align.toLlvm();
6625 if (isByRef(field_ty, mod)) {
6653 if (isByRef(field_ty, pt)) {
66266654 if (canElideLoad(self, body_tail)) return field_ptr;
66276655 return self.loadByRef(field_ptr, field_ty, payload_alignment, .normal);
66286656 } else {
......@@ -6635,14 +6663,15 @@ pub const FuncGen = struct {
66356663
66366664 fn airFieldParentPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
66376665 const o = self.dg.object;
6638 const mod = o.module;
6666 const pt = o.pt;
6667 const mod = pt.zcu;
66396668 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
66406669 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
66416670
66426671 const field_ptr = try self.resolveInst(extra.field_ptr);
66436672
66446673 const parent_ty = ty_pl.ty.toType().childType(mod);
6645 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
6674 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
66466675 if (field_offset == 0) return field_ptr;
66476676
66486677 const res_ty = try o.lowerType(ty_pl.ty.toType());
......@@ -6696,7 +6725,7 @@ pub const FuncGen = struct {
66966725
66976726 fn airDbgVarPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
66986727 const o = self.dg.object;
6699 const mod = o.module;
6728 const mod = o.pt.zcu;
67006729 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
67016730 const operand = try self.resolveInst(pl_op.operand);
67026731 const name = self.air.nullTerminatedString(pl_op.payload);
......@@ -6743,9 +6772,9 @@ pub const FuncGen = struct {
67436772 try o.lowerDebugType(operand_ty),
67446773 );
67456774
6746 const zcu = o.module;
6775 const pt = o.pt;
67476776 const owner_mod = self.dg.ownerModule();
6748 if (isByRef(operand_ty, zcu)) {
6777 if (isByRef(operand_ty, pt)) {
67496778 _ = try self.wip.callIntrinsic(
67506779 .normal,
67516780 .none,
......@@ -6759,7 +6788,7 @@ pub const FuncGen = struct {
67596788 "",
67606789 );
67616790 } else if (owner_mod.optimize_mode == .Debug) {
6762 const alignment = operand_ty.abiAlignment(zcu).toLlvm();
6791 const alignment = operand_ty.abiAlignment(pt).toLlvm();
67636792 const alloca = try self.buildAlloca(operand.typeOfWip(&self.wip), alignment);
67646793 _ = try self.wip.store(.normal, operand, alloca, alignment);
67656794 _ = try self.wip.callIntrinsic(
......@@ -6830,7 +6859,8 @@ pub const FuncGen = struct {
68306859 // This stores whether we need to add an elementtype attribute and
68316860 // if so, the element type itself.
68326861 const llvm_param_attrs = try arena.alloc(Builder.Type, max_param_count);
6833 const mod = o.module;
6862 const pt = o.pt;
6863 const mod = pt.zcu;
68346864 const target = mod.getTarget();
68356865
68366866 var llvm_ret_i: usize = 0;
......@@ -6930,13 +6960,13 @@ pub const FuncGen = struct {
69306960
69316961 const arg_llvm_value = try self.resolveInst(input);
69326962 const arg_ty = self.typeOf(input);
6933 const is_by_ref = isByRef(arg_ty, mod);
6963 const is_by_ref = isByRef(arg_ty, pt);
69346964 if (is_by_ref) {
69356965 if (constraintAllowsMemory(constraint)) {
69366966 llvm_param_values[llvm_param_i] = arg_llvm_value;
69376967 llvm_param_types[llvm_param_i] = arg_llvm_value.typeOfWip(&self.wip);
69386968 } else {
6939 const alignment = arg_ty.abiAlignment(mod).toLlvm();
6969 const alignment = arg_ty.abiAlignment(pt).toLlvm();
69406970 const arg_llvm_ty = try o.lowerType(arg_ty);
69416971 const load_inst =
69426972 try self.wip.load(.normal, arg_llvm_ty, arg_llvm_value, alignment, "");
......@@ -6948,7 +6978,7 @@ pub const FuncGen = struct {
69486978 llvm_param_values[llvm_param_i] = arg_llvm_value;
69496979 llvm_param_types[llvm_param_i] = arg_llvm_value.typeOfWip(&self.wip);
69506980 } else {
6951 const alignment = arg_ty.abiAlignment(mod).toLlvm();
6981 const alignment = arg_ty.abiAlignment(pt).toLlvm();
69526982 const arg_ptr = try self.buildAlloca(arg_llvm_value.typeOfWip(&self.wip), alignment);
69536983 _ = try self.wip.store(.normal, arg_llvm_value, arg_ptr, alignment);
69546984 llvm_param_values[llvm_param_i] = arg_ptr;
......@@ -7000,7 +7030,7 @@ pub const FuncGen = struct {
70007030 llvm_param_values[llvm_param_i] = llvm_rw_val;
70017031 llvm_param_types[llvm_param_i] = llvm_rw_val.typeOfWip(&self.wip);
70027032 } else {
7003 const alignment = rw_ty.abiAlignment(mod).toLlvm();
7033 const alignment = rw_ty.abiAlignment(pt).toLlvm();
70047034 const loaded = try self.wip.load(.normal, llvm_elem_ty, llvm_rw_val, alignment, "");
70057035 llvm_param_values[llvm_param_i] = loaded;
70067036 llvm_param_types[llvm_param_i] = llvm_elem_ty;
......@@ -7161,7 +7191,7 @@ pub const FuncGen = struct {
71617191 const output_ptr = try self.resolveInst(output);
71627192 const output_ptr_ty = self.typeOf(output);
71637193
7164 const alignment = output_ptr_ty.ptrAlignment(mod).toLlvm();
7194 const alignment = output_ptr_ty.ptrAlignment(pt).toLlvm();
71657195 _ = try self.wip.store(.normal, output_value, output_ptr, alignment);
71667196 } else {
71677197 ret_val = output_value;
......@@ -7179,7 +7209,8 @@ pub const FuncGen = struct {
71797209 cond: Builder.IntegerCondition,
71807210 ) !Builder.Value {
71817211 const o = self.dg.object;
7182 const mod = o.module;
7212 const pt = o.pt;
7213 const mod = pt.zcu;
71837214 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
71847215 const operand = try self.resolveInst(un_op);
71857216 const operand_ty = self.typeOf(un_op);
......@@ -7204,7 +7235,7 @@ pub const FuncGen = struct {
72047235
72057236 comptime assert(optional_layout_version == 3);
72067237
7207 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7238 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72087239 const loaded = if (operand_is_ptr)
72097240 try self.wip.load(.normal, optional_llvm_ty, operand, .default, "")
72107241 else
......@@ -7212,7 +7243,7 @@ pub const FuncGen = struct {
72127243 return self.wip.icmp(cond, loaded, try o.builder.intValue(.i8, 0), "");
72137244 }
72147245
7215 const is_by_ref = operand_is_ptr or isByRef(optional_ty, mod);
7246 const is_by_ref = operand_is_ptr or isByRef(optional_ty, pt);
72167247 return self.optCmpNull(cond, optional_llvm_ty, operand, is_by_ref);
72177248 }
72187249
......@@ -7223,7 +7254,8 @@ pub const FuncGen = struct {
72237254 operand_is_ptr: bool,
72247255 ) !Builder.Value {
72257256 const o = self.dg.object;
7226 const mod = o.module;
7257 const pt = o.pt;
7258 const mod = pt.zcu;
72277259 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72287260 const operand = try self.resolveInst(un_op);
72297261 const operand_ty = self.typeOf(un_op);
......@@ -7241,7 +7273,7 @@ pub const FuncGen = struct {
72417273 return val.toValue();
72427274 }
72437275
7244 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7276 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72457277 const loaded = if (operand_is_ptr)
72467278 try self.wip.load(.normal, try o.lowerType(err_union_ty), operand, .default, "")
72477279 else
......@@ -7249,9 +7281,9 @@ pub const FuncGen = struct {
72497281 return self.wip.icmp(cond, loaded, zero, "");
72507282 }
72517283
7252 const err_field_index = try errUnionErrorOffset(payload_ty, mod);
7284 const err_field_index = try errUnionErrorOffset(payload_ty, pt);
72537285
7254 const loaded = if (operand_is_ptr or isByRef(err_union_ty, mod)) loaded: {
7286 const loaded = if (operand_is_ptr or isByRef(err_union_ty, pt)) loaded: {
72557287 const err_union_llvm_ty = try o.lowerType(err_union_ty);
72567288 const err_field_ptr =
72577289 try self.wip.gepStruct(err_union_llvm_ty, operand, err_field_index, "");
......@@ -7262,12 +7294,13 @@ pub const FuncGen = struct {
72627294
72637295 fn airOptionalPayloadPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
72647296 const o = self.dg.object;
7265 const mod = o.module;
7297 const pt = o.pt;
7298 const mod = pt.zcu;
72667299 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
72677300 const operand = try self.resolveInst(ty_op.operand);
72687301 const optional_ty = self.typeOf(ty_op.operand).childType(mod);
72697302 const payload_ty = optional_ty.optionalChild(mod);
7270 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7303 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72717304 // We have a pointer to a zero-bit value and we need to return
72727305 // a pointer to a zero-bit value.
72737306 return operand;
......@@ -7283,13 +7316,14 @@ pub const FuncGen = struct {
72837316 comptime assert(optional_layout_version == 3);
72847317
72857318 const o = self.dg.object;
7286 const mod = o.module;
7319 const pt = o.pt;
7320 const mod = pt.zcu;
72877321 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
72887322 const operand = try self.resolveInst(ty_op.operand);
72897323 const optional_ty = self.typeOf(ty_op.operand).childType(mod);
72907324 const payload_ty = optional_ty.optionalChild(mod);
72917325 const non_null_bit = try o.builder.intValue(.i8, 1);
7292 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7326 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72937327 // We have a pointer to a i8. We need to set it to 1 and then return the same pointer.
72947328 _ = try self.wip.store(.normal, non_null_bit, operand, .default);
72957329 return operand;
......@@ -7314,13 +7348,14 @@ pub const FuncGen = struct {
73147348
73157349 fn airOptionalPayload(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
73167350 const o = self.dg.object;
7317 const mod = o.module;
7351 const pt = o.pt;
7352 const mod = pt.zcu;
73187353 const inst = body_tail[0];
73197354 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73207355 const operand = try self.resolveInst(ty_op.operand);
73217356 const optional_ty = self.typeOf(ty_op.operand);
73227357 const payload_ty = self.typeOfIndex(inst);
7323 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
7358 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
73247359
73257360 if (optional_ty.optionalReprIsPayload(mod)) {
73267361 // Payload value is the same as the optional value.
......@@ -7328,7 +7363,7 @@ pub const FuncGen = struct {
73287363 }
73297364
73307365 const opt_llvm_ty = try o.lowerType(optional_ty);
7331 const can_elide_load = if (isByRef(payload_ty, mod)) self.canElideLoad(body_tail) else false;
7366 const can_elide_load = if (isByRef(payload_ty, pt)) self.canElideLoad(body_tail) else false;
73327367 return self.optPayloadHandle(opt_llvm_ty, operand, optional_ty, can_elide_load);
73337368 }
73347369
......@@ -7338,7 +7373,8 @@ pub const FuncGen = struct {
73387373 operand_is_ptr: bool,
73397374 ) !Builder.Value {
73407375 const o = self.dg.object;
7341 const mod = o.module;
7376 const pt = o.pt;
7377 const mod = pt.zcu;
73427378 const inst = body_tail[0];
73437379 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73447380 const operand = try self.resolveInst(ty_op.operand);
......@@ -7347,17 +7383,17 @@ pub const FuncGen = struct {
73477383 const result_ty = self.typeOfIndex(inst);
73487384 const payload_ty = if (operand_is_ptr) result_ty.childType(mod) else result_ty;
73497385
7350 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7386 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
73517387 return if (operand_is_ptr) operand else .none;
73527388 }
7353 const offset = try errUnionPayloadOffset(payload_ty, mod);
7389 const offset = try errUnionPayloadOffset(payload_ty, pt);
73547390 const err_union_llvm_ty = try o.lowerType(err_union_ty);
73557391 if (operand_is_ptr) {
73567392 return self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
7357 } else if (isByRef(err_union_ty, mod)) {
7358 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
7393 } else if (isByRef(err_union_ty, pt)) {
7394 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
73597395 const payload_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
7360 if (isByRef(payload_ty, mod)) {
7396 if (isByRef(payload_ty, pt)) {
73617397 if (self.canElideLoad(body_tail)) return payload_ptr;
73627398 return self.loadByRef(payload_ptr, payload_ty, payload_alignment, .normal);
73637399 }
......@@ -7373,7 +7409,8 @@ pub const FuncGen = struct {
73737409 operand_is_ptr: bool,
73747410 ) !Builder.Value {
73757411 const o = self.dg.object;
7376 const mod = o.module;
7412 const pt = o.pt;
7413 const mod = pt.zcu;
73777414 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73787415 const operand = try self.resolveInst(ty_op.operand);
73797416 const operand_ty = self.typeOf(ty_op.operand);
......@@ -7388,14 +7425,14 @@ pub const FuncGen = struct {
73887425 }
73897426
73907427 const payload_ty = err_union_ty.errorUnionPayload(mod);
7391 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7428 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
73927429 if (!operand_is_ptr) return operand;
73937430 return self.wip.load(.normal, error_type, operand, .default, "");
73947431 }
73957432
7396 const offset = try errUnionErrorOffset(payload_ty, mod);
7433 const offset = try errUnionErrorOffset(payload_ty, pt);
73977434
7398 if (operand_is_ptr or isByRef(err_union_ty, mod)) {
7435 if (operand_is_ptr or isByRef(err_union_ty, pt)) {
73997436 const err_union_llvm_ty = try o.lowerType(err_union_ty);
74007437 const err_field_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
74017438 return self.wip.load(.normal, error_type, err_field_ptr, .default, "");
......@@ -7406,22 +7443,23 @@ pub const FuncGen = struct {
74067443
74077444 fn airErrUnionPayloadPtrSet(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
74087445 const o = self.dg.object;
7409 const mod = o.module;
7446 const pt = o.pt;
7447 const mod = pt.zcu;
74107448 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
74117449 const operand = try self.resolveInst(ty_op.operand);
74127450 const err_union_ty = self.typeOf(ty_op.operand).childType(mod);
74137451
74147452 const payload_ty = err_union_ty.errorUnionPayload(mod);
74157453 const non_error_val = try o.builder.intValue(try o.errorIntType(), 0);
7416 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7454 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
74177455 _ = try self.wip.store(.normal, non_error_val, operand, .default);
74187456 return operand;
74197457 }
74207458 const err_union_llvm_ty = try o.lowerType(err_union_ty);
74217459 {
7422 const err_int_ty = try mod.errorIntType();
7423 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7424 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7460 const err_int_ty = try pt.errorIntType();
7461 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
7462 const error_offset = try errUnionErrorOffset(payload_ty, pt);
74257463 // First set the non-error value.
74267464 const non_null_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, error_offset, "");
74277465 _ = try self.wip.store(.normal, non_error_val, non_null_ptr, error_alignment);
......@@ -7429,7 +7467,7 @@ pub const FuncGen = struct {
74297467 // Then return the payload pointer (only if it is used).
74307468 if (self.liveness.isUnused(inst)) return .none;
74317469
7432 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7470 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
74337471 return self.wip.gepStruct(err_union_llvm_ty, operand, payload_offset, "");
74347472 }
74357473
......@@ -7446,19 +7484,21 @@ pub const FuncGen = struct {
74467484
74477485 fn airSaveErrReturnTraceIndex(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
74487486 const o = self.dg.object;
7487 const pt = o.pt;
7488 const mod = pt.zcu;
7489
74497490 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
74507491 const struct_ty = ty_pl.ty.toType();
74517492 const field_index = ty_pl.payload;
74527493
7453 const mod = o.module;
74547494 const struct_llvm_ty = try o.lowerType(struct_ty);
74557495 const llvm_field_index = o.llvmFieldIndex(struct_ty, field_index).?;
74567496 assert(self.err_ret_trace != .none);
74577497 const field_ptr =
74587498 try self.wip.gepStruct(struct_llvm_ty, self.err_ret_trace, llvm_field_index, "");
7459 const field_alignment = struct_ty.structFieldAlign(field_index, mod);
7499 const field_alignment = struct_ty.structFieldAlign(field_index, pt);
74607500 const field_ty = struct_ty.structFieldType(field_index, mod);
7461 const field_ptr_ty = try mod.ptrType(.{
7501 const field_ptr_ty = try pt.ptrType(.{
74627502 .child = field_ty.toIntern(),
74637503 .flags = .{ .alignment = field_alignment },
74647504 });
......@@ -7490,29 +7530,30 @@ pub const FuncGen = struct {
74907530
74917531 fn airWrapOptional(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
74927532 const o = self.dg.object;
7493 const mod = o.module;
7533 const pt = o.pt;
7534 const mod = pt.zcu;
74947535 const inst = body_tail[0];
74957536 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
74967537 const payload_ty = self.typeOf(ty_op.operand);
74977538 const non_null_bit = try o.builder.intValue(.i8, 1);
74987539 comptime assert(optional_layout_version == 3);
7499 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return non_null_bit;
7540 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return non_null_bit;
75007541 const operand = try self.resolveInst(ty_op.operand);
75017542 const optional_ty = self.typeOfIndex(inst);
75027543 if (optional_ty.optionalReprIsPayload(mod)) return operand;
75037544 const llvm_optional_ty = try o.lowerType(optional_ty);
7504 if (isByRef(optional_ty, mod)) {
7545 if (isByRef(optional_ty, pt)) {
75057546 const directReturn = self.isNextRet(body_tail);
75067547 const optional_ptr = if (directReturn)
75077548 self.ret_ptr
75087549 else brk: {
7509 const alignment = optional_ty.abiAlignment(mod).toLlvm();
7550 const alignment = optional_ty.abiAlignment(pt).toLlvm();
75107551 const optional_ptr = try self.buildAllocaWorkaround(optional_ty, alignment);
75117552 break :brk optional_ptr;
75127553 };
75137554
75147555 const payload_ptr = try self.wip.gepStruct(llvm_optional_ty, optional_ptr, 0, "");
7515 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7556 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75167557 try self.store(payload_ptr, payload_ptr_ty, operand, .none);
75177558 const non_null_ptr = try self.wip.gepStruct(llvm_optional_ty, optional_ptr, 1, "");
75187559 _ = try self.wip.store(.normal, non_null_bit, non_null_ptr, .default);
......@@ -7523,36 +7564,36 @@ pub const FuncGen = struct {
75237564
75247565 fn airWrapErrUnionPayload(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
75257566 const o = self.dg.object;
7526 const mod = o.module;
7567 const pt = o.pt;
75277568 const inst = body_tail[0];
75287569 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
75297570 const err_un_ty = self.typeOfIndex(inst);
75307571 const operand = try self.resolveInst(ty_op.operand);
75317572 const payload_ty = self.typeOf(ty_op.operand);
7532 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7573 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
75337574 return operand;
75347575 }
75357576 const ok_err_code = try o.builder.intValue(try o.errorIntType(), 0);
75367577 const err_un_llvm_ty = try o.lowerType(err_un_ty);
75377578
7538 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7539 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7540 if (isByRef(err_un_ty, mod)) {
7579 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
7580 const error_offset = try errUnionErrorOffset(payload_ty, pt);
7581 if (isByRef(err_un_ty, pt)) {
75417582 const directReturn = self.isNextRet(body_tail);
75427583 const result_ptr = if (directReturn)
75437584 self.ret_ptr
75447585 else brk: {
7545 const alignment = err_un_ty.abiAlignment(mod).toLlvm();
7586 const alignment = err_un_ty.abiAlignment(pt).toLlvm();
75467587 const result_ptr = try self.buildAllocaWorkaround(err_un_ty, alignment);
75477588 break :brk result_ptr;
75487589 };
75497590
75507591 const err_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, error_offset, "");
7551 const err_int_ty = try mod.errorIntType();
7552 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7592 const err_int_ty = try pt.errorIntType();
7593 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
75537594 _ = try self.wip.store(.normal, ok_err_code, err_ptr, error_alignment);
75547595 const payload_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, payload_offset, "");
7555 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7596 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75567597 try self.store(payload_ptr, payload_ptr_ty, operand, .none);
75577598 return result_ptr;
75587599 }
......@@ -7564,33 +7605,34 @@ pub const FuncGen = struct {
75647605
75657606 fn airWrapErrUnionErr(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
75667607 const o = self.dg.object;
7567 const mod = o.module;
7608 const pt = o.pt;
7609 const mod = pt.zcu;
75687610 const inst = body_tail[0];
75697611 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
75707612 const err_un_ty = self.typeOfIndex(inst);
75717613 const payload_ty = err_un_ty.errorUnionPayload(mod);
75727614 const operand = try self.resolveInst(ty_op.operand);
7573 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return operand;
7615 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return operand;
75747616 const err_un_llvm_ty = try o.lowerType(err_un_ty);
75757617
7576 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7577 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7578 if (isByRef(err_un_ty, mod)) {
7618 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
7619 const error_offset = try errUnionErrorOffset(payload_ty, pt);
7620 if (isByRef(err_un_ty, pt)) {
75797621 const directReturn = self.isNextRet(body_tail);
75807622 const result_ptr = if (directReturn)
75817623 self.ret_ptr
75827624 else brk: {
7583 const alignment = err_un_ty.abiAlignment(mod).toLlvm();
7625 const alignment = err_un_ty.abiAlignment(pt).toLlvm();
75847626 const result_ptr = try self.buildAllocaWorkaround(err_un_ty, alignment);
75857627 break :brk result_ptr;
75867628 };
75877629
75887630 const err_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, error_offset, "");
7589 const err_int_ty = try mod.errorIntType();
7590 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7631 const err_int_ty = try pt.errorIntType();
7632 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
75917633 _ = try self.wip.store(.normal, operand, err_ptr, error_alignment);
75927634 const payload_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, payload_offset, "");
7593 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7635 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75947636 // TODO store undef to payload_ptr
75957637 _ = payload_ptr;
75967638 _ = payload_ptr_ty;
......@@ -7624,7 +7666,8 @@ pub const FuncGen = struct {
76247666
76257667 fn airVectorStoreElem(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76267668 const o = self.dg.object;
7627 const mod = o.module;
7669 const pt = o.pt;
7670 const mod = pt.zcu;
76287671 const data = self.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
76297672 const extra = self.air.extraData(Air.Bin, data.payload).data;
76307673
......@@ -7636,7 +7679,7 @@ pub const FuncGen = struct {
76367679 const access_kind: Builder.MemoryAccessKind =
76377680 if (vector_ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
76387681 const elem_llvm_ty = try o.lowerType(vector_ptr_ty.childType(mod));
7639 const alignment = vector_ptr_ty.ptrAlignment(mod).toLlvm();
7682 const alignment = vector_ptr_ty.ptrAlignment(pt).toLlvm();
76407683 const loaded = try self.wip.load(access_kind, elem_llvm_ty, vector_ptr, alignment, "");
76417684
76427685 const new_vector = try self.wip.insertElement(loaded, operand, index, "");
......@@ -7646,7 +7689,7 @@ pub const FuncGen = struct {
76467689
76477690 fn airMin(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76487691 const o = self.dg.object;
7649 const mod = o.module;
7692 const mod = o.pt.zcu;
76507693 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
76517694 const lhs = try self.resolveInst(bin_op.lhs);
76527695 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7666,7 +7709,7 @@ pub const FuncGen = struct {
76667709
76677710 fn airMax(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76687711 const o = self.dg.object;
7669 const mod = o.module;
7712 const mod = o.pt.zcu;
76707713 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
76717714 const lhs = try self.resolveInst(bin_op.lhs);
76727715 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7696,7 +7739,7 @@ pub const FuncGen = struct {
76967739
76977740 fn airAdd(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
76987741 const o = self.dg.object;
7699 const mod = o.module;
7742 const mod = o.pt.zcu;
77007743 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77017744 const lhs = try self.resolveInst(bin_op.lhs);
77027745 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7714,7 +7757,7 @@ pub const FuncGen = struct {
77147757 unsigned_intrinsic: Builder.Intrinsic,
77157758 ) !Builder.Value {
77167759 const o = fg.dg.object;
7717 const mod = o.module;
7760 const mod = o.pt.zcu;
77187761
77197762 const bin_op = fg.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77207763 const lhs = try fg.resolveInst(bin_op.lhs);
......@@ -7762,7 +7805,7 @@ pub const FuncGen = struct {
77627805
77637806 fn airAddSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
77647807 const o = self.dg.object;
7765 const mod = o.module;
7808 const mod = o.pt.zcu;
77667809 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77677810 const lhs = try self.resolveInst(bin_op.lhs);
77687811 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7782,7 +7825,7 @@ pub const FuncGen = struct {
77827825
77837826 fn airSub(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
77847827 const o = self.dg.object;
7785 const mod = o.module;
7828 const mod = o.pt.zcu;
77867829 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77877830 const lhs = try self.resolveInst(bin_op.lhs);
77887831 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7803,7 +7846,7 @@ pub const FuncGen = struct {
78037846
78047847 fn airSubSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
78057848 const o = self.dg.object;
7806 const mod = o.module;
7849 const mod = o.pt.zcu;
78077850 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78087851 const lhs = try self.resolveInst(bin_op.lhs);
78097852 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7823,7 +7866,7 @@ pub const FuncGen = struct {
78237866
78247867 fn airMul(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78257868 const o = self.dg.object;
7826 const mod = o.module;
7869 const mod = o.pt.zcu;
78277870 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78287871 const lhs = try self.resolveInst(bin_op.lhs);
78297872 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7844,7 +7887,7 @@ pub const FuncGen = struct {
78447887
78457888 fn airMulSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
78467889 const o = self.dg.object;
7847 const mod = o.module;
7890 const mod = o.pt.zcu;
78487891 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78497892 const lhs = try self.resolveInst(bin_op.lhs);
78507893 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7873,7 +7916,7 @@ pub const FuncGen = struct {
78737916
78747917 fn airDivTrunc(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78757918 const o = self.dg.object;
7876 const mod = o.module;
7919 const mod = o.pt.zcu;
78777920 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78787921 const lhs = try self.resolveInst(bin_op.lhs);
78797922 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7889,7 +7932,7 @@ pub const FuncGen = struct {
78897932
78907933 fn airDivFloor(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78917934 const o = self.dg.object;
7892 const mod = o.module;
7935 const mod = o.pt.zcu;
78937936 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78947937 const lhs = try self.resolveInst(bin_op.lhs);
78957938 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7921,7 +7964,7 @@ pub const FuncGen = struct {
79217964
79227965 fn airDivExact(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79237966 const o = self.dg.object;
7924 const mod = o.module;
7967 const mod = o.pt.zcu;
79257968 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79267969 const lhs = try self.resolveInst(bin_op.lhs);
79277970 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7939,7 +7982,7 @@ pub const FuncGen = struct {
79397982
79407983 fn airRem(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79417984 const o = self.dg.object;
7942 const mod = o.module;
7985 const mod = o.pt.zcu;
79437986 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79447987 const lhs = try self.resolveInst(bin_op.lhs);
79457988 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7956,7 +7999,7 @@ pub const FuncGen = struct {
79567999
79578000 fn airMod(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79588001 const o = self.dg.object;
7959 const mod = o.module;
8002 const mod = o.pt.zcu;
79608003 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79618004 const lhs = try self.resolveInst(bin_op.lhs);
79628005 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7992,7 +8035,7 @@ pub const FuncGen = struct {
79928035
79938036 fn airPtrAdd(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
79948037 const o = self.dg.object;
7995 const mod = o.module;
8038 const mod = o.pt.zcu;
79968039 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
79978040 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
79988041 const ptr = try self.resolveInst(bin_op.lhs);
......@@ -8014,7 +8057,7 @@ pub const FuncGen = struct {
80148057
80158058 fn airPtrSub(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
80168059 const o = self.dg.object;
8017 const mod = o.module;
8060 const mod = o.pt.zcu;
80188061 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
80198062 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
80208063 const ptr = try self.resolveInst(bin_op.lhs);
......@@ -8042,7 +8085,8 @@ pub const FuncGen = struct {
80428085 unsigned_intrinsic: Builder.Intrinsic,
80438086 ) !Builder.Value {
80448087 const o = self.dg.object;
8045 const mod = o.module;
8088 const pt = o.pt;
8089 const mod = pt.zcu;
80468090 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
80478091 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
80488092
......@@ -8065,8 +8109,8 @@ pub const FuncGen = struct {
80658109 const result_index = o.llvmFieldIndex(inst_ty, 0).?;
80668110 const overflow_index = o.llvmFieldIndex(inst_ty, 1).?;
80678111
8068 if (isByRef(inst_ty, mod)) {
8069 const result_alignment = inst_ty.abiAlignment(mod).toLlvm();
8112 if (isByRef(inst_ty, pt)) {
8113 const result_alignment = inst_ty.abiAlignment(pt).toLlvm();
80708114 const alloca_inst = try self.buildAllocaWorkaround(inst_ty, result_alignment);
80718115 {
80728116 const field_ptr = try self.wip.gepStruct(llvm_inst_ty, alloca_inst, result_index, "");
......@@ -8135,7 +8179,7 @@ pub const FuncGen = struct {
81358179 return o.builder.addFunction(
81368180 try o.builder.fnType(return_type, param_types, .normal),
81378181 fn_name,
8138 toLlvmAddressSpace(.generic, o.module.getTarget()),
8182 toLlvmAddressSpace(.generic, o.pt.zcu.getTarget()),
81398183 );
81408184 }
81418185
......@@ -8149,8 +8193,8 @@ pub const FuncGen = struct {
81498193 params: [2]Builder.Value,
81508194 ) !Builder.Value {
81518195 const o = self.dg.object;
8152 const mod = o.module;
8153 const target = o.module.getTarget();
8196 const mod = o.pt.zcu;
8197 const target = mod.getTarget();
81548198 const scalar_ty = ty.scalarType(mod);
81558199 const scalar_llvm_ty = try o.lowerType(scalar_ty);
81568200
......@@ -8255,7 +8299,7 @@ pub const FuncGen = struct {
82558299 params: [params_len]Builder.Value,
82568300 ) !Builder.Value {
82578301 const o = self.dg.object;
8258 const mod = o.module;
8302 const mod = o.pt.zcu;
82598303 const target = mod.getTarget();
82608304 const scalar_ty = ty.scalarType(mod);
82618305 const llvm_ty = try o.lowerType(ty);
......@@ -8396,7 +8440,8 @@ pub const FuncGen = struct {
83968440
83978441 fn airShlWithOverflow(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
83988442 const o = self.dg.object;
8399 const mod = o.module;
8443 const pt = o.pt;
8444 const mod = pt.zcu;
84008445 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
84018446 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
84028447
......@@ -8422,8 +8467,8 @@ pub const FuncGen = struct {
84228467 const result_index = o.llvmFieldIndex(dest_ty, 0).?;
84238468 const overflow_index = o.llvmFieldIndex(dest_ty, 1).?;
84248469
8425 if (isByRef(dest_ty, mod)) {
8426 const result_alignment = dest_ty.abiAlignment(mod).toLlvm();
8470 if (isByRef(dest_ty, pt)) {
8471 const result_alignment = dest_ty.abiAlignment(pt).toLlvm();
84278472 const alloca_inst = try self.buildAllocaWorkaround(dest_ty, result_alignment);
84288473 {
84298474 const field_ptr = try self.wip.gepStruct(llvm_dest_ty, alloca_inst, result_index, "");
......@@ -8466,7 +8511,7 @@ pub const FuncGen = struct {
84668511
84678512 fn airShlExact(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
84688513 const o = self.dg.object;
8469 const mod = o.module;
8514 const mod = o.pt.zcu;
84708515 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
84718516
84728517 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8497,7 +8542,8 @@ pub const FuncGen = struct {
84978542
84988543 fn airShlSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
84998544 const o = self.dg.object;
8500 const mod = o.module;
8545 const pt = o.pt;
8546 const mod = pt.zcu;
85018547 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
85028548
85038549 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8505,7 +8551,7 @@ pub const FuncGen = struct {
85058551
85068552 const lhs_ty = self.typeOf(bin_op.lhs);
85078553 const lhs_scalar_ty = lhs_ty.scalarType(mod);
8508 const lhs_bits = lhs_scalar_ty.bitSize(mod);
8554 const lhs_bits = lhs_scalar_ty.bitSize(pt);
85098555
85108556 const casted_rhs = try self.wip.conv(.unsigned, rhs, try o.lowerType(lhs_ty), "");
85118557
......@@ -8539,7 +8585,7 @@ pub const FuncGen = struct {
85398585
85408586 fn airShr(self: *FuncGen, inst: Air.Inst.Index, is_exact: bool) !Builder.Value {
85418587 const o = self.dg.object;
8542 const mod = o.module;
8588 const mod = o.pt.zcu;
85438589 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
85448590
85458591 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8558,7 +8604,7 @@ pub const FuncGen = struct {
85588604
85598605 fn airAbs(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
85608606 const o = self.dg.object;
8561 const mod = o.module;
8607 const mod = o.pt.zcu;
85628608 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
85638609 const operand = try self.resolveInst(ty_op.operand);
85648610 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8580,7 +8626,7 @@ pub const FuncGen = struct {
85808626
85818627 fn airIntCast(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
85828628 const o = self.dg.object;
8583 const mod = o.module;
8629 const mod = o.pt.zcu;
85848630 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
85858631 const dest_ty = self.typeOfIndex(inst);
85868632 const dest_llvm_ty = try o.lowerType(dest_ty);
......@@ -8604,7 +8650,7 @@ pub const FuncGen = struct {
86048650
86058651 fn airFptrunc(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
86068652 const o = self.dg.object;
8607 const mod = o.module;
8653 const mod = o.pt.zcu;
86088654 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
86098655 const operand = try self.resolveInst(ty_op.operand);
86108656 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8638,7 +8684,7 @@ pub const FuncGen = struct {
86388684
86398685 fn airFpext(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
86408686 const o = self.dg.object;
8641 const mod = o.module;
8687 const mod = o.pt.zcu;
86428688 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
86438689 const operand = try self.resolveInst(ty_op.operand);
86448690 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8696,9 +8742,10 @@ pub const FuncGen = struct {
86968742
86978743 fn bitCast(self: *FuncGen, operand: Builder.Value, operand_ty: Type, inst_ty: Type) !Builder.Value {
86988744 const o = self.dg.object;
8699 const mod = o.module;
8700 const operand_is_ref = isByRef(operand_ty, mod);
8701 const result_is_ref = isByRef(inst_ty, mod);
8745 const pt = o.pt;
8746 const mod = pt.zcu;
8747 const operand_is_ref = isByRef(operand_ty, pt);
8748 const result_is_ref = isByRef(inst_ty, pt);
87028749 const llvm_dest_ty = try o.lowerType(inst_ty);
87038750
87048751 if (operand_is_ref and result_is_ref) {
......@@ -8721,9 +8768,9 @@ pub const FuncGen = struct {
87218768 if (!result_is_ref) {
87228769 return self.dg.todo("implement bitcast vector to non-ref array", .{});
87238770 }
8724 const alignment = inst_ty.abiAlignment(mod).toLlvm();
8771 const alignment = inst_ty.abiAlignment(pt).toLlvm();
87258772 const array_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
8726 const bitcast_ok = elem_ty.bitSize(mod) == elem_ty.abiSize(mod) * 8;
8773 const bitcast_ok = elem_ty.bitSize(pt) == elem_ty.abiSize(pt) * 8;
87278774 if (bitcast_ok) {
87288775 _ = try self.wip.store(.normal, operand, array_ptr, alignment);
87298776 } else {
......@@ -8748,11 +8795,11 @@ pub const FuncGen = struct {
87488795 const llvm_vector_ty = try o.lowerType(inst_ty);
87498796 if (!operand_is_ref) return self.dg.todo("implement bitcast non-ref array to vector", .{});
87508797
8751 const bitcast_ok = elem_ty.bitSize(mod) == elem_ty.abiSize(mod) * 8;
8798 const bitcast_ok = elem_ty.bitSize(pt) == elem_ty.abiSize(pt) * 8;
87528799 if (bitcast_ok) {
87538800 // The array is aligned to the element's alignment, while the vector might have a completely
87548801 // different alignment. This means we need to enforce the alignment of this load.
8755 const alignment = elem_ty.abiAlignment(mod).toLlvm();
8802 const alignment = elem_ty.abiAlignment(pt).toLlvm();
87568803 return self.wip.load(.normal, llvm_vector_ty, operand, alignment, "");
87578804 } else {
87588805 // If the ABI size of the element type is not evenly divisible by size in bits;
......@@ -8777,24 +8824,25 @@ pub const FuncGen = struct {
87778824 }
87788825
87798826 if (operand_is_ref) {
8780 const alignment = operand_ty.abiAlignment(mod).toLlvm();
8827 const alignment = operand_ty.abiAlignment(pt).toLlvm();
87818828 return self.wip.load(.normal, llvm_dest_ty, operand, alignment, "");
87828829 }
87838830
87848831 if (result_is_ref) {
8785 const alignment = operand_ty.abiAlignment(mod).max(inst_ty.abiAlignment(mod)).toLlvm();
8832 const alignment = operand_ty.abiAlignment(pt).max(inst_ty.abiAlignment(pt)).toLlvm();
87868833 const result_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
87878834 _ = try self.wip.store(.normal, operand, result_ptr, alignment);
87888835 return result_ptr;
87898836 }
87908837
87918838 if (llvm_dest_ty.isStruct(&o.builder) or
8792 ((operand_ty.zigTypeTag(mod) == .Vector or inst_ty.zigTypeTag(mod) == .Vector) and operand_ty.bitSize(mod) != inst_ty.bitSize(mod)))
8839 ((operand_ty.zigTypeTag(mod) == .Vector or inst_ty.zigTypeTag(mod) == .Vector) and
8840 operand_ty.bitSize(pt) != inst_ty.bitSize(pt)))
87938841 {
87948842 // Both our operand and our result are values, not pointers,
87958843 // but LLVM won't let us bitcast struct values or vectors with padding bits.
87968844 // Therefore, we store operand to alloca, then load for result.
8797 const alignment = operand_ty.abiAlignment(mod).max(inst_ty.abiAlignment(mod)).toLlvm();
8845 const alignment = operand_ty.abiAlignment(pt).max(inst_ty.abiAlignment(pt)).toLlvm();
87988846 const result_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
87998847 _ = try self.wip.store(.normal, operand, result_ptr, alignment);
88008848 return self.wip.load(.normal, llvm_dest_ty, result_ptr, alignment, "");
......@@ -8811,7 +8859,8 @@ pub const FuncGen = struct {
88118859
88128860 fn airArg(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
88138861 const o = self.dg.object;
8814 const mod = o.module;
8862 const pt = o.pt;
8863 const mod = pt.zcu;
88158864 const arg_val = self.args[self.arg_index];
88168865 self.arg_index += 1;
88178866
......@@ -8847,7 +8896,7 @@ pub const FuncGen = struct {
88478896 };
88488897
88498898 const owner_mod = self.dg.ownerModule();
8850 if (isByRef(inst_ty, mod)) {
8899 if (isByRef(inst_ty, pt)) {
88518900 _ = try self.wip.callIntrinsic(
88528901 .normal,
88538902 .none,
......@@ -8861,7 +8910,7 @@ pub const FuncGen = struct {
88618910 "",
88628911 );
88638912 } else if (owner_mod.optimize_mode == .Debug) {
8864 const alignment = inst_ty.abiAlignment(mod).toLlvm();
8913 const alignment = inst_ty.abiAlignment(pt).toLlvm();
88658914 const alloca = try self.buildAlloca(arg_val.typeOfWip(&self.wip), alignment);
88668915 _ = try self.wip.store(.normal, arg_val, alloca, alignment);
88678916 _ = try self.wip.callIntrinsic(
......@@ -8897,27 +8946,29 @@ pub const FuncGen = struct {
88978946
88988947 fn airAlloc(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
88998948 const o = self.dg.object;
8900 const mod = o.module;
8949 const pt = o.pt;
8950 const mod = pt.zcu;
89018951 const ptr_ty = self.typeOfIndex(inst);
89028952 const pointee_type = ptr_ty.childType(mod);
8903 if (!pointee_type.isFnOrHasRuntimeBitsIgnoreComptime(mod))
8953 if (!pointee_type.isFnOrHasRuntimeBitsIgnoreComptime(pt))
89048954 return (try o.lowerPtrToVoid(ptr_ty)).toValue();
89058955
89068956 //const pointee_llvm_ty = try o.lowerType(pointee_type);
8907 const alignment = ptr_ty.ptrAlignment(mod).toLlvm();
8957 const alignment = ptr_ty.ptrAlignment(pt).toLlvm();
89088958 return self.buildAllocaWorkaround(pointee_type, alignment);
89098959 }
89108960
89118961 fn airRetPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
89128962 const o = self.dg.object;
8913 const mod = o.module;
8963 const pt = o.pt;
8964 const mod = pt.zcu;
89148965 const ptr_ty = self.typeOfIndex(inst);
89158966 const ret_ty = ptr_ty.childType(mod);
8916 if (!ret_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod))
8967 if (!ret_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt))
89178968 return (try o.lowerPtrToVoid(ptr_ty)).toValue();
89188969 if (self.ret_ptr != .none) return self.ret_ptr;
89198970 //const ret_llvm_ty = try o.lowerType(ret_ty);
8920 const alignment = ptr_ty.ptrAlignment(mod).toLlvm();
8971 const alignment = ptr_ty.ptrAlignment(pt).toLlvm();
89218972 return self.buildAllocaWorkaround(ret_ty, alignment);
89228973 }
89238974
......@@ -8928,7 +8979,7 @@ pub const FuncGen = struct {
89288979 llvm_ty: Builder.Type,
89298980 alignment: Builder.Alignment,
89308981 ) Allocator.Error!Builder.Value {
8931 const target = self.dg.object.module.getTarget();
8982 const target = self.dg.object.pt.zcu.getTarget();
89328983 return buildAllocaInner(&self.wip, llvm_ty, alignment, target);
89338984 }
89348985
......@@ -8939,18 +8990,19 @@ pub const FuncGen = struct {
89398990 alignment: Builder.Alignment,
89408991 ) Allocator.Error!Builder.Value {
89418992 const o = self.dg.object;
8942 return self.buildAlloca(try o.builder.arrayType(ty.abiSize(o.module), .i8), alignment);
8993 return self.buildAlloca(try o.builder.arrayType(ty.abiSize(o.pt), .i8), alignment);
89438994 }
89448995
89458996 fn airStore(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
89468997 const o = self.dg.object;
8947 const mod = o.module;
8998 const pt = o.pt;
8999 const mod = pt.zcu;
89489000 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
89499001 const dest_ptr = try self.resolveInst(bin_op.lhs);
89509002 const ptr_ty = self.typeOf(bin_op.lhs);
89519003 const operand_ty = ptr_ty.childType(mod);
89529004
8953 const val_is_undef = if (try self.air.value(bin_op.rhs, mod)) |val| val.isUndefDeep(mod) else false;
9005 const val_is_undef = if (try self.air.value(bin_op.rhs, pt)) |val| val.isUndefDeep(mod) else false;
89549006 if (val_is_undef) {
89559007 const ptr_info = ptr_ty.ptrInfo(mod);
89569008 const needs_bitmask = (ptr_info.packed_offset.host_size != 0);
......@@ -8964,10 +9016,10 @@ pub const FuncGen = struct {
89649016 // Even if safety is disabled, we still emit a memset to undefined since it conveys
89659017 // extra information to LLVM. However, safety makes the difference between using
89669018 // 0xaa or actual undefined for the fill byte.
8967 const len = try o.builder.intValue(try o.lowerType(Type.usize), operand_ty.abiSize(mod));
9019 const len = try o.builder.intValue(try o.lowerType(Type.usize), operand_ty.abiSize(pt));
89689020 _ = try self.wip.callMemSet(
89699021 dest_ptr,
8970 ptr_ty.ptrAlignment(mod).toLlvm(),
9022 ptr_ty.ptrAlignment(pt).toLlvm(),
89719023 if (safety) try o.builder.intValue(.i8, 0xaa) else try o.builder.undefValue(.i8),
89729024 len,
89739025 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal,
......@@ -8992,7 +9044,7 @@ pub const FuncGen = struct {
89929044 /// The first instruction of `body_tail` is the one whose copy we want to elide.
89939045 fn canElideLoad(fg: *FuncGen, body_tail: []const Air.Inst.Index) bool {
89949046 const o = fg.dg.object;
8995 const mod = o.module;
9047 const mod = o.pt.zcu;
89969048 const ip = &mod.intern_pool;
89979049 for (body_tail[1..]) |body_inst| {
89989050 switch (fg.liveness.categorizeOperand(fg.air, body_inst, body_tail[0], ip)) {
......@@ -9008,7 +9060,8 @@ pub const FuncGen = struct {
90089060
90099061 fn airLoad(fg: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
90109062 const o = fg.dg.object;
9011 const mod = o.module;
9063 const pt = o.pt;
9064 const mod = pt.zcu;
90129065 const inst = body_tail[0];
90139066 const ty_op = fg.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
90149067 const ptr_ty = fg.typeOf(ty_op.operand);
......@@ -9016,7 +9069,7 @@ pub const FuncGen = struct {
90169069 const ptr = try fg.resolveInst(ty_op.operand);
90179070
90189071 elide: {
9019 if (!isByRef(Type.fromInterned(ptr_info.child), mod)) break :elide;
9072 if (!isByRef(Type.fromInterned(ptr_info.child), pt)) break :elide;
90209073 if (!canElideLoad(fg, body_tail)) break :elide;
90219074 return ptr;
90229075 }
......@@ -9040,7 +9093,7 @@ pub const FuncGen = struct {
90409093 _ = inst;
90419094 const o = self.dg.object;
90429095 const llvm_usize = try o.lowerType(Type.usize);
9043 if (!target_util.supportsReturnAddress(o.module.getTarget())) {
9096 if (!target_util.supportsReturnAddress(o.pt.zcu.getTarget())) {
90449097 // https://github.com/ziglang/zig/issues/11946
90459098 return o.builder.intValue(llvm_usize, 0);
90469099 }
......@@ -9068,7 +9121,8 @@ pub const FuncGen = struct {
90689121 kind: Builder.Function.Instruction.CmpXchg.Kind,
90699122 ) !Builder.Value {
90709123 const o = self.dg.object;
9071 const mod = o.module;
9124 const pt = o.pt;
9125 const mod = pt.zcu;
90729126 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
90739127 const extra = self.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
90749128 const ptr = try self.resolveInst(extra.ptr);
......@@ -9095,7 +9149,7 @@ pub const FuncGen = struct {
90959149 self.sync_scope,
90969150 toLlvmAtomicOrdering(extra.successOrder()),
90979151 toLlvmAtomicOrdering(extra.failureOrder()),
9098 ptr_ty.ptrAlignment(mod).toLlvm(),
9152 ptr_ty.ptrAlignment(pt).toLlvm(),
90999153 "",
91009154 );
91019155
......@@ -9118,7 +9172,8 @@ pub const FuncGen = struct {
91189172
91199173 fn airAtomicRmw(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
91209174 const o = self.dg.object;
9121 const mod = o.module;
9175 const pt = o.pt;
9176 const mod = pt.zcu;
91229177 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
91239178 const extra = self.air.extraData(Air.AtomicRmw, pl_op.payload).data;
91249179 const ptr = try self.resolveInst(pl_op.operand);
......@@ -9134,7 +9189,7 @@ pub const FuncGen = struct {
91349189
91359190 const access_kind: Builder.MemoryAccessKind =
91369191 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
9137 const ptr_alignment = ptr_ty.ptrAlignment(mod).toLlvm();
9192 const ptr_alignment = ptr_ty.ptrAlignment(pt).toLlvm();
91389193
91399194 if (llvm_abi_ty != .none) {
91409195 // operand needs widening and truncating or bitcasting.
......@@ -9181,19 +9236,20 @@ pub const FuncGen = struct {
91819236
91829237 fn airAtomicLoad(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
91839238 const o = self.dg.object;
9184 const mod = o.module;
9239 const pt = o.pt;
9240 const mod = pt.zcu;
91859241 const atomic_load = self.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
91869242 const ptr = try self.resolveInst(atomic_load.ptr);
91879243 const ptr_ty = self.typeOf(atomic_load.ptr);
91889244 const info = ptr_ty.ptrInfo(mod);
91899245 const elem_ty = Type.fromInterned(info.child);
9190 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
9246 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
91919247 const ordering = toLlvmAtomicOrdering(atomic_load.order);
91929248 const llvm_abi_ty = try o.getAtomicAbiType(elem_ty, false);
91939249 const ptr_alignment = (if (info.flags.alignment != .none)
91949250 @as(InternPool.Alignment, info.flags.alignment)
91959251 else
9196 Type.fromInterned(info.child).abiAlignment(mod)).toLlvm();
9252 Type.fromInterned(info.child).abiAlignment(pt)).toLlvm();
91979253 const access_kind: Builder.MemoryAccessKind =
91989254 if (info.flags.is_volatile) .@"volatile" else .normal;
91999255 const elem_llvm_ty = try o.lowerType(elem_ty);
......@@ -9228,11 +9284,12 @@ pub const FuncGen = struct {
92289284 ordering: Builder.AtomicOrdering,
92299285 ) !Builder.Value {
92309286 const o = self.dg.object;
9231 const mod = o.module;
9287 const pt = o.pt;
9288 const mod = pt.zcu;
92329289 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
92339290 const ptr_ty = self.typeOf(bin_op.lhs);
92349291 const operand_ty = ptr_ty.childType(mod);
9235 if (!operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .none;
9292 if (!operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .none;
92369293 const ptr = try self.resolveInst(bin_op.lhs);
92379294 var element = try self.resolveInst(bin_op.rhs);
92389295 const llvm_abi_ty = try o.getAtomicAbiType(operand_ty, false);
......@@ -9252,12 +9309,13 @@ pub const FuncGen = struct {
92529309
92539310 fn airMemset(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
92549311 const o = self.dg.object;
9255 const mod = o.module;
9312 const pt = o.pt;
9313 const mod = pt.zcu;
92569314 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
92579315 const dest_slice = try self.resolveInst(bin_op.lhs);
92589316 const ptr_ty = self.typeOf(bin_op.lhs);
92599317 const elem_ty = self.typeOf(bin_op.rhs);
9260 const dest_ptr_align = ptr_ty.ptrAlignment(mod).toLlvm();
9318 const dest_ptr_align = ptr_ty.ptrAlignment(pt).toLlvm();
92619319 const dest_ptr = try self.sliceOrArrayPtr(dest_slice, ptr_ty);
92629320 const access_kind: Builder.MemoryAccessKind =
92639321 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
......@@ -9270,7 +9328,7 @@ pub const FuncGen = struct {
92709328 ptr_ty.isSlice(mod) and
92719329 std.Target.wasm.featureSetHas(o.target.cpu.features, .bulk_memory);
92729330
9273 if (try self.air.value(bin_op.rhs, mod)) |elem_val| {
9331 if (try self.air.value(bin_op.rhs, pt)) |elem_val| {
92749332 if (elem_val.isUndefDeep(mod)) {
92759333 // Even if safety is disabled, we still emit a memset to undefined since it conveys
92769334 // extra information to LLVM. However, safety makes the difference between using
......@@ -9296,7 +9354,7 @@ pub const FuncGen = struct {
92969354 // repeating byte pattern, for example, `@as(u64, 0)` has a
92979355 // repeating byte pattern of 0 bytes. In such case, the memset
92989356 // intrinsic can be used.
9299 if (try elem_val.hasRepeatedByteRepr(elem_ty, mod)) |byte_val| {
9357 if (try elem_val.hasRepeatedByteRepr(elem_ty, pt)) |byte_val| {
93009358 const fill_byte = try o.builder.intValue(.i8, byte_val);
93019359 const len = try self.sliceOrArrayLenInBytes(dest_slice, ptr_ty);
93029360 if (intrinsic_len0_traps) {
......@@ -9309,7 +9367,7 @@ pub const FuncGen = struct {
93099367 }
93109368
93119369 const value = try self.resolveInst(bin_op.rhs);
9312 const elem_abi_size = elem_ty.abiSize(mod);
9370 const elem_abi_size = elem_ty.abiSize(pt);
93139371
93149372 if (elem_abi_size == 1) {
93159373 // In this case we can take advantage of LLVM's intrinsic.
......@@ -9361,9 +9419,9 @@ pub const FuncGen = struct {
93619419 _ = try self.wip.brCond(end, body_block, end_block);
93629420
93639421 self.wip.cursor = .{ .block = body_block };
9364 const elem_abi_align = elem_ty.abiAlignment(mod);
9422 const elem_abi_align = elem_ty.abiAlignment(pt);
93659423 const it_ptr_align = InternPool.Alignment.fromLlvm(dest_ptr_align).min(elem_abi_align).toLlvm();
9366 if (isByRef(elem_ty, mod)) {
9424 if (isByRef(elem_ty, pt)) {
93679425 _ = try self.wip.callMemCpy(
93689426 it_ptr.toValue(),
93699427 it_ptr_align,
......@@ -9405,7 +9463,8 @@ pub const FuncGen = struct {
94059463
94069464 fn airMemcpy(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94079465 const o = self.dg.object;
9408 const mod = o.module;
9466 const pt = o.pt;
9467 const mod = pt.zcu;
94099468 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
94109469 const dest_slice = try self.resolveInst(bin_op.lhs);
94119470 const dest_ptr_ty = self.typeOf(bin_op.lhs);
......@@ -9434,9 +9493,9 @@ pub const FuncGen = struct {
94349493 self.wip.cursor = .{ .block = memcpy_block };
94359494 _ = try self.wip.callMemCpy(
94369495 dest_ptr,
9437 dest_ptr_ty.ptrAlignment(mod).toLlvm(),
9496 dest_ptr_ty.ptrAlignment(pt).toLlvm(),
94389497 src_ptr,
9439 src_ptr_ty.ptrAlignment(mod).toLlvm(),
9498 src_ptr_ty.ptrAlignment(pt).toLlvm(),
94409499 len,
94419500 access_kind,
94429501 );
......@@ -9447,9 +9506,9 @@ pub const FuncGen = struct {
94479506
94489507 _ = try self.wip.callMemCpy(
94499508 dest_ptr,
9450 dest_ptr_ty.ptrAlignment(mod).toLlvm(),
9509 dest_ptr_ty.ptrAlignment(pt).toLlvm(),
94519510 src_ptr,
9452 src_ptr_ty.ptrAlignment(mod).toLlvm(),
9511 src_ptr_ty.ptrAlignment(pt).toLlvm(),
94539512 len,
94549513 access_kind,
94559514 );
......@@ -9458,10 +9517,11 @@ pub const FuncGen = struct {
94589517
94599518 fn airSetUnionTag(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94609519 const o = self.dg.object;
9461 const mod = o.module;
9520 const pt = o.pt;
9521 const mod = pt.zcu;
94629522 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
94639523 const un_ty = self.typeOf(bin_op.lhs).childType(mod);
9464 const layout = un_ty.unionGetLayout(mod);
9524 const layout = un_ty.unionGetLayout(pt);
94659525 if (layout.tag_size == 0) return .none;
94669526 const union_ptr = try self.resolveInst(bin_op.lhs);
94679527 const new_tag = try self.resolveInst(bin_op.rhs);
......@@ -9479,13 +9539,13 @@ pub const FuncGen = struct {
94799539
94809540 fn airGetUnionTag(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94819541 const o = self.dg.object;
9482 const mod = o.module;
9542 const pt = o.pt;
94839543 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
94849544 const un_ty = self.typeOf(ty_op.operand);
9485 const layout = un_ty.unionGetLayout(mod);
9545 const layout = un_ty.unionGetLayout(pt);
94869546 if (layout.tag_size == 0) return .none;
94879547 const union_handle = try self.resolveInst(ty_op.operand);
9488 if (isByRef(un_ty, mod)) {
9548 if (isByRef(un_ty, pt)) {
94899549 const llvm_un_ty = try o.lowerType(un_ty);
94909550 if (layout.payload_size == 0)
94919551 return self.wip.load(.normal, llvm_un_ty, union_handle, .default, "");
......@@ -9554,7 +9614,7 @@ pub const FuncGen = struct {
95549614
95559615 fn airByteSwap(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
95569616 const o = self.dg.object;
9557 const mod = o.module;
9617 const mod = o.pt.zcu;
95589618 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
95599619 const operand_ty = self.typeOf(ty_op.operand);
95609620 var bits = operand_ty.intInfo(mod).bits;
......@@ -9588,7 +9648,7 @@ pub const FuncGen = struct {
95889648
95899649 fn airErrorSetHasValue(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
95909650 const o = self.dg.object;
9591 const mod = o.module;
9651 const mod = o.pt.zcu;
95929652 const ip = &mod.intern_pool;
95939653 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
95949654 const operand = try self.resolveInst(ty_op.operand);
......@@ -9638,7 +9698,8 @@ pub const FuncGen = struct {
96389698
96399699 fn getIsNamedEnumValueFunction(self: *FuncGen, enum_ty: Type) !Builder.Function.Index {
96409700 const o = self.dg.object;
9641 const zcu = o.module;
9701 const pt = o.pt;
9702 const zcu = pt.zcu;
96429703 const enum_type = zcu.intern_pool.loadEnumType(enum_ty.toIntern());
96439704
96449705 // TODO: detect when the type changes and re-emit this function.
......@@ -9678,7 +9739,7 @@ pub const FuncGen = struct {
96789739
96799740 for (0..enum_type.names.len) |field_index| {
96809741 const this_tag_int_value = try o.lowerValue(
9681 (try zcu.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
9742 (try pt.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
96829743 );
96839744 try wip_switch.addCase(this_tag_int_value, named_block, &wip);
96849745 }
......@@ -9745,7 +9806,8 @@ pub const FuncGen = struct {
97459806
97469807 fn airShuffle(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
97479808 const o = self.dg.object;
9748 const mod = o.module;
9809 const pt = o.pt;
9810 const mod = pt.zcu;
97499811 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
97509812 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
97519813 const a = try self.resolveInst(extra.a);
......@@ -9763,11 +9825,11 @@ pub const FuncGen = struct {
97639825 defer self.gpa.free(values);
97649826
97659827 for (values, 0..) |*val, i| {
9766 const elem = try mask.elemValue(mod, i);
9828 const elem = try mask.elemValue(pt, i);
97679829 if (elem.isUndef(mod)) {
97689830 val.* = try o.builder.undefConst(.i32);
97699831 } else {
9770 const int = elem.toSignedInt(mod);
9832 const int = elem.toSignedInt(pt);
97719833 const unsigned: u32 = @intCast(if (int >= 0) int else ~int + a_len);
97729834 val.* = try o.builder.intConst(.i32, unsigned);
97739835 }
......@@ -9854,7 +9916,7 @@ pub const FuncGen = struct {
98549916
98559917 fn airReduce(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
98569918 const o = self.dg.object;
9857 const mod = o.module;
9919 const mod = o.pt.zcu;
98589920 const target = mod.getTarget();
98599921
98609922 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
......@@ -9964,7 +10026,8 @@ pub const FuncGen = struct {
996410026
996510027 fn airAggregateInit(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
996610028 const o = self.dg.object;
9967 const mod = o.module;
10029 const pt = o.pt;
10030 const mod = pt.zcu;
996810031 const ip = &mod.intern_pool;
996910032 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
997010033 const result_ty = self.typeOfIndex(inst);
......@@ -9986,16 +10049,16 @@ pub const FuncGen = struct {
998610049 if (mod.typeToPackedStruct(result_ty)) |struct_type| {
998710050 const backing_int_ty = struct_type.backingIntType(ip).*;
998810051 assert(backing_int_ty != .none);
9989 const big_bits = Type.fromInterned(backing_int_ty).bitSize(mod);
10052 const big_bits = Type.fromInterned(backing_int_ty).bitSize(pt);
999010053 const int_ty = try o.builder.intType(@intCast(big_bits));
999110054 comptime assert(Type.packed_struct_layout_version == 2);
999210055 var running_int = try o.builder.intValue(int_ty, 0);
999310056 var running_bits: u16 = 0;
999410057 for (elements, struct_type.field_types.get(ip)) |elem, field_ty| {
9995 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
10058 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
999610059
999710060 const non_int_val = try self.resolveInst(elem);
9998 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(mod));
10061 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(pt));
999910062 const small_int_ty = try o.builder.intType(ty_bit_size);
1000010063 const small_int_val = if (Type.fromInterned(field_ty).isPtrAtRuntime(mod))
1000110064 try self.wip.cast(.ptrtoint, non_int_val, small_int_ty, "")
......@@ -10013,23 +10076,23 @@ pub const FuncGen = struct {
1001310076
1001410077 assert(result_ty.containerLayout(mod) != .@"packed");
1001510078
10016 if (isByRef(result_ty, mod)) {
10079 if (isByRef(result_ty, pt)) {
1001710080 // TODO in debug builds init to undef so that the padding will be 0xaa
1001810081 // even if we fully populate the fields.
10019 const alignment = result_ty.abiAlignment(mod).toLlvm();
10082 const alignment = result_ty.abiAlignment(pt).toLlvm();
1002010083 const alloca_inst = try self.buildAllocaWorkaround(result_ty, alignment);
1002110084
1002210085 for (elements, 0..) |elem, i| {
10023 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
10086 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
1002410087
1002510088 const llvm_elem = try self.resolveInst(elem);
1002610089 const llvm_i = o.llvmFieldIndex(result_ty, i).?;
1002710090 const field_ptr =
1002810091 try self.wip.gepStruct(llvm_result_ty, alloca_inst, llvm_i, "");
10029 const field_ptr_ty = try mod.ptrType(.{
10092 const field_ptr_ty = try pt.ptrType(.{
1003010093 .child = self.typeOf(elem).toIntern(),
1003110094 .flags = .{
10032 .alignment = result_ty.structFieldAlign(i, mod),
10095 .alignment = result_ty.structFieldAlign(i, pt),
1003310096 },
1003410097 });
1003510098 try self.store(field_ptr, field_ptr_ty, llvm_elem, .none);
......@@ -10039,7 +10102,7 @@ pub const FuncGen = struct {
1003910102 } else {
1004010103 var result = try o.builder.poisonValue(llvm_result_ty);
1004110104 for (elements, 0..) |elem, i| {
10042 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
10105 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
1004310106
1004410107 const llvm_elem = try self.resolveInst(elem);
1004510108 const llvm_i = o.llvmFieldIndex(result_ty, i).?;
......@@ -10049,15 +10112,15 @@ pub const FuncGen = struct {
1004910112 }
1005010113 },
1005110114 .Array => {
10052 assert(isByRef(result_ty, mod));
10115 assert(isByRef(result_ty, pt));
1005310116
1005410117 const llvm_usize = try o.lowerType(Type.usize);
1005510118 const usize_zero = try o.builder.intValue(llvm_usize, 0);
10056 const alignment = result_ty.abiAlignment(mod).toLlvm();
10119 const alignment = result_ty.abiAlignment(pt).toLlvm();
1005710120 const alloca_inst = try self.buildAllocaWorkaround(result_ty, alignment);
1005810121
1005910122 const array_info = result_ty.arrayInfo(mod);
10060 const elem_ptr_ty = try mod.ptrType(.{
10123 const elem_ptr_ty = try pt.ptrType(.{
1006110124 .child = array_info.elem_type.toIntern(),
1006210125 });
1006310126
......@@ -10084,21 +10147,22 @@ pub const FuncGen = struct {
1008410147
1008510148 fn airUnionInit(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1008610149 const o = self.dg.object;
10087 const mod = o.module;
10150 const pt = o.pt;
10151 const mod = pt.zcu;
1008810152 const ip = &mod.intern_pool;
1008910153 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1009010154 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
1009110155 const union_ty = self.typeOfIndex(inst);
1009210156 const union_llvm_ty = try o.lowerType(union_ty);
10093 const layout = union_ty.unionGetLayout(mod);
10157 const layout = union_ty.unionGetLayout(pt);
1009410158 const union_obj = mod.typeToUnion(union_ty).?;
1009510159
1009610160 if (union_obj.getLayout(ip) == .@"packed") {
10097 const big_bits = union_ty.bitSize(mod);
10161 const big_bits = union_ty.bitSize(pt);
1009810162 const int_llvm_ty = try o.builder.intType(@intCast(big_bits));
1009910163 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
1010010164 const non_int_val = try self.resolveInst(extra.init);
10101 const small_int_ty = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
10165 const small_int_ty = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
1010210166 const small_int_val = if (field_ty.isPtrAtRuntime(mod))
1010310167 try self.wip.cast(.ptrtoint, non_int_val, small_int_ty, "")
1010410168 else
......@@ -10110,19 +10174,19 @@ pub const FuncGen = struct {
1011010174 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
1011110175 const union_field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
1011210176 const enum_field_index = tag_ty.enumFieldIndex(union_field_name, mod).?;
10113 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
10114 break :blk try tag_val.intFromEnum(tag_ty, mod);
10177 const tag_val = try pt.enumValueFieldIndex(tag_ty, enum_field_index);
10178 break :blk try tag_val.intFromEnum(tag_ty, pt);
1011510179 };
1011610180 if (layout.payload_size == 0) {
1011710181 if (layout.tag_size == 0) {
1011810182 return .none;
1011910183 }
10120 assert(!isByRef(union_ty, mod));
10184 assert(!isByRef(union_ty, pt));
1012110185 var big_int_space: Value.BigIntSpace = undefined;
10122 const tag_big_int = tag_int_val.toBigInt(&big_int_space, mod);
10186 const tag_big_int = tag_int_val.toBigInt(&big_int_space, pt);
1012310187 return try o.builder.bigIntValue(union_llvm_ty, tag_big_int);
1012410188 }
10125 assert(isByRef(union_ty, mod));
10189 assert(isByRef(union_ty, pt));
1012610190 // The llvm type of the alloca will be the named LLVM union type, and will not
1012710191 // necessarily match the format that we need, depending on which tag is active.
1012810192 // We must construct the correct unnamed struct type here, in order to then set
......@@ -10132,14 +10196,14 @@ pub const FuncGen = struct {
1013210196 const llvm_payload = try self.resolveInst(extra.init);
1013310197 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
1013410198 const field_llvm_ty = try o.lowerType(field_ty);
10135 const field_size = field_ty.abiSize(mod);
10136 const field_align = mod.unionFieldNormalAlignment(union_obj, extra.field_index);
10199 const field_size = field_ty.abiSize(pt);
10200 const field_align = pt.unionFieldNormalAlignment(union_obj, extra.field_index);
1013710201 const llvm_usize = try o.lowerType(Type.usize);
1013810202 const usize_zero = try o.builder.intValue(llvm_usize, 0);
1013910203
1014010204 const llvm_union_ty = t: {
1014110205 const payload_ty = p: {
10142 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
10206 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1014310207 const padding_len = layout.payload_size;
1014410208 break :p try o.builder.arrayType(padding_len, .i8);
1014510209 }
......@@ -10169,7 +10233,7 @@ pub const FuncGen = struct {
1016910233
1017010234 // Now we follow the layout as expressed above with GEP instructions to set the
1017110235 // tag and the payload.
10172 const field_ptr_ty = try mod.ptrType(.{
10236 const field_ptr_ty = try pt.ptrType(.{
1017310237 .child = field_ty.toIntern(),
1017410238 .flags = .{ .alignment = field_align },
1017510239 });
......@@ -10195,9 +10259,9 @@ pub const FuncGen = struct {
1019510259 const field_ptr = try self.wip.gep(.inbounds, llvm_union_ty, result_ptr, &indices, "");
1019610260 const tag_ty = try o.lowerType(Type.fromInterned(union_obj.enum_tag_ty));
1019710261 var big_int_space: Value.BigIntSpace = undefined;
10198 const tag_big_int = tag_int_val.toBigInt(&big_int_space, mod);
10262 const tag_big_int = tag_int_val.toBigInt(&big_int_space, pt);
1019910263 const llvm_tag = try o.builder.bigIntValue(tag_ty, tag_big_int);
10200 const tag_alignment = Type.fromInterned(union_obj.enum_tag_ty).abiAlignment(mod).toLlvm();
10264 const tag_alignment = Type.fromInterned(union_obj.enum_tag_ty).abiAlignment(pt).toLlvm();
1020110265 _ = try self.wip.store(.normal, llvm_tag, field_ptr, tag_alignment);
1020210266 }
1020310267
......@@ -10223,7 +10287,7 @@ pub const FuncGen = struct {
1022310287 // by the target.
1022410288 // To work around this, don't emit llvm.prefetch in this case.
1022510289 // See https://bugs.llvm.org/show_bug.cgi?id=21037
10226 const mod = o.module;
10290 const mod = o.pt.zcu;
1022710291 const target = mod.getTarget();
1022810292 switch (prefetch.cache) {
1022910293 .instruction => switch (target.cpu.arch) {
......@@ -10279,7 +10343,7 @@ pub const FuncGen = struct {
1027910343
1028010344 fn airWorkItemId(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1028110345 const o = self.dg.object;
10282 const target = o.module.getTarget();
10346 const target = o.pt.zcu.getTarget();
1028310347 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1028410348
1028510349 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10289,7 +10353,7 @@ pub const FuncGen = struct {
1028910353
1029010354 fn airWorkGroupSize(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1029110355 const o = self.dg.object;
10292 const target = o.module.getTarget();
10356 const target = o.pt.zcu.getTarget();
1029310357 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1029410358
1029510359 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10312,7 +10376,7 @@ pub const FuncGen = struct {
1031210376
1031310377 fn airWorkGroupId(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1031410378 const o = self.dg.object;
10315 const target = o.module.getTarget();
10379 const target = o.pt.zcu.getTarget();
1031610380 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1031710381
1031810382 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10322,7 +10386,7 @@ pub const FuncGen = struct {
1032210386
1032310387 fn getErrorNameTable(self: *FuncGen) Allocator.Error!Builder.Variable.Index {
1032410388 const o = self.dg.object;
10325 const mod = o.module;
10389 const pt = o.pt;
1032610390
1032710391 const table = o.error_name_table;
1032810392 if (table != .none) return table;
......@@ -10334,7 +10398,7 @@ pub const FuncGen = struct {
1033410398 variable_index.setMutability(.constant, &o.builder);
1033510399 variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
1033610400 variable_index.setAlignment(
10337 Type.slice_const_u8_sentinel_0.abiAlignment(mod).toLlvm(),
10401 Type.slice_const_u8_sentinel_0.abiAlignment(pt).toLlvm(),
1033810402 &o.builder,
1033910403 );
1034010404
......@@ -10372,15 +10436,16 @@ pub const FuncGen = struct {
1037210436 can_elide_load: bool,
1037310437 ) !Builder.Value {
1037410438 const o = fg.dg.object;
10375 const mod = o.module;
10439 const pt = o.pt;
10440 const mod = pt.zcu;
1037610441 const payload_ty = opt_ty.optionalChild(mod);
1037710442
10378 if (isByRef(opt_ty, mod)) {
10443 if (isByRef(opt_ty, pt)) {
1037910444 // We have a pointer and we need to return a pointer to the first field.
1038010445 const payload_ptr = try fg.wip.gepStruct(opt_llvm_ty, opt_handle, 0, "");
1038110446
10382 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
10383 if (isByRef(payload_ty, mod)) {
10447 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
10448 if (isByRef(payload_ty, pt)) {
1038410449 if (can_elide_load)
1038510450 return payload_ptr;
1038610451
......@@ -10389,7 +10454,7 @@ pub const FuncGen = struct {
1038910454 return fg.loadTruncate(.normal, payload_ty, payload_ptr, payload_alignment);
1039010455 }
1039110456
10392 assert(!isByRef(payload_ty, mod));
10457 assert(!isByRef(payload_ty, pt));
1039310458 return fg.wip.extractValue(opt_handle, &.{0}, "");
1039410459 }
1039510460
......@@ -10400,12 +10465,12 @@ pub const FuncGen = struct {
1040010465 non_null_bit: Builder.Value,
1040110466 ) !Builder.Value {
1040210467 const o = self.dg.object;
10468 const pt = o.pt;
1040310469 const optional_llvm_ty = try o.lowerType(optional_ty);
1040410470 const non_null_field = try self.wip.cast(.zext, non_null_bit, .i8, "");
10405 const mod = o.module;
1040610471
10407 if (isByRef(optional_ty, mod)) {
10408 const payload_alignment = optional_ty.abiAlignment(mod).toLlvm();
10472 if (isByRef(optional_ty, pt)) {
10473 const payload_alignment = optional_ty.abiAlignment(pt).toLlvm();
1040910474 const alloca_inst = try self.buildAllocaWorkaround(optional_ty, payload_alignment);
1041010475
1041110476 {
......@@ -10432,7 +10497,8 @@ pub const FuncGen = struct {
1043210497 field_index: u32,
1043310498 ) !Builder.Value {
1043410499 const o = self.dg.object;
10435 const mod = o.module;
10500 const pt = o.pt;
10501 const mod = pt.zcu;
1043610502 const struct_ty = struct_ptr_ty.childType(mod);
1043710503 switch (struct_ty.zigTypeTag(mod)) {
1043810504 .Struct => switch (struct_ty.containerLayout(mod)) {
......@@ -10452,7 +10518,7 @@ pub const FuncGen = struct {
1045210518
1045310519 // We have a pointer to a packed struct field that happens to be byte-aligned.
1045410520 // Offset our operand pointer by the correct number of bytes.
10455 const byte_offset = @divExact(mod.structPackedFieldBitOffset(struct_type, field_index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
10521 const byte_offset = @divExact(pt.structPackedFieldBitOffset(struct_type, field_index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
1045610522 if (byte_offset == 0) return struct_ptr;
1045710523 const usize_ty = try o.lowerType(Type.usize);
1045810524 const llvm_index = try o.builder.intValue(usize_ty, byte_offset);
......@@ -10470,14 +10536,14 @@ pub const FuncGen = struct {
1047010536 // the struct.
1047110537 const llvm_index = try o.builder.intValue(
1047210538 try o.lowerType(Type.usize),
10473 @intFromBool(struct_ty.hasRuntimeBitsIgnoreComptime(mod)),
10539 @intFromBool(struct_ty.hasRuntimeBitsIgnoreComptime(pt)),
1047410540 );
1047510541 return self.wip.gep(.inbounds, struct_llvm_ty, struct_ptr, &.{llvm_index}, "");
1047610542 }
1047710543 },
1047810544 },
1047910545 .Union => {
10480 const layout = struct_ty.unionGetLayout(mod);
10546 const layout = struct_ty.unionGetLayout(pt);
1048110547 if (layout.payload_size == 0 or struct_ty.containerLayout(mod) == .@"packed") return struct_ptr;
1048210548 const payload_index = @intFromBool(layout.tag_align.compare(.gte, layout.payload_align));
1048310549 const union_llvm_ty = try o.lowerType(struct_ty);
......@@ -10500,9 +10566,10 @@ pub const FuncGen = struct {
1050010566 // => so load the byte aligned value and trunc the unwanted bits.
1050110567
1050210568 const o = fg.dg.object;
10503 const mod = o.module;
10569 const pt = o.pt;
10570 const mod = pt.zcu;
1050410571 const payload_llvm_ty = try o.lowerType(payload_ty);
10505 const abi_size = payload_ty.abiSize(mod);
10572 const abi_size = payload_ty.abiSize(pt);
1050610573
1050710574 // llvm bug workarounds:
1050810575 const workaround_explicit_mask = o.target.cpu.arch == .powerpc and abi_size >= 4;
......@@ -10522,7 +10589,7 @@ pub const FuncGen = struct {
1052210589 const shifted = if (payload_llvm_ty != load_llvm_ty and o.target.cpu.arch.endian() == .big)
1052310590 try fg.wip.bin(.lshr, loaded, try o.builder.intValue(
1052410591 load_llvm_ty,
10525 (payload_ty.abiSize(mod) - (std.math.divCeil(u64, payload_ty.bitSize(mod), 8) catch unreachable)) * 8,
10592 (payload_ty.abiSize(pt) - (std.math.divCeil(u64, payload_ty.bitSize(pt), 8) catch unreachable)) * 8,
1052610593 ), "")
1052710594 else
1052810595 loaded;
......@@ -10546,11 +10613,11 @@ pub const FuncGen = struct {
1054610613 access_kind: Builder.MemoryAccessKind,
1054710614 ) !Builder.Value {
1054810615 const o = fg.dg.object;
10549 const mod = o.module;
10616 const pt = o.pt;
1055010617 //const pointee_llvm_ty = try o.lowerType(pointee_type);
10551 const result_align = InternPool.Alignment.fromLlvm(ptr_alignment).max(pointee_type.abiAlignment(mod)).toLlvm();
10618 const result_align = InternPool.Alignment.fromLlvm(ptr_alignment).max(pointee_type.abiAlignment(pt)).toLlvm();
1055210619 const result_ptr = try fg.buildAllocaWorkaround(pointee_type, result_align);
10553 const size_bytes = pointee_type.abiSize(mod);
10620 const size_bytes = pointee_type.abiSize(pt);
1055410621 _ = try fg.wip.callMemCpy(
1055510622 result_ptr,
1055610623 result_align,
......@@ -10567,15 +10634,16 @@ pub const FuncGen = struct {
1056710634 /// For isByRef=false types, it creates a load instruction and returns it.
1056810635 fn load(self: *FuncGen, ptr: Builder.Value, ptr_ty: Type) !Builder.Value {
1056910636 const o = self.dg.object;
10570 const mod = o.module;
10637 const pt = o.pt;
10638 const mod = pt.zcu;
1057110639 const info = ptr_ty.ptrInfo(mod);
1057210640 const elem_ty = Type.fromInterned(info.child);
10573 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
10641 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
1057410642
1057510643 const ptr_alignment = (if (info.flags.alignment != .none)
1057610644 @as(InternPool.Alignment, info.flags.alignment)
1057710645 else
10578 elem_ty.abiAlignment(mod)).toLlvm();
10646 elem_ty.abiAlignment(pt)).toLlvm();
1057910647
1058010648 const access_kind: Builder.MemoryAccessKind =
1058110649 if (info.flags.is_volatile) .@"volatile" else .normal;
......@@ -10591,7 +10659,7 @@ pub const FuncGen = struct {
1059110659 }
1059210660
1059310661 if (info.packed_offset.host_size == 0) {
10594 if (isByRef(elem_ty, mod)) {
10662 if (isByRef(elem_ty, pt)) {
1059510663 return self.loadByRef(ptr, elem_ty, ptr_alignment, access_kind);
1059610664 }
1059710665 return self.loadTruncate(access_kind, elem_ty, ptr, ptr_alignment);
......@@ -10601,13 +10669,13 @@ pub const FuncGen = struct {
1060110669 const containing_int =
1060210670 try self.wip.load(access_kind, containing_int_ty, ptr, ptr_alignment, "");
1060310671
10604 const elem_bits = ptr_ty.childType(mod).bitSize(mod);
10672 const elem_bits = ptr_ty.childType(mod).bitSize(pt);
1060510673 const shift_amt = try o.builder.intValue(containing_int_ty, info.packed_offset.bit_offset);
1060610674 const shifted_value = try self.wip.bin(.lshr, containing_int, shift_amt, "");
1060710675 const elem_llvm_ty = try o.lowerType(elem_ty);
1060810676
10609 if (isByRef(elem_ty, mod)) {
10610 const result_align = elem_ty.abiAlignment(mod).toLlvm();
10677 if (isByRef(elem_ty, pt)) {
10678 const result_align = elem_ty.abiAlignment(pt).toLlvm();
1061110679 const result_ptr = try self.buildAllocaWorkaround(elem_ty, result_align);
1061210680
1061310681 const same_size_int = try o.builder.intType(@intCast(elem_bits));
......@@ -10639,13 +10707,14 @@ pub const FuncGen = struct {
1063910707 ordering: Builder.AtomicOrdering,
1064010708 ) !void {
1064110709 const o = self.dg.object;
10642 const mod = o.module;
10710 const pt = o.pt;
10711 const mod = pt.zcu;
1064310712 const info = ptr_ty.ptrInfo(mod);
1064410713 const elem_ty = Type.fromInterned(info.child);
10645 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
10714 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
1064610715 return;
1064710716 }
10648 const ptr_alignment = ptr_ty.ptrAlignment(mod).toLlvm();
10717 const ptr_alignment = ptr_ty.ptrAlignment(pt).toLlvm();
1064910718 const access_kind: Builder.MemoryAccessKind =
1065010719 if (info.flags.is_volatile) .@"volatile" else .normal;
1065110720
......@@ -10669,7 +10738,7 @@ pub const FuncGen = struct {
1066910738 assert(ordering == .none);
1067010739 const containing_int =
1067110740 try self.wip.load(access_kind, containing_int_ty, ptr, ptr_alignment, "");
10672 const elem_bits = ptr_ty.childType(mod).bitSize(mod);
10741 const elem_bits = ptr_ty.childType(mod).bitSize(pt);
1067310742 const shift_amt = try o.builder.intConst(containing_int_ty, info.packed_offset.bit_offset);
1067410743 // Convert to equally-sized integer type in order to perform the bit
1067510744 // operations on the value to store
......@@ -10704,7 +10773,7 @@ pub const FuncGen = struct {
1070410773 _ = try self.wip.store(access_kind, ored_value, ptr, ptr_alignment);
1070510774 return;
1070610775 }
10707 if (!isByRef(elem_ty, mod)) {
10776 if (!isByRef(elem_ty, pt)) {
1070810777 _ = try self.wip.storeAtomic(
1070910778 access_kind,
1071010779 elem,
......@@ -10720,8 +10789,8 @@ pub const FuncGen = struct {
1072010789 ptr,
1072110790 ptr_alignment,
1072210791 elem,
10723 elem_ty.abiAlignment(mod).toLlvm(),
10724 try o.builder.intValue(try o.lowerType(Type.usize), elem_ty.abiSize(mod)),
10792 elem_ty.abiAlignment(pt).toLlvm(),
10793 try o.builder.intValue(try o.lowerType(Type.usize), elem_ty.abiSize(pt)),
1072510794 access_kind,
1072610795 );
1072710796 }
......@@ -10747,12 +10816,13 @@ pub const FuncGen = struct {
1074710816 a5: Builder.Value,
1074810817 ) Allocator.Error!Builder.Value {
1074910818 const o = fg.dg.object;
10750 const mod = o.module;
10819 const pt = o.pt;
10820 const mod = pt.zcu;
1075110821 const target = mod.getTarget();
1075210822 if (!target_util.hasValgrindSupport(target)) return default_value;
1075310823
1075410824 const llvm_usize = try o.lowerType(Type.usize);
10755 const usize_alignment = Type.usize.abiAlignment(mod).toLlvm();
10825 const usize_alignment = Type.usize.abiAlignment(pt).toLlvm();
1075610826
1075710827 const array_llvm_ty = try o.builder.arrayType(6, llvm_usize);
1075810828 const array_ptr = if (fg.valgrind_client_request_array == .none) a: {
......@@ -10813,13 +10883,13 @@ pub const FuncGen = struct {
1081310883
1081410884 fn typeOf(fg: *FuncGen, inst: Air.Inst.Ref) Type {
1081510885 const o = fg.dg.object;
10816 const mod = o.module;
10886 const mod = o.pt.zcu;
1081710887 return fg.air.typeOf(inst, &mod.intern_pool);
1081810888 }
1081910889
1082010890 fn typeOfIndex(fg: *FuncGen, inst: Air.Inst.Index) Type {
1082110891 const o = fg.dg.object;
10822 const mod = o.module;
10892 const mod = o.pt.zcu;
1082310893 return fg.air.typeOfIndex(inst, &mod.intern_pool);
1082410894 }
1082510895};
......@@ -10990,12 +11060,12 @@ fn toLlvmGlobalAddressSpace(wanted_address_space: std.builtin.AddressSpace, targ
1099011060 };
1099111061}
1099211062
10993fn returnTypeByRef(zcu: *Zcu, target: std.Target, ty: Type) bool {
10994 if (isByRef(ty, zcu)) {
11063fn returnTypeByRef(pt: Zcu.PerThread, target: std.Target, ty: Type) bool {
11064 if (isByRef(ty, pt)) {
1099511065 return true;
1099611066 } else if (target.cpu.arch.isX86() and
1099711067 !std.Target.x86.featureSetHas(target.cpu.features, .evex512) and
10998 ty.totalVectorBits(zcu) >= 512)
11068 ty.totalVectorBits(pt) >= 512)
1099911069 {
1100011070 // As of LLVM 18, passing a vector byval with fastcc that is 512 bits or more returns
1100111071 // "512-bit vector arguments require 'evex512' for AVX512"
......@@ -11005,38 +11075,38 @@ fn returnTypeByRef(zcu: *Zcu, target: std.Target, ty: Type) bool {
1100511075 }
1100611076}
1100711077
11008fn firstParamSRet(fn_info: InternPool.Key.FuncType, zcu: *Zcu, target: std.Target) bool {
11078fn firstParamSRet(fn_info: InternPool.Key.FuncType, pt: Zcu.PerThread, target: std.Target) bool {
1100911079 const return_type = Type.fromInterned(fn_info.return_type);
11010 if (!return_type.hasRuntimeBitsIgnoreComptime(zcu)) return false;
11080 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) return false;
1101111081
1101211082 return switch (fn_info.cc) {
11013 .Unspecified, .Inline => returnTypeByRef(zcu, target, return_type),
11083 .Unspecified, .Inline => returnTypeByRef(pt, target, return_type),
1101411084 .C => switch (target.cpu.arch) {
1101511085 .mips, .mipsel => false,
11016 .x86 => isByRef(return_type, zcu),
11086 .x86 => isByRef(return_type, pt),
1101711087 .x86_64 => switch (target.os.tag) {
11018 .windows => x86_64_abi.classifyWindows(return_type, zcu) == .memory,
11019 else => firstParamSRetSystemV(return_type, zcu, target),
11088 .windows => x86_64_abi.classifyWindows(return_type, pt) == .memory,
11089 else => firstParamSRetSystemV(return_type, pt, target),
1102011090 },
11021 .wasm32 => wasm_c_abi.classifyType(return_type, zcu)[0] == .indirect,
11022 .aarch64, .aarch64_be => aarch64_c_abi.classifyType(return_type, zcu) == .memory,
11023 .arm, .armeb => switch (arm_c_abi.classifyType(return_type, zcu, .ret)) {
11091 .wasm32 => wasm_c_abi.classifyType(return_type, pt)[0] == .indirect,
11092 .aarch64, .aarch64_be => aarch64_c_abi.classifyType(return_type, pt) == .memory,
11093 .arm, .armeb => switch (arm_c_abi.classifyType(return_type, pt, .ret)) {
1102411094 .memory, .i64_array => true,
1102511095 .i32_array => |size| size != 1,
1102611096 .byval => false,
1102711097 },
11028 .riscv32, .riscv64 => riscv_c_abi.classifyType(return_type, zcu) == .memory,
11098 .riscv32, .riscv64 => riscv_c_abi.classifyType(return_type, pt) == .memory,
1102911099 else => false, // TODO investigate C ABI for other architectures
1103011100 },
11031 .SysV => firstParamSRetSystemV(return_type, zcu, target),
11032 .Win64 => x86_64_abi.classifyWindows(return_type, zcu) == .memory,
11033 .Stdcall => !isScalar(zcu, return_type),
11101 .SysV => firstParamSRetSystemV(return_type, pt, target),
11102 .Win64 => x86_64_abi.classifyWindows(return_type, pt) == .memory,
11103 .Stdcall => !isScalar(pt.zcu, return_type),
1103411104 else => false,
1103511105 };
1103611106}
1103711107
11038fn firstParamSRetSystemV(ty: Type, zcu: *Zcu, target: std.Target) bool {
11039 const class = x86_64_abi.classifySystemV(ty, zcu, target, .ret);
11108fn firstParamSRetSystemV(ty: Type, pt: Zcu.PerThread, target: std.Target) bool {
11109 const class = x86_64_abi.classifySystemV(ty, pt, target, .ret);
1104011110 if (class[0] == .memory) return true;
1104111111 if (class[0] == .x87 and class[2] != .none) return true;
1104211112 return false;
......@@ -11046,9 +11116,10 @@ fn firstParamSRetSystemV(ty: Type, zcu: *Zcu, target: std.Target) bool {
1104611116/// completely differently in the function prototype to honor the C ABI, and then
1104711117/// be effectively bitcasted to the actual return type.
1104811118fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11049 const mod = o.module;
11119 const pt = o.pt;
11120 const mod = pt.zcu;
1105011121 const return_type = Type.fromInterned(fn_info.return_type);
11051 if (!return_type.hasRuntimeBitsIgnoreComptime(mod)) {
11122 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) {
1105211123 // If the return type is an error set or an error union, then we make this
1105311124 // anyerror return type instead, so that it can be coerced into a function
1105411125 // pointer type which has anyerror as the return type.
......@@ -11058,12 +11129,12 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1105811129 switch (fn_info.cc) {
1105911130 .Unspecified,
1106011131 .Inline,
11061 => return if (returnTypeByRef(mod, target, return_type)) .void else o.lowerType(return_type),
11132 => return if (returnTypeByRef(pt, target, return_type)) .void else o.lowerType(return_type),
1106211133
1106311134 .C => {
1106411135 switch (target.cpu.arch) {
1106511136 .mips, .mipsel => return o.lowerType(return_type),
11066 .x86 => return if (isByRef(return_type, mod)) .void else o.lowerType(return_type),
11137 .x86 => return if (isByRef(return_type, pt)) .void else o.lowerType(return_type),
1106711138 .x86_64 => switch (target.os.tag) {
1106811139 .windows => return lowerWin64FnRetTy(o, fn_info),
1106911140 else => return lowerSystemVFnRetTy(o, fn_info),
......@@ -11072,36 +11143,36 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1107211143 if (isScalar(mod, return_type)) {
1107311144 return o.lowerType(return_type);
1107411145 }
11075 const classes = wasm_c_abi.classifyType(return_type, mod);
11146 const classes = wasm_c_abi.classifyType(return_type, pt);
1107611147 if (classes[0] == .indirect or classes[0] == .none) {
1107711148 return .void;
1107811149 }
1107911150
1108011151 assert(classes[0] == .direct and classes[1] == .none);
11081 const scalar_type = wasm_c_abi.scalarType(return_type, mod);
11082 return o.builder.intType(@intCast(scalar_type.abiSize(mod) * 8));
11152 const scalar_type = wasm_c_abi.scalarType(return_type, pt);
11153 return o.builder.intType(@intCast(scalar_type.abiSize(pt) * 8));
1108311154 },
1108411155 .aarch64, .aarch64_be => {
11085 switch (aarch64_c_abi.classifyType(return_type, mod)) {
11156 switch (aarch64_c_abi.classifyType(return_type, pt)) {
1108611157 .memory => return .void,
1108711158 .float_array => return o.lowerType(return_type),
1108811159 .byval => return o.lowerType(return_type),
11089 .integer => return o.builder.intType(@intCast(return_type.bitSize(mod))),
11160 .integer => return o.builder.intType(@intCast(return_type.bitSize(pt))),
1109011161 .double_integer => return o.builder.arrayType(2, .i64),
1109111162 }
1109211163 },
1109311164 .arm, .armeb => {
11094 switch (arm_c_abi.classifyType(return_type, mod, .ret)) {
11165 switch (arm_c_abi.classifyType(return_type, pt, .ret)) {
1109511166 .memory, .i64_array => return .void,
1109611167 .i32_array => |len| return if (len == 1) .i32 else .void,
1109711168 .byval => return o.lowerType(return_type),
1109811169 }
1109911170 },
1110011171 .riscv32, .riscv64 => {
11101 switch (riscv_c_abi.classifyType(return_type, mod)) {
11172 switch (riscv_c_abi.classifyType(return_type, pt)) {
1110211173 .memory => return .void,
1110311174 .integer => {
11104 return o.builder.intType(@intCast(return_type.bitSize(mod)));
11175 return o.builder.intType(@intCast(return_type.bitSize(pt)));
1110511176 },
1110611177 .double_integer => {
1110711178 return o.builder.structType(.normal, &.{ .i64, .i64 });
......@@ -11112,7 +11183,7 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1111211183 var types: [8]Builder.Type = undefined;
1111311184 for (0..return_type.structFieldCount(mod)) |field_index| {
1111411185 const field_ty = return_type.structFieldType(field_index, mod);
11115 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
11186 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
1111611187 types[types_len] = try o.lowerType(field_ty);
1111711188 types_len += 1;
1111811189 }
......@@ -11132,14 +11203,14 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1113211203}
1113311204
1113411205fn lowerWin64FnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11135 const mod = o.module;
11206 const pt = o.pt;
1113611207 const return_type = Type.fromInterned(fn_info.return_type);
11137 switch (x86_64_abi.classifyWindows(return_type, mod)) {
11208 switch (x86_64_abi.classifyWindows(return_type, pt)) {
1113811209 .integer => {
11139 if (isScalar(mod, return_type)) {
11210 if (isScalar(pt.zcu, return_type)) {
1114011211 return o.lowerType(return_type);
1114111212 } else {
11142 return o.builder.intType(@intCast(return_type.abiSize(mod) * 8));
11213 return o.builder.intType(@intCast(return_type.abiSize(pt) * 8));
1114311214 }
1114411215 },
1114511216 .win_i128 => return o.builder.vectorType(.normal, 2, .i64),
......@@ -11150,14 +11221,15 @@ fn lowerWin64FnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Err
1115011221}
1115111222
1115211223fn lowerSystemVFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11153 const mod = o.module;
11224 const pt = o.pt;
11225 const mod = pt.zcu;
1115411226 const ip = &mod.intern_pool;
1115511227 const return_type = Type.fromInterned(fn_info.return_type);
1115611228 if (isScalar(mod, return_type)) {
1115711229 return o.lowerType(return_type);
1115811230 }
1115911231 const target = mod.getTarget();
11160 const classes = x86_64_abi.classifySystemV(return_type, mod, target, .ret);
11232 const classes = x86_64_abi.classifySystemV(return_type, pt, target, .ret);
1116111233 if (classes[0] == .memory) return .void;
1116211234 var types_index: u32 = 0;
1116311235 var types_buffer: [8]Builder.Type = undefined;
......@@ -11249,8 +11321,7 @@ const ParamTypeIterator = struct {
1124911321
1125011322 pub fn next(it: *ParamTypeIterator) Allocator.Error!?Lowering {
1125111323 if (it.zig_index >= it.fn_info.param_types.len) return null;
11252 const zcu = it.object.module;
11253 const ip = &zcu.intern_pool;
11324 const ip = &it.object.pt.zcu.intern_pool;
1125411325 const ty = it.fn_info.param_types.get(ip)[it.zig_index];
1125511326 it.byval_attr = false;
1125611327 return nextInner(it, Type.fromInterned(ty));
......@@ -11258,8 +11329,7 @@ const ParamTypeIterator = struct {
1125811329
1125911330 /// `airCall` uses this instead of `next` so that it can take into account variadic functions.
1126011331 pub fn nextCall(it: *ParamTypeIterator, fg: *FuncGen, args: []const Air.Inst.Ref) Allocator.Error!?Lowering {
11261 const zcu = it.object.module;
11262 const ip = &zcu.intern_pool;
11332 const ip = &it.object.pt.zcu.intern_pool;
1126311333 if (it.zig_index >= it.fn_info.param_types.len) {
1126411334 if (it.zig_index >= args.len) {
1126511335 return null;
......@@ -11272,10 +11342,11 @@ const ParamTypeIterator = struct {
1127211342 }
1127311343
1127411344 fn nextInner(it: *ParamTypeIterator, ty: Type) Allocator.Error!?Lowering {
11275 const zcu = it.object.module;
11345 const pt = it.object.pt;
11346 const zcu = pt.zcu;
1127611347 const target = zcu.getTarget();
1127711348
11278 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
11349 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
1127911350 it.zig_index += 1;
1128011351 return .no_bits;
1128111352 }
......@@ -11288,11 +11359,11 @@ const ParamTypeIterator = struct {
1128811359 {
1128911360 it.llvm_index += 1;
1129011361 return .slice;
11291 } else if (isByRef(ty, zcu)) {
11362 } else if (isByRef(ty, pt)) {
1129211363 return .byref;
1129311364 } else if (target.cpu.arch.isX86() and
1129411365 !std.Target.x86.featureSetHas(target.cpu.features, .evex512) and
11295 ty.totalVectorBits(zcu) >= 512)
11366 ty.totalVectorBits(pt) >= 512)
1129611367 {
1129711368 // As of LLVM 18, passing a vector byval with fastcc that is 512 bits or more returns
1129811369 // "512-bit vector arguments require 'evex512' for AVX512"
......@@ -11320,7 +11391,7 @@ const ParamTypeIterator = struct {
1132011391 if (isScalar(zcu, ty)) {
1132111392 return .byval;
1132211393 }
11323 const classes = wasm_c_abi.classifyType(ty, zcu);
11394 const classes = wasm_c_abi.classifyType(ty, pt);
1132411395 if (classes[0] == .indirect) {
1132511396 return .byref;
1132611397 }
......@@ -11329,7 +11400,7 @@ const ParamTypeIterator = struct {
1132911400 .aarch64, .aarch64_be => {
1133011401 it.zig_index += 1;
1133111402 it.llvm_index += 1;
11332 switch (aarch64_c_abi.classifyType(ty, zcu)) {
11403 switch (aarch64_c_abi.classifyType(ty, pt)) {
1133311404 .memory => return .byref_mut,
1133411405 .float_array => |len| return Lowering{ .float_array = len },
1133511406 .byval => return .byval,
......@@ -11344,7 +11415,7 @@ const ParamTypeIterator = struct {
1134411415 .arm, .armeb => {
1134511416 it.zig_index += 1;
1134611417 it.llvm_index += 1;
11347 switch (arm_c_abi.classifyType(ty, zcu, .arg)) {
11418 switch (arm_c_abi.classifyType(ty, pt, .arg)) {
1134811419 .memory => {
1134911420 it.byval_attr = true;
1135011421 return .byref;
......@@ -11359,7 +11430,7 @@ const ParamTypeIterator = struct {
1135911430 it.llvm_index += 1;
1136011431 if (ty.toIntern() == .f16_type and
1136111432 !std.Target.riscv.featureSetHas(target.cpu.features, .d)) return .as_u16;
11362 switch (riscv_c_abi.classifyType(ty, zcu)) {
11433 switch (riscv_c_abi.classifyType(ty, pt)) {
1136311434 .memory => return .byref_mut,
1136411435 .byval => return .byval,
1136511436 .integer => return .abi_sized_int,
......@@ -11368,7 +11439,7 @@ const ParamTypeIterator = struct {
1136811439 it.types_len = 0;
1136911440 for (0..ty.structFieldCount(zcu)) |field_index| {
1137011441 const field_ty = ty.structFieldType(field_index, zcu);
11371 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
11442 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
1137211443 it.types_buffer[it.types_len] = try it.object.lowerType(field_ty);
1137311444 it.types_len += 1;
1137411445 }
......@@ -11406,10 +11477,10 @@ const ParamTypeIterator = struct {
1140611477 }
1140711478
1140811479 fn nextWin64(it: *ParamTypeIterator, ty: Type) ?Lowering {
11409 const zcu = it.object.module;
11410 switch (x86_64_abi.classifyWindows(ty, zcu)) {
11480 const pt = it.object.pt;
11481 switch (x86_64_abi.classifyWindows(ty, pt)) {
1141111482 .integer => {
11412 if (isScalar(zcu, ty)) {
11483 if (isScalar(pt.zcu, ty)) {
1141311484 it.zig_index += 1;
1141411485 it.llvm_index += 1;
1141511486 return .byval;
......@@ -11439,17 +11510,17 @@ const ParamTypeIterator = struct {
1143911510 }
1144011511
1144111512 fn nextSystemV(it: *ParamTypeIterator, ty: Type) Allocator.Error!?Lowering {
11442 const zcu = it.object.module;
11443 const ip = &zcu.intern_pool;
11444 const target = zcu.getTarget();
11445 const classes = x86_64_abi.classifySystemV(ty, zcu, target, .arg);
11513 const pt = it.object.pt;
11514 const ip = &pt.zcu.intern_pool;
11515 const target = pt.zcu.getTarget();
11516 const classes = x86_64_abi.classifySystemV(ty, pt, target, .arg);
1144611517 if (classes[0] == .memory) {
1144711518 it.zig_index += 1;
1144811519 it.llvm_index += 1;
1144911520 it.byval_attr = true;
1145011521 return .byref;
1145111522 }
11452 if (isScalar(zcu, ty)) {
11523 if (isScalar(pt.zcu, ty)) {
1145311524 it.zig_index += 1;
1145411525 it.llvm_index += 1;
1145511526 return .byval;
......@@ -11550,7 +11621,7 @@ fn iterateParamTypes(object: *Object, fn_info: InternPool.Key.FuncType) ParamTyp
1155011621
1155111622fn ccAbiPromoteInt(
1155211623 cc: std.builtin.CallingConvention,
11553 mod: *Module,
11624 mod: *Zcu,
1155411625 ty: Type,
1155511626) ?std.builtin.Signedness {
1155611627 const target = mod.getTarget();
......@@ -11598,13 +11669,13 @@ fn ccAbiPromoteInt(
1159811669
1159911670/// This is the one source of truth for whether a type is passed around as an LLVM pointer,
1160011671/// or as an LLVM value.
11601fn isByRef(ty: Type, mod: *Module) bool {
11672fn isByRef(ty: Type, pt: Zcu.PerThread) bool {
1160211673 // For tuples and structs, if there are more than this many non-void
1160311674 // fields, then we make it byref, otherwise byval.
1160411675 const max_fields_byval = 0;
11605 const ip = &mod.intern_pool;
11676 const ip = &pt.zcu.intern_pool;
1160611677
11607 switch (ty.zigTypeTag(mod)) {
11678 switch (ty.zigTypeTag(pt.zcu)) {
1160811679 .Type,
1160911680 .ComptimeInt,
1161011681 .ComptimeFloat,
......@@ -11627,17 +11698,17 @@ fn isByRef(ty: Type, mod: *Module) bool {
1162711698 .AnyFrame,
1162811699 => return false,
1162911700
11630 .Array, .Frame => return ty.hasRuntimeBits(mod),
11701 .Array, .Frame => return ty.hasRuntimeBits(pt),
1163111702 .Struct => {
1163211703 const struct_type = switch (ip.indexToKey(ty.toIntern())) {
1163311704 .anon_struct_type => |tuple| {
1163411705 var count: usize = 0;
1163511706 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, field_val| {
11636 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
11707 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
1163711708
1163811709 count += 1;
1163911710 if (count > max_fields_byval) return true;
11640 if (isByRef(Type.fromInterned(field_ty), mod)) return true;
11711 if (isByRef(Type.fromInterned(field_ty), pt)) return true;
1164111712 }
1164211713 return false;
1164311714 },
......@@ -11655,27 +11726,27 @@ fn isByRef(ty: Type, mod: *Module) bool {
1165511726 count += 1;
1165611727 if (count > max_fields_byval) return true;
1165711728 const field_ty = Type.fromInterned(field_types[field_index]);
11658 if (isByRef(field_ty, mod)) return true;
11729 if (isByRef(field_ty, pt)) return true;
1165911730 }
1166011731 return false;
1166111732 },
11662 .Union => switch (ty.containerLayout(mod)) {
11733 .Union => switch (ty.containerLayout(pt.zcu)) {
1166311734 .@"packed" => return false,
11664 else => return ty.hasRuntimeBits(mod),
11735 else => return ty.hasRuntimeBits(pt),
1166511736 },
1166611737 .ErrorUnion => {
11667 const payload_ty = ty.errorUnionPayload(mod);
11668 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
11738 const payload_ty = ty.errorUnionPayload(pt.zcu);
11739 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1166911740 return false;
1167011741 }
1167111742 return true;
1167211743 },
1167311744 .Optional => {
11674 const payload_ty = ty.optionalChild(mod);
11675 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
11745 const payload_ty = ty.optionalChild(pt.zcu);
11746 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1167611747 return false;
1167711748 }
11678 if (ty.optionalReprIsPayload(mod)) {
11749 if (ty.optionalReprIsPayload(pt.zcu)) {
1167911750 return false;
1168011751 }
1168111752 return true;
......@@ -11683,7 +11754,7 @@ fn isByRef(ty: Type, mod: *Module) bool {
1168311754 }
1168411755}
1168511756
11686fn isScalar(mod: *Module, ty: Type) bool {
11757fn isScalar(mod: *Zcu, ty: Type) bool {
1168711758 return switch (ty.zigTypeTag(mod)) {
1168811759 .Void,
1168911760 .Bool,
......@@ -11774,7 +11845,7 @@ const lt_errors_fn_name = "__zig_lt_errors_len";
1177411845/// Without this workaround, LLVM crashes with "unknown codeview register H1"
1177511846/// https://github.com/llvm/llvm-project/issues/56484
1177611847fn needDbgVarWorkaround(o: *Object) bool {
11777 const target = o.module.getTarget();
11848 const target = o.pt.zcu.getTarget();
1177811849 if (target.os.tag == .windows and target.cpu.arch == .aarch64) {
1177911850 return true;
1178011851 }
......@@ -11817,14 +11888,14 @@ fn buildAllocaInner(
1181711888 return wip.conv(.unneeded, alloca, .ptr, "");
1181811889}
1181911890
11820fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) !u1 {
11821 const err_int_ty = try mod.errorIntType();
11822 return @intFromBool(err_int_ty.abiAlignment(mod).compare(.gt, payload_ty.abiAlignment(mod)));
11891fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) !u1 {
11892 const err_int_ty = try pt.errorIntType();
11893 return @intFromBool(err_int_ty.abiAlignment(pt).compare(.gt, payload_ty.abiAlignment(pt)));
1182311894}
1182411895
11825fn errUnionErrorOffset(payload_ty: Type, mod: *Module) !u1 {
11826 const err_int_ty = try mod.errorIntType();
11827 return @intFromBool(err_int_ty.abiAlignment(mod).compare(.lte, payload_ty.abiAlignment(mod)));
11896fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) !u1 {
11897 const err_int_ty = try pt.errorIntType();
11898 return @intFromBool(err_int_ty.abiAlignment(pt).compare(.lte, payload_ty.abiAlignment(pt)));
1182811899}
1182911900
1183011901/// Returns true for asm constraint (e.g. "=*m", "=r") if it accepts a memory location
src/codegen/spirv.zig+239-211
......@@ -6,9 +6,7 @@ const assert = std.debug.assert;
66const Signedness = std.builtin.Signedness;
77
88const Zcu = @import("../Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
11const Decl = Module.Decl;
9const Decl = Zcu.Decl;
1210const Type = @import("../Type.zig");
1311const Value = @import("../Value.zig");
1412const Air = @import("../Air.zig");
......@@ -188,12 +186,13 @@ pub const Object = struct {
188186
189187 fn genDecl(
190188 self: *Object,
191 zcu: *Zcu,
189 pt: Zcu.PerThread,
192190 decl_index: InternPool.DeclIndex,
193191 air: Air,
194192 liveness: Liveness,
195193 ) !void {
196 const gpa = self.gpa;
194 const zcu = pt.zcu;
195 const gpa = zcu.gpa;
197196 const decl = zcu.declPtr(decl_index);
198197 const namespace = zcu.namespacePtr(decl.src_namespace);
199198 const structured_cfg = namespace.fileScope(zcu).mod.structured_cfg;
......@@ -201,7 +200,7 @@ pub const Object = struct {
201200 var decl_gen = DeclGen{
202201 .gpa = gpa,
203202 .object = self,
204 .module = zcu,
203 .pt = pt,
205204 .spv = &self.spv,
206205 .decl_index = decl_index,
207206 .air = air,
......@@ -235,34 +234,34 @@ pub const Object = struct {
235234
236235 pub fn updateFunc(
237236 self: *Object,
238 mod: *Module,
237 pt: Zcu.PerThread,
239238 func_index: InternPool.Index,
240239 air: Air,
241240 liveness: Liveness,
242241 ) !void {
243 const decl_index = mod.funcInfo(func_index).owner_decl;
242 const decl_index = pt.zcu.funcInfo(func_index).owner_decl;
244243 // TODO: Separate types for generating decls and functions?
245 try self.genDecl(mod, decl_index, air, liveness);
244 try self.genDecl(pt, decl_index, air, liveness);
246245 }
247246
248247 pub fn updateDecl(
249248 self: *Object,
250 mod: *Module,
249 pt: Zcu.PerThread,
251250 decl_index: InternPool.DeclIndex,
252251 ) !void {
253 try self.genDecl(mod, decl_index, undefined, undefined);
252 try self.genDecl(pt, decl_index, undefined, undefined);
254253 }
255254
256255 /// Fetch or allocate a result id for decl index. This function also marks the decl as alive.
257256 /// Note: Function does not actually generate the decl, it just allocates an index.
258 pub fn resolveDecl(self: *Object, mod: *Module, decl_index: InternPool.DeclIndex) !SpvModule.Decl.Index {
259 const decl = mod.declPtr(decl_index);
257 pub fn resolveDecl(self: *Object, zcu: *Zcu, decl_index: InternPool.DeclIndex) !SpvModule.Decl.Index {
258 const decl = zcu.declPtr(decl_index);
260259 assert(decl.has_tv); // TODO: Do we need to handle a situation where this is false?
261260
262261 const entry = try self.decl_link.getOrPut(self.gpa, decl_index);
263262 if (!entry.found_existing) {
264263 // TODO: Extern fn?
265 const kind: SpvModule.Decl.Kind = if (decl.val.isFuncBody(mod))
264 const kind: SpvModule.Decl.Kind = if (decl.val.isFuncBody(zcu))
266265 .func
267266 else switch (decl.@"addrspace") {
268267 .generic => .invocation_global,
......@@ -285,7 +284,7 @@ const DeclGen = struct {
285284 object: *Object,
286285
287286 /// The Zig module that we are generating decls for.
288 module: *Module,
287 pt: Zcu.PerThread,
289288
290289 /// The SPIR-V module that instructions should be emitted into.
291290 /// This is the same as `self.object.spv`, repeated here for brevity.
......@@ -333,7 +332,7 @@ const DeclGen = struct {
333332
334333 /// If `gen` returned `Error.CodegenFail`, this contains an explanatory message.
335334 /// Memory is owned by `module.gpa`.
336 error_msg: ?*Module.ErrorMsg = null,
335 error_msg: ?*Zcu.ErrorMsg = null,
337336
338337 /// Possible errors the `genDecl` function may return.
339338 const Error = error{ CodegenFail, OutOfMemory };
......@@ -410,15 +409,15 @@ const DeclGen = struct {
410409
411410 /// Return the target which we are currently compiling for.
412411 pub fn getTarget(self: *DeclGen) std.Target {
413 return self.module.getTarget();
412 return self.pt.zcu.getTarget();
414413 }
415414
416415 pub fn fail(self: *DeclGen, comptime format: []const u8, args: anytype) Error {
417416 @setCold(true);
418 const mod = self.module;
419 const src_loc = self.module.declPtr(self.decl_index).navSrcLoc(mod);
417 const zcu = self.pt.zcu;
418 const src_loc = zcu.declPtr(self.decl_index).navSrcLoc(zcu);
420419 assert(self.error_msg == null);
421 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args);
420 self.error_msg = try Zcu.ErrorMsg.create(zcu.gpa, src_loc, format, args);
422421 return error.CodegenFail;
423422 }
424423
......@@ -439,8 +438,9 @@ const DeclGen = struct {
439438
440439 /// Fetch the result-id for a previously generated instruction or constant.
441440 fn resolve(self: *DeclGen, inst: Air.Inst.Ref) !IdRef {
442 const mod = self.module;
443 if (try self.air.value(inst, mod)) |val| {
441 const pt = self.pt;
442 const mod = pt.zcu;
443 if (try self.air.value(inst, pt)) |val| {
444444 const ty = self.typeOf(inst);
445445 if (ty.zigTypeTag(mod) == .Fn) {
446446 const fn_decl_index = switch (mod.intern_pool.indexToKey(val.ip_index)) {
......@@ -462,7 +462,7 @@ const DeclGen = struct {
462462 fn resolveAnonDecl(self: *DeclGen, val: InternPool.Index) !IdRef {
463463 // TODO: This cannot be a function at this point, but it should probably be handled anyway.
464464
465 const mod = self.module;
465 const mod = self.pt.zcu;
466466 const ty = Type.fromInterned(mod.intern_pool.typeOf(val));
467467 const decl_ptr_ty_id = try self.ptrType(ty, .Generic);
468468
......@@ -642,7 +642,7 @@ const DeclGen = struct {
642642
643643 /// Checks whether the type can be directly translated to SPIR-V vectors
644644 fn isSpvVector(self: *DeclGen, ty: Type) bool {
645 const mod = self.module;
645 const mod = self.pt.zcu;
646646 const target = self.getTarget();
647647 if (ty.zigTypeTag(mod) != .Vector) return false;
648648
......@@ -668,7 +668,7 @@ const DeclGen = struct {
668668 }
669669
670670 fn arithmeticTypeInfo(self: *DeclGen, ty: Type) ArithmeticTypeInfo {
671 const mod = self.module;
671 const mod = self.pt.zcu;
672672 const target = self.getTarget();
673673 var scalar_ty = ty.scalarType(mod);
674674 if (scalar_ty.zigTypeTag(mod) == .Enum) {
......@@ -744,7 +744,7 @@ const DeclGen = struct {
744744 /// the value to an unsigned int first for Kernels.
745745 fn constInt(self: *DeclGen, ty: Type, value: anytype, repr: Repr) !IdRef {
746746 // TODO: Cache?
747 const mod = self.module;
747 const mod = self.pt.zcu;
748748 const scalar_ty = ty.scalarType(mod);
749749 const int_info = scalar_ty.intInfo(mod);
750750 // Use backing bits so that negatives are sign extended
......@@ -824,7 +824,7 @@ const DeclGen = struct {
824824 /// Construct a vector at runtime.
825825 /// ty must be an vector type.
826826 fn constructVector(self: *DeclGen, ty: Type, constituents: []const IdRef) !IdRef {
827 const mod = self.module;
827 const mod = self.pt.zcu;
828828 assert(ty.vectorLen(mod) == constituents.len);
829829
830830 // Note: older versions of the Khronos SPRIV-LLVM translator crash on this instruction
......@@ -848,7 +848,7 @@ const DeclGen = struct {
848848 /// Construct a vector at runtime with all lanes set to the same value.
849849 /// ty must be an vector type.
850850 fn constructVectorSplat(self: *DeclGen, ty: Type, constituent: IdRef) !IdRef {
851 const mod = self.module;
851 const mod = self.pt.zcu;
852852 const n = ty.vectorLen(mod);
853853
854854 const constituents = try self.gpa.alloc(IdRef, n);
......@@ -886,12 +886,13 @@ const DeclGen = struct {
886886 return id;
887887 }
888888
889 const mod = self.module;
889 const pt = self.pt;
890 const mod = pt.zcu;
890891 const target = self.getTarget();
891892 const result_ty_id = try self.resolveType(ty, repr);
892893 const ip = &mod.intern_pool;
893894
894 log.debug("lowering constant: ty = {}, val = {}", .{ ty.fmt(mod), val.fmtValue(mod, null) });
895 log.debug("lowering constant: ty = {}, val = {}", .{ ty.fmt(pt), val.fmtValue(pt, null) });
895896 if (val.isUndefDeep(mod)) {
896897 return self.spv.constUndef(result_ty_id);
897898 }
......@@ -940,16 +941,16 @@ const DeclGen = struct {
940941 },
941942 .int => {
942943 if (ty.isSignedInt(mod)) {
943 break :cache try self.constInt(ty, val.toSignedInt(mod), repr);
944 break :cache try self.constInt(ty, val.toSignedInt(pt), repr);
944945 } else {
945 break :cache try self.constInt(ty, val.toUnsignedInt(mod), repr);
946 break :cache try self.constInt(ty, val.toUnsignedInt(pt), repr);
946947 }
947948 },
948949 .float => {
949950 const lit: spec.LiteralContextDependentNumber = switch (ty.floatBits(target)) {
950 16 => .{ .uint32 = @as(u16, @bitCast(val.toFloat(f16, mod))) },
951 32 => .{ .float32 = val.toFloat(f32, mod) },
952 64 => .{ .float64 = val.toFloat(f64, mod) },
951 16 => .{ .uint32 = @as(u16, @bitCast(val.toFloat(f16, pt))) },
952 32 => .{ .float32 = val.toFloat(f32, pt) },
953 64 => .{ .float64 = val.toFloat(f64, pt) },
953954 80, 128 => unreachable, // TODO
954955 else => unreachable,
955956 };
......@@ -968,17 +969,17 @@ const DeclGen = struct {
968969 .error_union => |error_union| {
969970 // TODO: Error unions may be constructed with constant instructions if the payload type
970971 // allows it. For now, just generate it here regardless.
971 const err_int_ty = try mod.errorIntType();
972 const err_int_ty = try pt.errorIntType();
972973 const err_ty = switch (error_union.val) {
973974 .err_name => ty.errorUnionSet(mod),
974975 .payload => err_int_ty,
975976 };
976977 const err_val = switch (error_union.val) {
977 .err_name => |err_name| Value.fromInterned((try mod.intern(.{ .err = .{
978 .err_name => |err_name| Value.fromInterned(try pt.intern(.{ .err = .{
978979 .ty = ty.errorUnionSet(mod).toIntern(),
979980 .name = err_name,
980 } }))),
981 .payload => try mod.intValue(err_int_ty, 0),
981 } })),
982 .payload => try pt.intValue(err_int_ty, 0),
982983 };
983984 const payload_ty = ty.errorUnionPayload(mod);
984985 const eu_layout = self.errorUnionLayout(payload_ty);
......@@ -988,7 +989,7 @@ const DeclGen = struct {
988989 }
989990
990991 const payload_val = Value.fromInterned(switch (error_union.val) {
991 .err_name => try mod.intern(.{ .undef = payload_ty.toIntern() }),
992 .err_name => try pt.intern(.{ .undef = payload_ty.toIntern() }),
992993 .payload => |payload| payload,
993994 });
994995
......@@ -1007,7 +1008,7 @@ const DeclGen = struct {
10071008 return try self.constructStruct(ty, &types, &constituents);
10081009 },
10091010 .enum_tag => {
1010 const int_val = try val.intFromEnum(ty, mod);
1011 const int_val = try val.intFromEnum(ty, pt);
10111012 const int_ty = ty.intTagType(mod);
10121013 break :cache try self.constant(int_ty, int_val, repr);
10131014 },
......@@ -1026,7 +1027,7 @@ const DeclGen = struct {
10261027 const payload_ty = ty.optionalChild(mod);
10271028 const maybe_payload_val = val.optionalValue(mod);
10281029
1029 if (!payload_ty.hasRuntimeBits(mod)) {
1030 if (!payload_ty.hasRuntimeBits(pt)) {
10301031 break :cache try self.constBool(maybe_payload_val != null, .indirect);
10311032 } else if (ty.optionalReprIsPayload(mod)) {
10321033 // Optional representation is a nullable pointer or slice.
......@@ -1104,13 +1105,13 @@ const DeclGen = struct {
11041105 var it = struct_type.iterateRuntimeOrder(ip);
11051106 while (it.next()) |field_index| {
11061107 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1107 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1108 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
11081109 // This is a zero-bit field - we only needed it for the alignment.
11091110 continue;
11101111 }
11111112
11121113 // TODO: Padding?
1113 const field_val = try val.fieldValue(mod, field_index);
1114 const field_val = try val.fieldValue(pt, field_index);
11141115 const field_id = try self.constant(field_ty, field_val, .indirect);
11151116
11161117 try types.append(field_ty);
......@@ -1126,7 +1127,7 @@ const DeclGen = struct {
11261127 const active_field = ty.unionTagFieldIndex(Value.fromInterned(un.tag), mod).?;
11271128 const union_obj = mod.typeToUnion(ty).?;
11281129 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[active_field]);
1129 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(mod))
1130 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(pt))
11301131 try self.constant(field_ty, Value.fromInterned(un.val), .direct)
11311132 else
11321133 null;
......@@ -1144,10 +1145,10 @@ const DeclGen = struct {
11441145 fn constantPtr(self: *DeclGen, ptr_val: Value) Error!IdRef {
11451146 // TODO: Caching??
11461147
1147 const zcu = self.module;
1148 const pt = self.pt;
11481149
1149 if (ptr_val.isUndef(zcu)) {
1150 const result_ty = ptr_val.typeOf(zcu);
1150 if (ptr_val.isUndef(pt.zcu)) {
1151 const result_ty = ptr_val.typeOf(pt.zcu);
11511152 const result_ty_id = try self.resolveType(result_ty, .direct);
11521153 return self.spv.constUndef(result_ty_id);
11531154 }
......@@ -1155,12 +1156,13 @@ const DeclGen = struct {
11551156 var arena = std.heap.ArenaAllocator.init(self.gpa);
11561157 defer arena.deinit();
11571158
1158 const derivation = try ptr_val.pointerDerivation(arena.allocator(), zcu);
1159 const derivation = try ptr_val.pointerDerivation(arena.allocator(), pt);
11591160 return self.derivePtr(derivation);
11601161 }
11611162
11621163 fn derivePtr(self: *DeclGen, derivation: Value.PointerDeriveStep) Error!IdRef {
1163 const zcu = self.module;
1164 const pt = self.pt;
1165 const zcu = pt.zcu;
11641166 switch (derivation) {
11651167 .comptime_alloc_ptr, .comptime_field_ptr => unreachable,
11661168 .int => |int| {
......@@ -1172,12 +1174,12 @@ const DeclGen = struct {
11721174 try self.func.body.emit(self.spv.gpa, .OpConvertUToPtr, .{
11731175 .id_result_type = result_ty_id,
11741176 .id_result = result_ptr_id,
1175 .integer_value = try self.constant(Type.usize, try zcu.intValue(Type.usize, int.addr), .direct),
1177 .integer_value = try self.constant(Type.usize, try pt.intValue(Type.usize, int.addr), .direct),
11761178 });
11771179 return result_ptr_id;
11781180 },
11791181 .decl_ptr => |decl| {
1180 const result_ptr_ty = try zcu.declPtr(decl).declPtrType(zcu);
1182 const result_ptr_ty = try zcu.declPtr(decl).declPtrType(pt);
11811183 return self.constantDeclRef(result_ptr_ty, decl);
11821184 },
11831185 .anon_decl_ptr => |ad| {
......@@ -1188,18 +1190,18 @@ const DeclGen = struct {
11881190 .opt_payload_ptr => @panic("TODO"),
11891191 .field_ptr => |field| {
11901192 const parent_ptr_id = try self.derivePtr(field.parent.*);
1191 const parent_ptr_ty = try field.parent.ptrType(zcu);
1193 const parent_ptr_ty = try field.parent.ptrType(pt);
11921194 return self.structFieldPtr(field.result_ptr_ty, parent_ptr_ty, parent_ptr_id, field.field_idx);
11931195 },
11941196 .elem_ptr => |elem| {
11951197 const parent_ptr_id = try self.derivePtr(elem.parent.*);
1196 const parent_ptr_ty = try elem.parent.ptrType(zcu);
1198 const parent_ptr_ty = try elem.parent.ptrType(pt);
11971199 const index_id = try self.constInt(Type.usize, elem.elem_idx, .direct);
11981200 return self.ptrElemPtr(parent_ptr_ty, parent_ptr_id, index_id);
11991201 },
12001202 .offset_and_cast => |oac| {
12011203 const parent_ptr_id = try self.derivePtr(oac.parent.*);
1202 const parent_ptr_ty = try oac.parent.ptrType(zcu);
1204 const parent_ptr_ty = try oac.parent.ptrType(pt);
12031205 disallow: {
12041206 if (oac.byte_offset != 0) break :disallow;
12051207 // Allow changing the pointer type child only to restructure arrays.
......@@ -1218,8 +1220,8 @@ const DeclGen = struct {
12181220 return result_ptr_id;
12191221 }
12201222 return self.fail("Cannot perform pointer cast: '{}' to '{}'", .{
1221 parent_ptr_ty.fmt(zcu),
1222 oac.new_ptr_ty.fmt(zcu),
1223 parent_ptr_ty.fmt(pt),
1224 oac.new_ptr_ty.fmt(pt),
12231225 });
12241226 },
12251227 }
......@@ -1232,7 +1234,8 @@ const DeclGen = struct {
12321234 ) !IdRef {
12331235 // TODO: Merge this function with constantDeclRef.
12341236
1235 const mod = self.module;
1237 const pt = self.pt;
1238 const mod = pt.zcu;
12361239 const ip = &mod.intern_pool;
12371240 const ty_id = try self.resolveType(ty, .direct);
12381241 const decl_val = anon_decl.val;
......@@ -1247,7 +1250,7 @@ const DeclGen = struct {
12471250 }
12481251
12491252 // const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
1250 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
1253 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
12511254 // Pointer to nothing - return undefoined
12521255 return self.spv.constUndef(ty_id);
12531256 }
......@@ -1276,7 +1279,8 @@ const DeclGen = struct {
12761279 }
12771280
12781281 fn constantDeclRef(self: *DeclGen, ty: Type, decl_index: InternPool.DeclIndex) !IdRef {
1279 const mod = self.module;
1282 const pt = self.pt;
1283 const mod = pt.zcu;
12801284 const ty_id = try self.resolveType(ty, .direct);
12811285 const decl = mod.declPtr(decl_index);
12821286
......@@ -1290,7 +1294,7 @@ const DeclGen = struct {
12901294 else => {},
12911295 }
12921296
1293 if (!decl.typeOf(mod).isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
1297 if (!decl.typeOf(mod).isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
12941298 // Pointer to nothing - return undefined.
12951299 return self.spv.constUndef(ty_id);
12961300 }
......@@ -1331,7 +1335,7 @@ const DeclGen = struct {
13311335 fn resolveTypeName(self: *DeclGen, ty: Type) ![]const u8 {
13321336 var name = std.ArrayList(u8).init(self.gpa);
13331337 defer name.deinit();
1334 try ty.print(name.writer(), self.module);
1338 try ty.print(name.writer(), self.pt);
13351339 return try name.toOwnedSlice();
13361340 }
13371341
......@@ -1424,14 +1428,14 @@ const DeclGen = struct {
14241428 }
14251429
14261430 fn zigScalarOrVectorTypeLike(self: *DeclGen, new_ty: Type, base_ty: Type) !Type {
1427 const mod = self.module;
1428 const new_scalar_ty = new_ty.scalarType(mod);
1429 if (!base_ty.isVector(mod)) {
1431 const pt = self.pt;
1432 const new_scalar_ty = new_ty.scalarType(pt.zcu);
1433 if (!base_ty.isVector(pt.zcu)) {
14301434 return new_scalar_ty;
14311435 }
14321436
1433 return try mod.vectorType(.{
1434 .len = base_ty.vectorLen(mod),
1437 return try pt.vectorType(.{
1438 .len = base_ty.vectorLen(pt.zcu),
14351439 .child = new_scalar_ty.toIntern(),
14361440 });
14371441 }
......@@ -1455,7 +1459,7 @@ const DeclGen = struct {
14551459 /// }
14561460 /// If any of the fields' size is 0, it will be omitted.
14571461 fn resolveUnionType(self: *DeclGen, ty: Type) !IdRef {
1458 const mod = self.module;
1462 const mod = self.pt.zcu;
14591463 const ip = &mod.intern_pool;
14601464 const union_obj = mod.typeToUnion(ty).?;
14611465
......@@ -1506,12 +1510,12 @@ const DeclGen = struct {
15061510 }
15071511
15081512 fn resolveFnReturnType(self: *DeclGen, ret_ty: Type) !IdRef {
1509 const mod = self.module;
1510 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1513 const pt = self.pt;
1514 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
15111515 // If the return type is an error set or an error union, then we make this
15121516 // anyerror return type instead, so that it can be coerced into a function
15131517 // pointer type which has anyerror as the return type.
1514 if (ret_ty.isError(mod)) {
1518 if (ret_ty.isError(pt.zcu)) {
15151519 return self.resolveType(Type.anyerror, .direct);
15161520 } else {
15171521 return self.resolveType(Type.void, .direct);
......@@ -1533,9 +1537,10 @@ const DeclGen = struct {
15331537 }
15341538
15351539 fn resolveTypeInner(self: *DeclGen, ty: Type, repr: Repr) Error!IdRef {
1536 const mod = self.module;
1540 const pt = self.pt;
1541 const mod = pt.zcu;
15371542 const ip = &mod.intern_pool;
1538 log.debug("resolveType: ty = {}", .{ty.fmt(mod)});
1543 log.debug("resolveType: ty = {}", .{ty.fmt(pt)});
15391544 const target = self.getTarget();
15401545
15411546 const section = &self.spv.sections.types_globals_constants;
......@@ -1607,7 +1612,7 @@ const DeclGen = struct {
16071612 return self.fail("array type of {} elements is too large", .{ty.arrayLenIncludingSentinel(mod)});
16081613 };
16091614
1610 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1615 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) {
16111616 // The size of the array would be 0, but that is not allowed in SPIR-V.
16121617 // This path can be reached when the backend is asked to generate a pointer to
16131618 // an array of some zero-bit type. This should always be an indirect path.
......@@ -1655,7 +1660,7 @@ const DeclGen = struct {
16551660 var param_index: usize = 0;
16561661 for (fn_info.param_types.get(ip)) |param_ty_index| {
16571662 const param_ty = Type.fromInterned(param_ty_index);
1658 if (!param_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1663 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
16591664
16601665 param_ty_ids[param_index] = try self.resolveType(param_ty, .direct);
16611666 param_index += 1;
......@@ -1713,7 +1718,7 @@ const DeclGen = struct {
17131718
17141719 var member_index: usize = 0;
17151720 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, field_val| {
1716 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
1721 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
17171722
17181723 member_types[member_index] = try self.resolveType(Type.fromInterned(field_ty), .indirect);
17191724 member_index += 1;
......@@ -1742,7 +1747,7 @@ const DeclGen = struct {
17421747 var it = struct_type.iterateRuntimeOrder(ip);
17431748 while (it.next()) |field_index| {
17441749 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1745 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1750 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17461751 // This is a zero-bit field - we only needed it for the alignment.
17471752 continue;
17481753 }
......@@ -1761,7 +1766,7 @@ const DeclGen = struct {
17611766 },
17621767 .Optional => {
17631768 const payload_ty = ty.optionalChild(mod);
1764 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1769 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17651770 // Just use a bool.
17661771 // Note: Always generate the bool with indirect format, to save on some sanity
17671772 // Perform the conversion to a direct bool when the field is extracted.
......@@ -1878,14 +1883,14 @@ const DeclGen = struct {
18781883 };
18791884
18801885 fn errorUnionLayout(self: *DeclGen, payload_ty: Type) ErrorUnionLayout {
1881 const mod = self.module;
1886 const pt = self.pt;
18821887
1883 const error_align = Type.anyerror.abiAlignment(mod);
1884 const payload_align = payload_ty.abiAlignment(mod);
1888 const error_align = Type.anyerror.abiAlignment(pt);
1889 const payload_align = payload_ty.abiAlignment(pt);
18851890
18861891 const error_first = error_align.compare(.gt, payload_align);
18871892 return .{
1888 .payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod),
1893 .payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt),
18891894 .error_first = error_first,
18901895 };
18911896 }
......@@ -1909,9 +1914,10 @@ const DeclGen = struct {
19091914 };
19101915
19111916 fn unionLayout(self: *DeclGen, ty: Type) UnionLayout {
1912 const mod = self.module;
1917 const pt = self.pt;
1918 const mod = pt.zcu;
19131919 const ip = &mod.intern_pool;
1914 const layout = ty.unionGetLayout(self.module);
1920 const layout = ty.unionGetLayout(pt);
19151921 const union_obj = mod.typeToUnion(ty).?;
19161922
19171923 var union_layout = UnionLayout{
......@@ -1932,7 +1938,7 @@ const DeclGen = struct {
19321938 const most_aligned_field = layout.most_aligned_field;
19331939 const most_aligned_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[most_aligned_field]);
19341940 union_layout.payload_ty = most_aligned_field_ty;
1935 union_layout.payload_size = @intCast(most_aligned_field_ty.abiSize(mod));
1941 union_layout.payload_size = @intCast(most_aligned_field_ty.abiSize(pt));
19361942 } else {
19371943 union_layout.payload_size = 0;
19381944 }
......@@ -1999,7 +2005,7 @@ const DeclGen = struct {
19992005 }
20002006
20012007 fn materialize(self: Temporary, dg: *DeclGen) !IdResult {
2002 const mod = dg.module;
2008 const mod = dg.pt.zcu;
20032009 switch (self.value) {
20042010 .singleton => |id| return id,
20052011 .exploded_vector => |range| {
......@@ -2029,12 +2035,12 @@ const DeclGen = struct {
20292035 /// 'Explode' a temporary into separate elements. This turns a vector
20302036 /// into a bag of elements.
20312037 fn explode(self: Temporary, dg: *DeclGen) !IdRange {
2032 const mod = dg.module;
2038 const mod = dg.pt.zcu;
20332039
20342040 // If the value is a scalar, then this is a no-op.
20352041 if (!self.ty.isVector(mod)) {
20362042 return switch (self.value) {
2037 .singleton => |id| IdRange{ .base = @intFromEnum(id), .len = 1 },
2043 .singleton => |id| .{ .base = @intFromEnum(id), .len = 1 },
20382044 .exploded_vector => |range| range,
20392045 };
20402046 }
......@@ -2088,7 +2094,7 @@ const DeclGen = struct {
20882094 /// only checks the size, but the source-of-truth is implemented
20892095 /// by `isSpvVector()`.
20902096 fn fromType(ty: Type, dg: *DeclGen) Vectorization {
2091 const mod = dg.module;
2097 const mod = dg.pt.zcu;
20922098 if (!ty.isVector(mod)) {
20932099 return .scalar;
20942100 } else if (dg.isSpvVector(ty)) {
......@@ -2164,11 +2170,11 @@ const DeclGen = struct {
21642170 /// Turns `ty` into the result-type of an individual vector operation.
21652171 /// `ty` may be a scalar or vector, it doesn't matter.
21662172 fn operationType(self: Vectorization, dg: *DeclGen, ty: Type) !Type {
2167 const mod = dg.module;
2168 const scalar_ty = ty.scalarType(mod);
2173 const pt = dg.pt;
2174 const scalar_ty = ty.scalarType(pt.zcu);
21692175 return switch (self) {
21702176 .scalar, .unrolled => scalar_ty,
2171 .spv_vectorized => |n| try mod.vectorType(.{
2177 .spv_vectorized => |n| try pt.vectorType(.{
21722178 .len = n,
21732179 .child = scalar_ty.toIntern(),
21742180 }),
......@@ -2178,11 +2184,11 @@ const DeclGen = struct {
21782184 /// Turns `ty` into the result-type of the entire operation.
21792185 /// `ty` may be a scalar or vector, it doesn't matter.
21802186 fn resultType(self: Vectorization, dg: *DeclGen, ty: Type) !Type {
2181 const mod = dg.module;
2182 const scalar_ty = ty.scalarType(mod);
2187 const pt = dg.pt;
2188 const scalar_ty = ty.scalarType(pt.zcu);
21832189 return switch (self) {
21842190 .scalar => scalar_ty,
2185 .unrolled, .spv_vectorized => |n| try mod.vectorType(.{
2191 .unrolled, .spv_vectorized => |n| try pt.vectorType(.{
21862192 .len = n,
21872193 .child = scalar_ty.toIntern(),
21882194 }),
......@@ -2193,8 +2199,8 @@ const DeclGen = struct {
21932199 /// this setup, and returns a new type that holds the relevant information on how to access
21942200 /// elements of the input.
21952201 fn prepare(self: Vectorization, dg: *DeclGen, tmp: Temporary) !PreparedOperand {
2196 const mod = dg.module;
2197 const is_vector = tmp.ty.isVector(mod);
2202 const pt = dg.pt;
2203 const is_vector = tmp.ty.isVector(pt.zcu);
21982204 const is_spv_vector = dg.isSpvVector(tmp.ty);
21992205 const value: PreparedOperand.Value = switch (tmp.value) {
22002206 .singleton => |id| switch (self) {
......@@ -2209,7 +2215,7 @@ const DeclGen = struct {
22092215 }
22102216
22112217 // Broadcast scalar into vector.
2212 const vector_ty = try mod.vectorType(.{
2218 const vector_ty = try pt.vectorType(.{
22132219 .len = self.components(),
22142220 .child = tmp.ty.toIntern(),
22152221 });
......@@ -2340,7 +2346,7 @@ const DeclGen = struct {
23402346 /// This function builds an OpSConvert of OpUConvert depending on the
23412347 /// signedness of the types.
23422348 fn buildIntConvert(self: *DeclGen, dst_ty: Type, src: Temporary) !Temporary {
2343 const mod = self.module;
2349 const mod = self.pt.zcu;
23442350
23452351 const dst_ty_id = try self.resolveType(dst_ty.scalarType(mod), .direct);
23462352 const src_ty_id = try self.resolveType(src.ty.scalarType(mod), .direct);
......@@ -2419,7 +2425,7 @@ const DeclGen = struct {
24192425 }
24202426
24212427 fn buildSelect(self: *DeclGen, condition: Temporary, lhs: Temporary, rhs: Temporary) !Temporary {
2422 const mod = self.module;
2428 const mod = self.pt.zcu;
24232429
24242430 const v = self.vectorization(.{ condition, lhs, rhs });
24252431 const ops = v.operations();
......@@ -2764,7 +2770,8 @@ const DeclGen = struct {
27642770 lhs: Temporary,
27652771 rhs: Temporary,
27662772 ) !struct { Temporary, Temporary } {
2767 const mod = self.module;
2773 const pt = self.pt;
2774 const mod = pt.zcu;
27682775 const target = self.getTarget();
27692776 const ip = &mod.intern_pool;
27702777
......@@ -2814,7 +2821,7 @@ const DeclGen = struct {
28142821 // where T is maybe vectorized.
28152822 const types = [2]InternPool.Index{ arith_op_ty.toIntern(), arith_op_ty.toIntern() };
28162823 const values = [2]InternPool.Index{ .none, .none };
2817 const index = try ip.getAnonStructType(mod.gpa, .{
2824 const index = try ip.getAnonStructType(mod.gpa, pt.tid, .{
28182825 .types = &types,
28192826 .values = &values,
28202827 .names = &.{},
......@@ -2888,7 +2895,7 @@ const DeclGen = struct {
28882895 /// the name of an error in the text executor.
28892896 fn generateTestEntryPoint(self: *DeclGen, name: []const u8, spv_test_decl_index: SpvModule.Decl.Index) !void {
28902897 const anyerror_ty_id = try self.resolveType(Type.anyerror, .direct);
2891 const ptr_anyerror_ty = try self.module.ptrType(.{
2898 const ptr_anyerror_ty = try self.pt.ptrType(.{
28922899 .child = Type.anyerror.toIntern(),
28932900 .flags = .{ .address_space = .global },
28942901 });
......@@ -2940,7 +2947,8 @@ const DeclGen = struct {
29402947 }
29412948
29422949 fn genDecl(self: *DeclGen) !void {
2943 const mod = self.module;
2950 const pt = self.pt;
2951 const mod = pt.zcu;
29442952 const ip = &mod.intern_pool;
29452953 const decl = mod.declPtr(self.decl_index);
29462954 const spv_decl_index = try self.object.resolveDecl(mod, self.decl_index);
......@@ -2967,7 +2975,7 @@ const DeclGen = struct {
29672975 try self.args.ensureUnusedCapacity(self.gpa, fn_info.param_types.len);
29682976 for (fn_info.param_types.get(ip)) |param_ty_index| {
29692977 const param_ty = Type.fromInterned(param_ty_index);
2970 if (!param_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2978 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
29712979
29722980 const param_type_id = try self.resolveType(param_ty, .direct);
29732981 const arg_result_id = self.spv.allocId();
......@@ -3004,11 +3012,11 @@ const DeclGen = struct {
30043012 // Append the actual code into the functions section.
30053013 try self.spv.addFunction(spv_decl_index, self.func);
30063014
3007 const fqn = try decl.fullyQualifiedName(self.module);
3015 const fqn = try decl.fullyQualifiedName(self.pt.zcu);
30083016 try self.spv.debugName(result_id, fqn.toSlice(ip));
30093017
30103018 // Temporarily generate a test kernel declaration if this is a test function.
3011 if (self.module.test_functions.contains(self.decl_index)) {
3019 if (self.pt.zcu.test_functions.contains(self.decl_index)) {
30123020 try self.generateTestEntryPoint(fqn.toSlice(ip), spv_decl_index);
30133021 }
30143022 },
......@@ -3033,7 +3041,7 @@ const DeclGen = struct {
30333041 .storage_class = final_storage_class,
30343042 });
30353043
3036 const fqn = try decl.fullyQualifiedName(self.module);
3044 const fqn = try decl.fullyQualifiedName(self.pt.zcu);
30373045 try self.spv.debugName(result_id, fqn.toSlice(ip));
30383046 try self.spv.declareDeclDeps(spv_decl_index, &.{});
30393047 },
......@@ -3078,7 +3086,7 @@ const DeclGen = struct {
30783086 try self.func.body.emit(self.spv.gpa, .OpFunctionEnd, {});
30793087 try self.spv.addFunction(spv_decl_index, self.func);
30803088
3081 const fqn = try decl.fullyQualifiedName(self.module);
3089 const fqn = try decl.fullyQualifiedName(self.pt.zcu);
30823090 try self.spv.debugNameFmt(initializer_id, "initializer of {}", .{fqn.fmt(ip)});
30833091
30843092 try self.spv.sections.types_globals_constants.emit(self.spv.gpa, .OpExtInst, .{
......@@ -3119,7 +3127,7 @@ const DeclGen = struct {
31193127 /// Convert representation from indirect (in memory) to direct (in 'register')
31203128 /// This converts the argument type from resolveType(ty, .indirect) to resolveType(ty, .direct).
31213129 fn convertToDirect(self: *DeclGen, ty: Type, operand_id: IdRef) !IdRef {
3122 const mod = self.module;
3130 const mod = self.pt.zcu;
31233131 switch (ty.scalarType(mod).zigTypeTag(mod)) {
31243132 .Bool => {
31253133 const false_id = try self.constBool(false, .indirect);
......@@ -3145,7 +3153,7 @@ const DeclGen = struct {
31453153 /// Convert representation from direct (in 'register) to direct (in memory)
31463154 /// This converts the argument type from resolveType(ty, .direct) to resolveType(ty, .indirect).
31473155 fn convertToIndirect(self: *DeclGen, ty: Type, operand_id: IdRef) !IdRef {
3148 const mod = self.module;
3156 const mod = self.pt.zcu;
31493157 switch (ty.scalarType(mod).zigTypeTag(mod)) {
31503158 .Bool => {
31513159 const result = try self.intFromBool(Temporary.init(ty, operand_id));
......@@ -3222,7 +3230,7 @@ const DeclGen = struct {
32223230 }
32233231
32243232 fn genInst(self: *DeclGen, inst: Air.Inst.Index) !void {
3225 const mod = self.module;
3233 const mod = self.pt.zcu;
32263234 const ip = &mod.intern_pool;
32273235 if (self.liveness.isUnused(inst) and !self.air.mustLower(inst, ip))
32283236 return;
......@@ -3402,7 +3410,7 @@ const DeclGen = struct {
34023410 }
34033411
34043412 fn airShift(self: *DeclGen, inst: Air.Inst.Index, unsigned: BinaryOp, signed: BinaryOp) !?IdRef {
3405 const mod = self.module;
3413 const mod = self.pt.zcu;
34063414 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34073415
34083416 const base = try self.temporary(bin_op.lhs);
......@@ -3480,7 +3488,7 @@ const DeclGen = struct {
34803488 /// All other values are returned unmodified (this makes strange integer
34813489 /// wrapping easier to use in generic operations).
34823490 fn normalize(self: *DeclGen, value: Temporary, info: ArithmeticTypeInfo) !Temporary {
3483 const mod = self.module;
3491 const mod = self.pt.zcu;
34843492 const ty = value.ty;
34853493 switch (info.class) {
34863494 .integer, .bool, .float => return value,
......@@ -3721,7 +3729,7 @@ const DeclGen = struct {
37213729
37223730 fn airMulOverflow(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
37233731 const target = self.getTarget();
3724 const mod = self.module;
3732 const pt = self.pt;
37253733
37263734 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
37273735 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
......@@ -3758,7 +3766,7 @@ const DeclGen = struct {
37583766 const result, const overflowed = switch (info.signedness) {
37593767 .unsigned => blk: {
37603768 if (maybe_op_ty_bits) |op_ty_bits| {
3761 const op_ty = try mod.intType(.unsigned, op_ty_bits);
3769 const op_ty = try pt.intType(.unsigned, op_ty_bits);
37623770 const casted_lhs = try self.buildIntConvert(op_ty, lhs);
37633771 const casted_rhs = try self.buildIntConvert(op_ty, rhs);
37643772
......@@ -3828,7 +3836,7 @@ const DeclGen = struct {
38283836 );
38293837
38303838 if (maybe_op_ty_bits) |op_ty_bits| {
3831 const op_ty = try mod.intType(.signed, op_ty_bits);
3839 const op_ty = try pt.intType(.signed, op_ty_bits);
38323840 // Assume normalized; sign bit is set. We want a sign extend.
38333841 const casted_lhs = try self.buildIntConvert(op_ty, lhs);
38343842 const casted_rhs = try self.buildIntConvert(op_ty, rhs);
......@@ -3900,7 +3908,7 @@ const DeclGen = struct {
39003908 }
39013909
39023910 fn airShlOverflow(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
3903 const mod = self.module;
3911 const mod = self.pt.zcu;
39043912
39053913 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39063914 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
......@@ -3958,7 +3966,7 @@ const DeclGen = struct {
39583966 fn airClzCtz(self: *DeclGen, inst: Air.Inst.Index, op: UnaryOp) !?IdRef {
39593967 if (self.liveness.isUnused(inst)) return null;
39603968
3961 const mod = self.module;
3969 const mod = self.pt.zcu;
39623970 const target = self.getTarget();
39633971 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
39643972 const operand = try self.temporary(ty_op.operand);
......@@ -4007,7 +4015,7 @@ const DeclGen = struct {
40074015 }
40084016
40094017 fn airReduce(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4010 const mod = self.module;
4018 const mod = self.pt.zcu;
40114019 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
40124020 const operand = try self.resolve(reduce.operand);
40134021 const operand_ty = self.typeOf(reduce.operand);
......@@ -4082,7 +4090,8 @@ const DeclGen = struct {
40824090 }
40834091
40844092 fn airShuffle(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4085 const mod = self.module;
4093 const pt = self.pt;
4094 const mod = pt.zcu;
40864095 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40874096 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
40884097 const a = try self.resolve(extra.a);
......@@ -4108,14 +4117,14 @@ const DeclGen = struct {
41084117 const a_len = a_ty.vectorLen(mod);
41094118
41104119 for (components, 0..) |*component, i| {
4111 const elem = try mask.elemValue(mod, i);
4120 const elem = try mask.elemValue(pt, i);
41124121 if (elem.isUndef(mod)) {
41134122 // This is explicitly valid for OpVectorShuffle, it indicates undefined.
41144123 component.* = 0xFFFF_FFFF;
41154124 continue;
41164125 }
41174126
4118 const index = elem.toSignedInt(mod);
4127 const index = elem.toSignedInt(pt);
41194128 if (index >= 0) {
41204129 component.* = @intCast(index);
41214130 } else {
......@@ -4140,13 +4149,13 @@ const DeclGen = struct {
41404149 defer self.gpa.free(components);
41414150
41424151 for (components, 0..) |*id, i| {
4143 const elem = try mask.elemValue(mod, i);
4152 const elem = try mask.elemValue(pt, i);
41444153 if (elem.isUndef(mod)) {
41454154 id.* = try self.spv.constUndef(scalar_ty_id);
41464155 continue;
41474156 }
41484157
4149 const index = elem.toSignedInt(mod);
4158 const index = elem.toSignedInt(pt);
41504159 if (index >= 0) {
41514160 id.* = try self.extractVectorComponent(scalar_ty, a, @intCast(index));
41524161 } else {
......@@ -4220,7 +4229,7 @@ const DeclGen = struct {
42204229 }
42214230
42224231 fn ptrAdd(self: *DeclGen, result_ty: Type, ptr_ty: Type, ptr_id: IdRef, offset_id: IdRef) !IdRef {
4223 const mod = self.module;
4232 const mod = self.pt.zcu;
42244233 const result_ty_id = try self.resolveType(result_ty, .direct);
42254234
42264235 switch (ptr_ty.ptrSize(mod)) {
......@@ -4276,7 +4285,8 @@ const DeclGen = struct {
42764285 lhs: Temporary,
42774286 rhs: Temporary,
42784287 ) !Temporary {
4279 const mod = self.module;
4288 const pt = self.pt;
4289 const mod = pt.zcu;
42804290 const scalar_ty = lhs.ty.scalarType(mod);
42814291 const is_vector = lhs.ty.isVector(mod);
42824292
......@@ -4324,7 +4334,7 @@ const DeclGen = struct {
43244334
43254335 const payload_ty = ty.optionalChild(mod);
43264336 if (ty.optionalReprIsPayload(mod)) {
4327 assert(payload_ty.hasRuntimeBitsIgnoreComptime(mod));
4337 assert(payload_ty.hasRuntimeBitsIgnoreComptime(pt));
43284338 assert(!payload_ty.isSlice(mod));
43294339
43304340 return try self.cmp(op, lhs.pun(payload_ty), rhs.pun(payload_ty));
......@@ -4333,12 +4343,12 @@ const DeclGen = struct {
43334343 const lhs_id = try lhs.materialize(self);
43344344 const rhs_id = try rhs.materialize(self);
43354345
4336 const lhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4346 const lhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
43374347 try self.extractField(Type.bool, lhs_id, 1)
43384348 else
43394349 try self.convertToDirect(Type.bool, lhs_id);
43404350
4341 const rhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4351 const rhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
43424352 try self.extractField(Type.bool, rhs_id, 1)
43434353 else
43444354 try self.convertToDirect(Type.bool, rhs_id);
......@@ -4346,7 +4356,7 @@ const DeclGen = struct {
43464356 const lhs_valid = Temporary.init(Type.bool, lhs_valid_id);
43474357 const rhs_valid = Temporary.init(Type.bool, rhs_valid_id);
43484358
4349 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4359 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43504360 return try self.cmp(op, lhs_valid, rhs_valid);
43514361 }
43524362
......@@ -4466,7 +4476,7 @@ const DeclGen = struct {
44664476 src_ty: Type,
44674477 src_id: IdRef,
44684478 ) !IdRef {
4469 const mod = self.module;
4479 const mod = self.pt.zcu;
44704480 const src_ty_id = try self.resolveType(src_ty, .direct);
44714481 const dst_ty_id = try self.resolveType(dst_ty, .direct);
44724482
......@@ -4675,7 +4685,8 @@ const DeclGen = struct {
46754685 }
46764686
46774687 fn airArrayToSlice(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4678 const mod = self.module;
4688 const pt = self.pt;
4689 const mod = pt.zcu;
46794690 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
46804691 const array_ptr_ty = self.typeOf(ty_op.operand);
46814692 const array_ty = array_ptr_ty.childType(mod);
......@@ -4687,7 +4698,7 @@ const DeclGen = struct {
46874698 const array_ptr_id = try self.resolve(ty_op.operand);
46884699 const len_id = try self.constInt(Type.usize, array_ty.arrayLen(mod), .direct);
46894700
4690 const elem_ptr_id = if (!array_ty.hasRuntimeBitsIgnoreComptime(mod))
4701 const elem_ptr_id = if (!array_ty.hasRuntimeBitsIgnoreComptime(pt))
46914702 // Note: The pointer is something like *opaque{}, so we need to bitcast it to the element type.
46924703 try self.bitCast(elem_ptr_ty, array_ptr_ty, array_ptr_id)
46934704 else
......@@ -4719,7 +4730,8 @@ const DeclGen = struct {
47194730 }
47204731
47214732 fn airAggregateInit(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4722 const mod = self.module;
4733 const pt = self.pt;
4734 const mod = pt.zcu;
47234735 const ip = &mod.intern_pool;
47244736 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
47254737 const result_ty = self.typeOfIndex(inst);
......@@ -4742,8 +4754,8 @@ const DeclGen = struct {
47424754 switch (ip.indexToKey(result_ty.toIntern())) {
47434755 .anon_struct_type => |tuple| {
47444756 for (tuple.types.get(ip), elements, 0..) |field_ty, element, i| {
4745 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
4746 assert(Type.fromInterned(field_ty).hasRuntimeBits(mod));
4757 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
4758 assert(Type.fromInterned(field_ty).hasRuntimeBits(pt));
47474759
47484760 const id = try self.resolve(element);
47494761 types[index] = Type.fromInterned(field_ty);
......@@ -4756,9 +4768,9 @@ const DeclGen = struct {
47564768 var it = struct_type.iterateRuntimeOrder(ip);
47574769 for (elements, 0..) |element, i| {
47584770 const field_index = it.next().?;
4759 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
4771 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
47604772 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
4761 assert(field_ty.hasRuntimeBitsIgnoreComptime(mod));
4773 assert(field_ty.hasRuntimeBitsIgnoreComptime(pt));
47624774
47634775 const id = try self.resolve(element);
47644776 types[index] = field_ty;
......@@ -4808,13 +4820,14 @@ const DeclGen = struct {
48084820 }
48094821
48104822 fn sliceOrArrayLen(self: *DeclGen, operand_id: IdRef, ty: Type) !IdRef {
4811 const mod = self.module;
4823 const pt = self.pt;
4824 const mod = pt.zcu;
48124825 switch (ty.ptrSize(mod)) {
48134826 .Slice => return self.extractField(Type.usize, operand_id, 1),
48144827 .One => {
48154828 const array_ty = ty.childType(mod);
48164829 const elem_ty = array_ty.childType(mod);
4817 const abi_size = elem_ty.abiSize(mod);
4830 const abi_size = elem_ty.abiSize(pt);
48184831 const size = array_ty.arrayLenIncludingSentinel(mod) * abi_size;
48194832 return try self.constInt(Type.usize, size, .direct);
48204833 },
......@@ -4823,7 +4836,7 @@ const DeclGen = struct {
48234836 }
48244837
48254838 fn sliceOrArrayPtr(self: *DeclGen, operand_id: IdRef, ty: Type) !IdRef {
4826 const mod = self.module;
4839 const mod = self.pt.zcu;
48274840 if (ty.isSlice(mod)) {
48284841 const ptr_ty = ty.slicePtrFieldType(mod);
48294842 return self.extractField(ptr_ty, operand_id, 0);
......@@ -4855,7 +4868,7 @@ const DeclGen = struct {
48554868 }
48564869
48574870 fn airSliceElemPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4858 const mod = self.module;
4871 const mod = self.pt.zcu;
48594872 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
48604873 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
48614874 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -4872,7 +4885,7 @@ const DeclGen = struct {
48724885 }
48734886
48744887 fn airSliceElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4875 const mod = self.module;
4888 const mod = self.pt.zcu;
48764889 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
48774890 const slice_ty = self.typeOf(bin_op.lhs);
48784891 if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) return null;
......@@ -4889,7 +4902,7 @@ const DeclGen = struct {
48894902 }
48904903
48914904 fn ptrElemPtr(self: *DeclGen, ptr_ty: Type, ptr_id: IdRef, index_id: IdRef) !IdRef {
4892 const mod = self.module;
4905 const mod = self.pt.zcu;
48934906 // Construct new pointer type for the resulting pointer
48944907 const elem_ty = ptr_ty.elemType2(mod); // use elemType() so that we get T for *[N]T.
48954908 const elem_ptr_ty_id = try self.ptrType(elem_ty, self.spvStorageClass(ptr_ty.ptrAddressSpace(mod)));
......@@ -4904,14 +4917,15 @@ const DeclGen = struct {
49044917 }
49054918
49064919 fn airPtrElemPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4907 const mod = self.module;
4920 const pt = self.pt;
4921 const mod = pt.zcu;
49084922 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
49094923 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
49104924 const src_ptr_ty = self.typeOf(bin_op.lhs);
49114925 const elem_ty = src_ptr_ty.childType(mod);
49124926 const ptr_id = try self.resolve(bin_op.lhs);
49134927
4914 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4928 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) {
49154929 const dst_ptr_ty = self.typeOfIndex(inst);
49164930 return try self.bitCast(dst_ptr_ty, src_ptr_ty, ptr_id);
49174931 }
......@@ -4921,7 +4935,7 @@ const DeclGen = struct {
49214935 }
49224936
49234937 fn airArrayElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4924 const mod = self.module;
4938 const mod = self.pt.zcu;
49254939 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49264940 const array_ty = self.typeOf(bin_op.lhs);
49274941 const elem_ty = array_ty.childType(mod);
......@@ -4982,7 +4996,7 @@ const DeclGen = struct {
49824996 }
49834997
49844998 fn airPtrElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4985 const mod = self.module;
4999 const mod = self.pt.zcu;
49865000 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49875001 const ptr_ty = self.typeOf(bin_op.lhs);
49885002 const elem_ty = self.typeOfIndex(inst);
......@@ -4993,7 +5007,7 @@ const DeclGen = struct {
49935007 }
49945008
49955009 fn airVectorStoreElem(self: *DeclGen, inst: Air.Inst.Index) !void {
4996 const mod = self.module;
5010 const mod = self.pt.zcu;
49975011 const data = self.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
49985012 const extra = self.air.extraData(Air.Bin, data.payload).data;
49995013
......@@ -5015,7 +5029,7 @@ const DeclGen = struct {
50155029 }
50165030
50175031 fn airSetUnionTag(self: *DeclGen, inst: Air.Inst.Index) !void {
5018 const mod = self.module;
5032 const mod = self.pt.zcu;
50195033 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
50205034 const un_ptr_ty = self.typeOf(bin_op.lhs);
50215035 const un_ty = un_ptr_ty.childType(mod);
......@@ -5041,7 +5055,7 @@ const DeclGen = struct {
50415055 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50425056 const un_ty = self.typeOf(ty_op.operand);
50435057
5044 const mod = self.module;
5058 const mod = self.pt.zcu;
50455059 const layout = self.unionLayout(un_ty);
50465060 if (layout.tag_size == 0) return null;
50475061
......@@ -5064,7 +5078,8 @@ const DeclGen = struct {
50645078
50655079 // Note: The result here is not cached, because it generates runtime code.
50665080
5067 const mod = self.module;
5081 const pt = self.pt;
5082 const mod = pt.zcu;
50685083 const ip = &mod.intern_pool;
50695084 const union_ty = mod.typeToUnion(ty).?;
50705085 const tag_ty = Type.fromInterned(union_ty.enum_tag_ty);
......@@ -5076,9 +5091,9 @@ const DeclGen = struct {
50765091 const layout = self.unionLayout(ty);
50775092
50785093 const tag_int = if (layout.tag_size != 0) blk: {
5079 const tag_val = try mod.enumValueFieldIndex(tag_ty, active_field);
5080 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
5081 break :blk tag_int_val.toUnsignedInt(mod);
5094 const tag_val = try pt.enumValueFieldIndex(tag_ty, active_field);
5095 const tag_int_val = try tag_val.intFromEnum(tag_ty, pt);
5096 break :blk tag_int_val.toUnsignedInt(pt);
50825097 } else 0;
50835098
50845099 if (!layout.has_payload) {
......@@ -5095,7 +5110,7 @@ const DeclGen = struct {
50955110 }
50965111
50975112 const payload_ty = Type.fromInterned(union_ty.field_types.get(ip)[active_field]);
5098 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5113 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
50995114 const pl_ptr_ty_id = try self.ptrType(layout.payload_ty, .Function);
51005115 const pl_ptr_id = try self.accessChain(pl_ptr_ty_id, tmp_id, &.{layout.payload_index});
51015116 const active_pl_ptr_ty_id = try self.ptrType(payload_ty, .Function);
......@@ -5118,7 +5133,8 @@ const DeclGen = struct {
51185133 }
51195134
51205135 fn airUnionInit(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5121 const mod = self.module;
5136 const pt = self.pt;
5137 const mod = pt.zcu;
51225138 const ip = &mod.intern_pool;
51235139 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51245140 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
......@@ -5126,7 +5142,7 @@ const DeclGen = struct {
51265142
51275143 const union_obj = mod.typeToUnion(ty).?;
51285144 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
5129 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(mod))
5145 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(pt))
51305146 try self.resolve(extra.init)
51315147 else
51325148 null;
......@@ -5134,7 +5150,8 @@ const DeclGen = struct {
51345150 }
51355151
51365152 fn airStructFieldVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5137 const mod = self.module;
5153 const pt = self.pt;
5154 const mod = pt.zcu;
51385155 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51395156 const struct_field = self.air.extraData(Air.StructField, ty_pl.payload).data;
51405157
......@@ -5143,7 +5160,7 @@ const DeclGen = struct {
51435160 const field_index = struct_field.field_index;
51445161 const field_ty = object_ty.structFieldType(field_index, mod);
51455162
5146 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return null;
5163 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return null;
51475164
51485165 switch (object_ty.zigTypeTag(mod)) {
51495166 .Struct => switch (object_ty.containerLayout(mod)) {
......@@ -5178,7 +5195,8 @@ const DeclGen = struct {
51785195 }
51795196
51805197 fn airFieldParentPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5181 const mod = self.module;
5198 const pt = self.pt;
5199 const mod = pt.zcu;
51825200 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51835201 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
51845202
......@@ -5187,7 +5205,7 @@ const DeclGen = struct {
51875205
51885206 const field_ptr = try self.resolve(extra.field_ptr);
51895207 const field_ptr_int = try self.intFromPtr(field_ptr);
5190 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
5208 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
51915209
51925210 const base_ptr_int = base_ptr_int: {
51935211 if (field_offset == 0) break :base_ptr_int field_ptr_int;
......@@ -5218,7 +5236,7 @@ const DeclGen = struct {
52185236 ) !IdRef {
52195237 const result_ty_id = try self.resolveType(result_ptr_ty, .direct);
52205238
5221 const zcu = self.module;
5239 const zcu = self.pt.zcu;
52225240 const object_ty = object_ptr_ty.childType(zcu);
52235241 switch (object_ty.zigTypeTag(zcu)) {
52245242 .Pointer => {
......@@ -5312,7 +5330,7 @@ const DeclGen = struct {
53125330 }
53135331
53145332 fn airAlloc(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5315 const mod = self.module;
5333 const mod = self.pt.zcu;
53165334 const ptr_ty = self.typeOfIndex(inst);
53175335 assert(ptr_ty.ptrAddressSpace(mod) == .generic);
53185336 const child_ty = ptr_ty.childType(mod);
......@@ -5486,9 +5504,10 @@ const DeclGen = struct {
54865504 // of the block, then a label, and then generate the rest of the current
54875505 // ir.Block in a different SPIR-V block.
54885506
5489 const mod = self.module;
5507 const pt = self.pt;
5508 const mod = pt.zcu;
54905509 const ty = self.typeOfIndex(inst);
5491 const have_block_result = ty.isFnOrHasRuntimeBitsIgnoreComptime(mod);
5510 const have_block_result = ty.isFnOrHasRuntimeBitsIgnoreComptime(pt);
54925511
54935512 const cf = switch (self.control_flow) {
54945513 .structured => |*cf| cf,
......@@ -5618,13 +5637,13 @@ const DeclGen = struct {
56185637 }
56195638
56205639 fn airBr(self: *DeclGen, inst: Air.Inst.Index) !void {
5621 const mod = self.module;
5640 const pt = self.pt;
56225641 const br = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
56235642 const operand_ty = self.typeOf(br.operand);
56245643
56255644 switch (self.control_flow) {
56265645 .structured => |*cf| {
5627 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5646 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
56285647 const operand_id = try self.resolve(br.operand);
56295648 const block_result_var_id = cf.block_results.get(br.block_inst).?;
56305649 try self.store(operand_ty, block_result_var_id, operand_id, .{});
......@@ -5635,7 +5654,7 @@ const DeclGen = struct {
56355654 },
56365655 .unstructured => |cf| {
56375656 const block = cf.blocks.get(br.block_inst).?;
5638 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5657 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
56395658 const operand_id = try self.resolve(br.operand);
56405659 // current_block_label should not be undefined here, lest there
56415660 // is a br or br_void in the function's body.
......@@ -5762,7 +5781,7 @@ const DeclGen = struct {
57625781 }
57635782
57645783 fn airLoad(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5765 const mod = self.module;
5784 const mod = self.pt.zcu;
57665785 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57675786 const ptr_ty = self.typeOf(ty_op.operand);
57685787 const elem_ty = self.typeOfIndex(inst);
......@@ -5773,20 +5792,22 @@ const DeclGen = struct {
57735792 }
57745793
57755794 fn airStore(self: *DeclGen, inst: Air.Inst.Index) !void {
5795 const mod = self.pt.zcu;
57765796 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57775797 const ptr_ty = self.typeOf(bin_op.lhs);
5778 const elem_ty = ptr_ty.childType(self.module);
5798 const elem_ty = ptr_ty.childType(mod);
57795799 const ptr = try self.resolve(bin_op.lhs);
57805800 const value = try self.resolve(bin_op.rhs);
57815801
5782 try self.store(elem_ty, ptr, value, .{ .is_volatile = ptr_ty.isVolatilePtr(self.module) });
5802 try self.store(elem_ty, ptr, value, .{ .is_volatile = ptr_ty.isVolatilePtr(mod) });
57835803 }
57845804
57855805 fn airRet(self: *DeclGen, inst: Air.Inst.Index) !void {
5806 const pt = self.pt;
5807 const mod = pt.zcu;
57865808 const operand = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
57875809 const ret_ty = self.typeOf(operand);
5788 const mod = self.module;
5789 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5810 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
57905811 const decl = mod.declPtr(self.decl_index);
57915812 const fn_info = mod.typeToFunc(decl.typeOf(mod)).?;
57925813 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
......@@ -5805,12 +5826,13 @@ const DeclGen = struct {
58055826 }
58065827
58075828 fn airRetLoad(self: *DeclGen, inst: Air.Inst.Index) !void {
5808 const mod = self.module;
5829 const pt = self.pt;
5830 const mod = pt.zcu;
58095831 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
58105832 const ptr_ty = self.typeOf(un_op);
58115833 const ret_ty = ptr_ty.childType(mod);
58125834
5813 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5835 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
58145836 const decl = mod.declPtr(self.decl_index);
58155837 const fn_info = mod.typeToFunc(decl.typeOf(mod)).?;
58165838 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
......@@ -5832,7 +5854,7 @@ const DeclGen = struct {
58325854 }
58335855
58345856 fn airTry(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5835 const mod = self.module;
5857 const mod = self.pt.zcu;
58365858 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
58375859 const err_union_id = try self.resolve(pl_op.operand);
58385860 const extra = self.air.extraData(Air.Try, pl_op.payload);
......@@ -5902,7 +5924,7 @@ const DeclGen = struct {
59025924 }
59035925
59045926 fn airErrUnionErr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5905 const mod = self.module;
5927 const mod = self.pt.zcu;
59065928 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59075929 const operand_id = try self.resolve(ty_op.operand);
59085930 const err_union_ty = self.typeOf(ty_op.operand);
......@@ -5938,7 +5960,7 @@ const DeclGen = struct {
59385960 }
59395961
59405962 fn airWrapErrUnionErr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5941 const mod = self.module;
5963 const mod = self.pt.zcu;
59425964 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59435965 const err_union_ty = self.typeOfIndex(inst);
59445966 const payload_ty = err_union_ty.errorUnionPayload(mod);
......@@ -5985,7 +6007,8 @@ const DeclGen = struct {
59856007 }
59866008
59876009 fn airIsNull(self: *DeclGen, inst: Air.Inst.Index, is_pointer: bool, pred: enum { is_null, is_non_null }) !?IdRef {
5988 const mod = self.module;
6010 const pt = self.pt;
6011 const mod = pt.zcu;
59896012 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
59906013 const operand_id = try self.resolve(un_op);
59916014 const operand_ty = self.typeOf(un_op);
......@@ -6026,7 +6049,7 @@ const DeclGen = struct {
60266049
60276050 const is_non_null_id = blk: {
60286051 if (is_pointer) {
6029 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6052 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
60306053 const storage_class = self.spvStorageClass(operand_ty.ptrAddressSpace(mod));
60316054 const bool_ptr_ty_id = try self.ptrType(Type.bool, storage_class);
60326055 const tag_ptr_id = try self.accessChain(bool_ptr_ty_id, operand_id, &.{1});
......@@ -6036,7 +6059,7 @@ const DeclGen = struct {
60366059 break :blk try self.load(Type.bool, operand_id, .{});
60376060 }
60386061
6039 break :blk if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
6062 break :blk if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
60406063 try self.extractField(Type.bool, operand_id, 1)
60416064 else
60426065 // Optional representation is bool indicating whether the optional is set
......@@ -6061,7 +6084,7 @@ const DeclGen = struct {
60616084 }
60626085
60636086 fn airIsErr(self: *DeclGen, inst: Air.Inst.Index, pred: enum { is_err, is_non_err }) !?IdRef {
6064 const mod = self.module;
6087 const mod = self.pt.zcu;
60656088 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
60666089 const operand_id = try self.resolve(un_op);
60676090 const err_union_ty = self.typeOf(un_op);
......@@ -6094,13 +6117,14 @@ const DeclGen = struct {
60946117 }
60956118
60966119 fn airUnwrapOptional(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6097 const mod = self.module;
6120 const pt = self.pt;
6121 const mod = pt.zcu;
60986122 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60996123 const operand_id = try self.resolve(ty_op.operand);
61006124 const optional_ty = self.typeOf(ty_op.operand);
61016125 const payload_ty = self.typeOfIndex(inst);
61026126
6103 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return null;
6127 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return null;
61046128
61056129 if (optional_ty.optionalReprIsPayload(mod)) {
61066130 return operand_id;
......@@ -6110,7 +6134,8 @@ const DeclGen = struct {
61106134 }
61116135
61126136 fn airUnwrapOptionalPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6113 const mod = self.module;
6137 const pt = self.pt;
6138 const mod = pt.zcu;
61146139 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61156140 const operand_id = try self.resolve(ty_op.operand);
61166141 const operand_ty = self.typeOf(ty_op.operand);
......@@ -6119,7 +6144,7 @@ const DeclGen = struct {
61196144 const result_ty = self.typeOfIndex(inst);
61206145 const result_ty_id = try self.resolveType(result_ty, .direct);
61216146
6122 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6147 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61236148 // There is no payload, but we still need to return a valid pointer.
61246149 // We can just return anything here, so just return a pointer to the operand.
61256150 return try self.bitCast(result_ty, operand_ty, operand_id);
......@@ -6134,11 +6159,12 @@ const DeclGen = struct {
61346159 }
61356160
61366161 fn airWrapOptional(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6137 const mod = self.module;
6162 const pt = self.pt;
6163 const mod = pt.zcu;
61386164 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61396165 const payload_ty = self.typeOf(ty_op.operand);
61406166
6141 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6167 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61426168 return try self.constBool(true, .indirect);
61436169 }
61446170
......@@ -6156,7 +6182,8 @@ const DeclGen = struct {
61566182 }
61576183
61586184 fn airSwitchBr(self: *DeclGen, inst: Air.Inst.Index) !void {
6159 const mod = self.module;
6185 const pt = self.pt;
6186 const mod = pt.zcu;
61606187 const target = self.getTarget();
61616188 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
61626189 const cond_ty = self.typeOf(pl_op.operand);
......@@ -6240,15 +6267,15 @@ const DeclGen = struct {
62406267 const label = case_labels.at(case_i);
62416268
62426269 for (items) |item| {
6243 const value = (try self.air.value(item, mod)) orelse unreachable;
6270 const value = (try self.air.value(item, pt)) orelse unreachable;
62446271 const int_val: u64 = switch (cond_ty.zigTypeTag(mod)) {
6245 .Bool, .Int => if (cond_ty.isSignedInt(mod)) @bitCast(value.toSignedInt(mod)) else value.toUnsignedInt(mod),
6272 .Bool, .Int => if (cond_ty.isSignedInt(mod)) @bitCast(value.toSignedInt(pt)) else value.toUnsignedInt(pt),
62466273 .Enum => blk: {
62476274 // TODO: figure out of cond_ty is correct (something with enum literals)
6248 break :blk (try value.intFromEnum(cond_ty, mod)).toUnsignedInt(mod); // TODO: composite integer constants
6275 break :blk (try value.intFromEnum(cond_ty, pt)).toUnsignedInt(pt); // TODO: composite integer constants
62496276 },
62506277 .ErrorSet => value.getErrorInt(mod),
6251 .Pointer => value.toUnsignedInt(mod),
6278 .Pointer => value.toUnsignedInt(pt),
62526279 else => unreachable,
62536280 };
62546281 const int_lit: spec.LiteralContextDependentNumber = switch (cond_words) {
......@@ -6328,8 +6355,9 @@ const DeclGen = struct {
63286355 }
63296356
63306357 fn airDbgStmt(self: *DeclGen, inst: Air.Inst.Index) !void {
6358 const pt = self.pt;
6359 const mod = pt.zcu;
63316360 const dbg_stmt = self.air.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
6332 const mod = self.module;
63336361 const decl = mod.declPtr(self.decl_index);
63346362 const path = decl.getFileScope(mod).sub_file_path;
63356363 try self.func.body.emit(self.spv.gpa, .OpLine, .{
......@@ -6340,7 +6368,7 @@ const DeclGen = struct {
63406368 }
63416369
63426370 fn airDbgInlineBlock(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6343 const mod = self.module;
6371 const mod = self.pt.zcu;
63446372 const inst_datas = self.air.instructions.items(.data);
63456373 const extra = self.air.extraData(Air.DbgInlineBlock, inst_datas[@intFromEnum(inst)].ty_pl.payload);
63466374 const decl = mod.funcOwnerDeclPtr(extra.data.func);
......@@ -6358,7 +6386,7 @@ const DeclGen = struct {
63586386 }
63596387
63606388 fn airAssembly(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6361 const mod = self.module;
6389 const mod = self.pt.zcu;
63626390 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
63636391 const extra = self.air.extraData(Air.Asm, ty_pl.payload);
63646392
......@@ -6440,20 +6468,20 @@ const DeclGen = struct {
64406468 // TODO: Translate proper error locations.
64416469 assert(as.errors.items.len != 0);
64426470 assert(self.error_msg == null);
6443 const src_loc = self.module.declPtr(self.decl_index).navSrcLoc(mod);
6444 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, "failed to assemble SPIR-V inline assembly", .{});
6445 const notes = try self.module.gpa.alloc(Module.ErrorMsg, as.errors.items.len);
6471 const src_loc = mod.declPtr(self.decl_index).navSrcLoc(mod);
6472 self.error_msg = try Zcu.ErrorMsg.create(mod.gpa, src_loc, "failed to assemble SPIR-V inline assembly", .{});
6473 const notes = try mod.gpa.alloc(Zcu.ErrorMsg, as.errors.items.len);
64466474
64476475 // Sub-scope to prevent `return error.CodegenFail` from running the errdefers.
64486476 {
6449 errdefer self.module.gpa.free(notes);
6477 errdefer mod.gpa.free(notes);
64506478 var i: usize = 0;
64516479 errdefer for (notes[0..i]) |*note| {
6452 note.deinit(self.module.gpa);
6480 note.deinit(mod.gpa);
64536481 };
64546482
64556483 while (i < as.errors.items.len) : (i += 1) {
6456 notes[i] = try Module.ErrorMsg.init(self.module.gpa, src_loc, "{s}", .{as.errors.items[i].msg});
6484 notes[i] = try Zcu.ErrorMsg.init(mod.gpa, src_loc, "{s}", .{as.errors.items[i].msg});
64576485 }
64586486 }
64596487 self.error_msg.?.notes = notes;
......@@ -6489,7 +6517,8 @@ const DeclGen = struct {
64896517 fn airCall(self: *DeclGen, inst: Air.Inst.Index, modifier: std.builtin.CallModifier) !?IdRef {
64906518 _ = modifier;
64916519
6492 const mod = self.module;
6520 const pt = self.pt;
6521 const mod = pt.zcu;
64936522 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
64946523 const extra = self.air.extraData(Air.Call, pl_op.payload);
64956524 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
......@@ -6515,7 +6544,7 @@ const DeclGen = struct {
65156544 // before starting to emit OpFunctionCall instructions. Hence the
65166545 // temporary params buffer.
65176546 const arg_ty = self.typeOf(arg);
6518 if (!arg_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
6547 if (!arg_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
65196548 const arg_id = try self.resolve(arg);
65206549
65216550 params[n_params] = arg_id;
......@@ -6533,7 +6562,7 @@ const DeclGen = struct {
65336562 try self.func.body.emit(self.spv.gpa, .OpUnreachable, {});
65346563 }
65356564
6536 if (self.liveness.isUnused(inst) or !Type.fromInterned(return_type).hasRuntimeBitsIgnoreComptime(mod)) {
6565 if (self.liveness.isUnused(inst) or !Type.fromInterned(return_type).hasRuntimeBitsIgnoreComptime(pt)) {
65376566 return null;
65386567 }
65396568
......@@ -6541,11 +6570,10 @@ const DeclGen = struct {
65416570 }
65426571
65436572 fn builtin3D(self: *DeclGen, result_ty: Type, builtin: spec.BuiltIn, dimension: u32, out_of_range_value: anytype) !IdRef {
6544 const mod = self.module;
65456573 if (dimension >= 3) {
65466574 return try self.constInt(result_ty, out_of_range_value, .direct);
65476575 }
6548 const vec_ty = try mod.vectorType(.{
6576 const vec_ty = try self.pt.vectorType(.{
65496577 .len = 3,
65506578 .child = result_ty.toIntern(),
65516579 });
......@@ -6591,12 +6619,12 @@ const DeclGen = struct {
65916619 }
65926620
65936621 fn typeOf(self: *DeclGen, inst: Air.Inst.Ref) Type {
6594 const mod = self.module;
6622 const mod = self.pt.zcu;
65956623 return self.air.typeOf(inst, &mod.intern_pool);
65966624 }
65976625
65986626 fn typeOfIndex(self: *DeclGen, inst: Air.Inst.Index) Type {
6599 const mod = self.module;
6627 const mod = self.pt.zcu;
66006628 return self.air.typeOfIndex(inst, &mod.intern_pool);
66016629 }
66026630};
src/crash_report.zig+3-3
......@@ -76,9 +76,9 @@ fn dumpStatusReport() !void {
7676
7777 const stderr = io.getStdErr().writer();
7878 const block: *Sema.Block = anal.block;
79 const mod = anal.sema.mod;
79 const zcu = anal.sema.pt.zcu;
8080
81 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, mod);
81 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, zcu);
8282
8383 try stderr.writeAll("Analyzing ");
8484 try writeFilePath(file, stderr);
......@@ -104,7 +104,7 @@ fn dumpStatusReport() !void {
104104 while (parent) |curr| {
105105 fba.reset();
106106 try stderr.writeAll(" in ");
107 const cur_block_file, const cur_block_src_base_node = Zcu.LazySrcLoc.resolveBaseNode(curr.block.src_base_inst, mod);
107 const cur_block_file, const cur_block_src_base_node = Zcu.LazySrcLoc.resolveBaseNode(curr.block.src_base_inst, zcu);
108108 try writeFilePath(cur_block_file, stderr);
109109 try stderr.writeAll("\n > ");
110110 print_zir.renderSingleInstruction(
src/link.zig+24-25
......@@ -15,8 +15,6 @@ const Compilation = @import("Compilation.zig");
1515const LibCInstallation = std.zig.LibCInstallation;
1616const Liveness = @import("Liveness.zig");
1717const Zcu = @import("Zcu.zig");
18/// Deprecated.
19const Module = Zcu;
2018const InternPool = @import("InternPool.zig");
2119const Type = @import("Type.zig");
2220const Value = @import("Value.zig");
......@@ -367,14 +365,14 @@ pub const File = struct {
367365 /// Called from within the CodeGen to lower a local variable instantion as an unnamed
368366 /// constant. Returns the symbol index of the lowered constant in the read-only section
369367 /// of the final binary.
370 pub fn lowerUnnamedConst(base: *File, val: Value, decl_index: InternPool.DeclIndex) UpdateDeclError!u32 {
368 pub fn lowerUnnamedConst(base: *File, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) UpdateDeclError!u32 {
371369 if (build_options.only_c) @compileError("unreachable");
372370 switch (base.tag) {
373371 .spirv => unreachable,
374372 .c => unreachable,
375373 .nvptx => unreachable,
376374 inline else => |t| {
377 return @as(*t.Type(), @fieldParentPtr("base", base)).lowerUnnamedConst(val, decl_index);
375 return @as(*t.Type(), @fieldParentPtr("base", base)).lowerUnnamedConst(pt, val, decl_index);
378376 },
379377 }
380378 }
......@@ -399,13 +397,13 @@ pub const File = struct {
399397 }
400398
401399 /// May be called before or after updateExports for any given Decl.
402 pub fn updateDecl(base: *File, module: *Module, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
403 const decl = module.declPtr(decl_index);
400 pub fn updateDecl(base: *File, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
401 const decl = pt.zcu.declPtr(decl_index);
404402 assert(decl.has_tv);
405403 switch (base.tag) {
406404 inline else => |tag| {
407405 if (tag != .c and build_options.only_c) unreachable;
408 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDecl(module, decl_index);
406 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDecl(pt, decl_index);
409407 },
410408 }
411409 }
......@@ -413,7 +411,7 @@ pub const File = struct {
413411 /// May be called before or after updateExports for any given Decl.
414412 pub fn updateFunc(
415413 base: *File,
416 module: *Module,
414 pt: Zcu.PerThread,
417415 func_index: InternPool.Index,
418416 air: Air,
419417 liveness: Liveness,
......@@ -421,12 +419,12 @@ pub const File = struct {
421419 switch (base.tag) {
422420 inline else => |tag| {
423421 if (tag != .c and build_options.only_c) unreachable;
424 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateFunc(module, func_index, air, liveness);
422 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateFunc(pt, func_index, air, liveness);
425423 },
426424 }
427425 }
428426
429 pub fn updateDeclLineNumber(base: *File, module: *Module, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
427 pub fn updateDeclLineNumber(base: *File, module: *Zcu, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
430428 const decl = module.declPtr(decl_index);
431429 assert(decl.has_tv);
432430 switch (base.tag) {
......@@ -537,7 +535,7 @@ pub const File = struct {
537535 /// Commit pending changes and write headers. Takes into account final output mode
538536 /// and `use_lld`, not only `effectiveOutputMode`.
539537 /// `arena` has the lifetime of the call to `Compilation.update`.
540 pub fn flush(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
538 pub fn flush(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
541539 if (build_options.only_c) {
542540 assert(base.tag == .c);
543541 return @as(*C, @fieldParentPtr("base", base)).flush(arena, prog_node);
......@@ -563,27 +561,27 @@ pub const File = struct {
563561 const output_mode = comp.config.output_mode;
564562 const link_mode = comp.config.link_mode;
565563 if (use_lld and output_mode == .Lib and link_mode == .static) {
566 return base.linkAsArchive(arena, prog_node);
564 return base.linkAsArchive(arena, tid, prog_node);
567565 }
568566 switch (base.tag) {
569567 inline else => |tag| {
570 return @as(*tag.Type(), @fieldParentPtr("base", base)).flush(arena, prog_node);
568 return @as(*tag.Type(), @fieldParentPtr("base", base)).flush(arena, tid, prog_node);
571569 },
572570 }
573571 }
574572
575573 /// Commit pending changes and write headers. Works based on `effectiveOutputMode`
576574 /// rather than final output mode.
577 pub fn flushModule(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
575 pub fn flushModule(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
578576 switch (base.tag) {
579577 inline else => |tag| {
580578 if (tag != .c and build_options.only_c) unreachable;
581 return @as(*tag.Type(), @fieldParentPtr("base", base)).flushModule(arena, prog_node);
579 return @as(*tag.Type(), @fieldParentPtr("base", base)).flushModule(arena, tid, prog_node);
582580 },
583581 }
584582 }
585583
586 /// Called when a Decl is deleted from the Module.
584 /// Called when a Decl is deleted from the Zcu.
587585 pub fn freeDecl(base: *File, decl_index: InternPool.DeclIndex) void {
588586 switch (base.tag) {
589587 inline else => |tag| {
......@@ -604,14 +602,14 @@ pub const File = struct {
604602 /// May be called before or after updateDecl for any given Decl.
605603 pub fn updateExports(
606604 base: *File,
607 module: *Module,
608 exported: Module.Exported,
605 pt: Zcu.PerThread,
606 exported: Zcu.Exported,
609607 export_indices: []const u32,
610608 ) UpdateExportsError!void {
611609 switch (base.tag) {
612610 inline else => |tag| {
613611 if (tag != .c and build_options.only_c) unreachable;
614 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateExports(module, exported, export_indices);
612 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateExports(pt, exported, export_indices);
615613 },
616614 }
617615 }
......@@ -644,9 +642,10 @@ pub const File = struct {
644642
645643 pub fn lowerAnonDecl(
646644 base: *File,
645 pt: Zcu.PerThread,
647646 decl_val: InternPool.Index,
648647 decl_align: InternPool.Alignment,
649 src_loc: Module.LazySrcLoc,
648 src_loc: Zcu.LazySrcLoc,
650649 ) !LowerResult {
651650 if (build_options.only_c) @compileError("unreachable");
652651 switch (base.tag) {
......@@ -654,7 +653,7 @@ pub const File = struct {
654653 .spirv => unreachable,
655654 .nvptx => unreachable,
656655 inline else => |tag| {
657 return @as(*tag.Type(), @fieldParentPtr("base", base)).lowerAnonDecl(decl_val, decl_align, src_loc);
656 return @as(*tag.Type(), @fieldParentPtr("base", base)).lowerAnonDecl(pt, decl_val, decl_align, src_loc);
658657 },
659658 }
660659 }
......@@ -689,7 +688,7 @@ pub const File = struct {
689688 }
690689 }
691690
692 pub fn linkAsArchive(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
691 pub fn linkAsArchive(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
693692 const tracy = trace(@src());
694693 defer tracy.end();
695694
......@@ -704,7 +703,7 @@ pub const File = struct {
704703 // If there is no Zig code to compile, then we should skip flushing the output file
705704 // because it will not be part of the linker line anyway.
706705 const zcu_obj_path: ?[]const u8 = if (opt_zcu != null) blk: {
707 try base.flushModule(arena, prog_node);
706 try base.flushModule(arena, tid, prog_node);
708707
709708 const dirname = fs.path.dirname(full_out_path_z) orelse ".";
710709 break :blk try fs.path.join(arena, &.{ dirname, base.zcu_object_sub_path.? });
......@@ -896,14 +895,14 @@ pub const File = struct {
896895 kind: Kind,
897896 ty: Type,
898897
899 pub fn initDecl(kind: Kind, decl: ?InternPool.DeclIndex, mod: *Module) LazySymbol {
898 pub fn initDecl(kind: Kind, decl: ?InternPool.DeclIndex, mod: *Zcu) LazySymbol {
900899 return .{ .kind = kind, .ty = if (decl) |decl_index|
901900 mod.declPtr(decl_index).val.toType()
902901 else
903902 Type.anyerror };
904903 }
905904
906 pub fn getDecl(self: LazySymbol, mod: *Module) InternPool.OptionalDeclIndex {
905 pub fn getDecl(self: LazySymbol, mod: *Zcu) InternPool.OptionalDeclIndex {
907906 return InternPool.OptionalDeclIndex.init(self.ty.getOwnerDeclOrNull(mod));
908907 }
909908 };
src/link/C.zig+31-28
......@@ -186,13 +186,13 @@ pub fn freeDecl(self: *C, decl_index: InternPool.DeclIndex) void {
186186
187187pub fn updateFunc(
188188 self: *C,
189 zcu: *Zcu,
189 pt: Zcu.PerThread,
190190 func_index: InternPool.Index,
191191 air: Air,
192192 liveness: Liveness,
193193) !void {
194 const gpa = self.base.comp.gpa;
195
194 const zcu = pt.zcu;
195 const gpa = zcu.gpa;
196196 const func = zcu.funcInfo(func_index);
197197 const decl_index = func.owner_decl;
198198 const decl = zcu.declPtr(decl_index);
......@@ -218,7 +218,7 @@ pub fn updateFunc(
218218 .object = .{
219219 .dg = .{
220220 .gpa = gpa,
221 .zcu = zcu,
221 .pt = pt,
222222 .mod = file_scope.mod,
223223 .error_msg = null,
224224 .pass = .{ .decl = decl_index },
......@@ -263,7 +263,7 @@ pub fn updateFunc(
263263 gop.value_ptr.code = try self.addString(function.object.code.items);
264264}
265265
266fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
266fn updateAnonDecl(self: *C, pt: Zcu.PerThread, i: usize) !void {
267267 const gpa = self.base.comp.gpa;
268268 const anon_decl = self.anon_decls.keys()[i];
269269
......@@ -275,8 +275,8 @@ fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
275275 var object: codegen.Object = .{
276276 .dg = .{
277277 .gpa = gpa,
278 .zcu = zcu,
279 .mod = zcu.root_mod,
278 .pt = pt,
279 .mod = pt.zcu.root_mod,
280280 .error_msg = null,
281281 .pass = .{ .anon = anon_decl },
282282 .is_naked_fn = false,
......@@ -319,12 +319,13 @@ fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
319319 };
320320}
321321
322pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
322pub fn updateDecl(self: *C, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
323323 const tracy = trace(@src());
324324 defer tracy.end();
325325
326326 const gpa = self.base.comp.gpa;
327327
328 const zcu = pt.zcu;
328329 const decl = zcu.declPtr(decl_index);
329330 const gop = try self.decl_table.getOrPut(gpa, decl_index);
330331 errdefer _ = self.decl_table.pop();
......@@ -342,7 +343,7 @@ pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
342343 var object: codegen.Object = .{
343344 .dg = .{
344345 .gpa = gpa,
345 .zcu = zcu,
346 .pt = pt,
346347 .mod = file_scope.mod,
347348 .error_msg = null,
348349 .pass = .{ .decl = decl_index },
......@@ -390,8 +391,8 @@ pub fn updateDeclLineNumber(self: *C, zcu: *Zcu, decl_index: InternPool.DeclInde
390391 _ = decl_index;
391392}
392393
393pub fn flush(self: *C, arena: Allocator, prog_node: std.Progress.Node) !void {
394 return self.flushModule(arena, prog_node);
394pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
395 return self.flushModule(arena, tid, prog_node);
395396}
396397
397398fn abiDefines(self: *C, target: std.Target) !std.ArrayList(u8) {
......@@ -409,7 +410,7 @@ fn abiDefines(self: *C, target: std.Target) !std.ArrayList(u8) {
409410 return defines;
410411}
411412
412pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !void {
413pub fn flushModule(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
413414 _ = arena; // Has the same lifetime as the call to Compilation.update.
414415
415416 const tracy = trace(@src());
......@@ -421,11 +422,12 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
421422 const comp = self.base.comp;
422423 const gpa = comp.gpa;
423424 const zcu = self.base.comp.module.?;
425 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = tid };
424426
425427 {
426428 var i: usize = 0;
427429 while (i < self.anon_decls.count()) : (i += 1) {
428 try updateAnonDecl(self, zcu, i);
430 try updateAnonDecl(self, pt, i);
429431 }
430432 }
431433
......@@ -463,7 +465,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
463465 self.lazy_fwd_decl_buf.clearRetainingCapacity();
464466 self.lazy_code_buf.clearRetainingCapacity();
465467 try f.lazy_ctype_pool.init(gpa);
466 try self.flushErrDecls(zcu, &f.lazy_ctype_pool);
468 try self.flushErrDecls(pt, &f.lazy_ctype_pool);
467469
468470 // Unlike other backends, the .c code we are emitting has order-dependent decls.
469471 // `CType`s, forward decls, and non-functions first.
......@@ -483,7 +485,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
483485 }
484486
485487 for (self.anon_decls.keys(), self.anon_decls.values()) |value, *decl_block| try self.flushDeclBlock(
486 zcu,
488 pt,
487489 zcu.root_mod,
488490 &f,
489491 decl_block,
......@@ -497,7 +499,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
497499 const extern_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;
498500 const mod = zcu.namespacePtr(decl.src_namespace).fileScope(zcu).mod;
499501 try self.flushDeclBlock(
500 zcu,
502 pt,
501503 mod,
502504 &f,
503505 decl_block,
......@@ -670,7 +672,7 @@ fn flushCTypes(
670672 }
671673}
672674
673fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDeclError!void {
675fn flushErrDecls(self: *C, pt: Zcu.PerThread, ctype_pool: *codegen.CType.Pool) FlushDeclError!void {
674676 const gpa = self.base.comp.gpa;
675677
676678 const fwd_decl = &self.lazy_fwd_decl_buf;
......@@ -679,8 +681,8 @@ fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDecl
679681 var object = codegen.Object{
680682 .dg = .{
681683 .gpa = gpa,
682 .zcu = zcu,
683 .mod = zcu.root_mod,
684 .pt = pt,
685 .mod = pt.zcu.root_mod,
684686 .error_msg = null,
685687 .pass = .flush,
686688 .is_naked_fn = false,
......@@ -712,7 +714,7 @@ fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDecl
712714
713715fn flushLazyFn(
714716 self: *C,
715 zcu: *Zcu,
717 pt: Zcu.PerThread,
716718 mod: *Module,
717719 ctype_pool: *codegen.CType.Pool,
718720 lazy_ctype_pool: *const codegen.CType.Pool,
......@@ -726,7 +728,7 @@ fn flushLazyFn(
726728 var object = codegen.Object{
727729 .dg = .{
728730 .gpa = gpa,
729 .zcu = zcu,
731 .pt = pt,
730732 .mod = mod,
731733 .error_msg = null,
732734 .pass = .flush,
......@@ -761,7 +763,7 @@ fn flushLazyFn(
761763
762764fn flushLazyFns(
763765 self: *C,
764 zcu: *Zcu,
766 pt: Zcu.PerThread,
765767 mod: *Module,
766768 f: *Flush,
767769 lazy_ctype_pool: *const codegen.CType.Pool,
......@@ -775,13 +777,13 @@ fn flushLazyFns(
775777 const gop = f.lazy_fns.getOrPutAssumeCapacity(entry.key_ptr.*);
776778 if (gop.found_existing) continue;
777779 gop.value_ptr.* = {};
778 try self.flushLazyFn(zcu, mod, &f.lazy_ctype_pool, lazy_ctype_pool, entry);
780 try self.flushLazyFn(pt, mod, &f.lazy_ctype_pool, lazy_ctype_pool, entry);
779781 }
780782}
781783
782784fn flushDeclBlock(
783785 self: *C,
784 zcu: *Zcu,
786 pt: Zcu.PerThread,
785787 mod: *Module,
786788 f: *Flush,
787789 decl_block: *const DeclBlock,
......@@ -790,7 +792,7 @@ fn flushDeclBlock(
790792 extern_name: InternPool.OptionalNullTerminatedString,
791793) FlushDeclError!void {
792794 const gpa = self.base.comp.gpa;
793 try self.flushLazyFns(zcu, mod, f, &decl_block.ctype_pool, decl_block.lazy_fns);
795 try self.flushLazyFns(pt, mod, f, &decl_block.ctype_pool, decl_block.lazy_fns);
794796 try f.all_buffers.ensureUnusedCapacity(gpa, 1);
795797 // avoid emitting extern decls that are already exported
796798 if (extern_name.unwrap()) |name| if (export_names.contains(name)) return;
......@@ -845,11 +847,12 @@ pub fn flushEmitH(zcu: *Zcu) !void {
845847
846848pub fn updateExports(
847849 self: *C,
848 zcu: *Zcu,
850 pt: Zcu.PerThread,
849851 exported: Zcu.Exported,
850852 export_indices: []const u32,
851853) !void {
852 const gpa = self.base.comp.gpa;
854 const zcu = pt.zcu;
855 const gpa = zcu.gpa;
853856 const mod, const pass: codegen.DeclGen.Pass, const decl_block, const exported_block = switch (exported) {
854857 .decl_index => |decl_index| .{
855858 zcu.namespacePtr(zcu.declPtr(decl_index).src_namespace).fileScope(zcu).mod,
......@@ -869,7 +872,7 @@ pub fn updateExports(
869872 fwd_decl.clearRetainingCapacity();
870873 var dg: codegen.DeclGen = .{
871874 .gpa = gpa,
872 .zcu = zcu,
875 .pt = pt,
873876 .mod = mod,
874877 .error_msg = null,
875878 .pass = pass,
src/link/Coff.zig+53-32
......@@ -1120,16 +1120,17 @@ fn freeAtom(self: *Coff, atom_index: Atom.Index) void {
11201120 self.getAtomPtr(atom_index).sym_index = 0;
11211121}
11221122
1123pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
1123pub fn updateFunc(self: *Coff, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
11241124 if (build_options.skip_non_native and builtin.object_format != .coff) {
11251125 @panic("Attempted to compile for object format that was disabled by build configuration");
11261126 }
11271127 if (self.llvm_object) |llvm_object| {
1128 return llvm_object.updateFunc(mod, func_index, air, liveness);
1128 return llvm_object.updateFunc(pt, func_index, air, liveness);
11291129 }
11301130 const tracy = trace(@src());
11311131 defer tracy.end();
11321132
1133 const mod = pt.zcu;
11331134 const func = mod.funcInfo(func_index);
11341135 const decl_index = func.owner_decl;
11351136 const decl = mod.declPtr(decl_index);
......@@ -1144,6 +1145,7 @@ pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air:
11441145
11451146 const res = try codegen.generateFunction(
11461147 &self.base,
1148 pt,
11471149 decl.navSrcLoc(mod),
11481150 func_index,
11491151 air,
......@@ -1160,14 +1162,14 @@ pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air:
11601162 },
11611163 };
11621164
1163 try self.updateDeclCode(decl_index, code, .FUNCTION);
1165 try self.updateDeclCode(pt, decl_index, code, .FUNCTION);
11641166
11651167 // Exports will be updated by `Zcu.processExports` after the update.
11661168}
11671169
1168pub fn lowerUnnamedConst(self: *Coff, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1169 const gpa = self.base.comp.gpa;
1170 const mod = self.base.comp.module.?;
1170pub fn lowerUnnamedConst(self: *Coff, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1171 const mod = pt.zcu;
1172 const gpa = mod.gpa;
11711173 const decl = mod.declPtr(decl_index);
11721174 const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index);
11731175 if (!gop.found_existing) {
......@@ -1179,7 +1181,7 @@ pub fn lowerUnnamedConst(self: *Coff, val: Value, decl_index: InternPool.DeclInd
11791181 const sym_name = try std.fmt.allocPrint(gpa, "__unnamed_{}_{d}", .{ decl_name.fmt(&mod.intern_pool), index });
11801182 defer gpa.free(sym_name);
11811183 const ty = val.typeOf(mod);
1182 const atom_index = switch (try self.lowerConst(sym_name, val, ty.abiAlignment(mod), self.rdata_section_index.?, decl.navSrcLoc(mod))) {
1184 const atom_index = switch (try self.lowerConst(pt, sym_name, val, ty.abiAlignment(pt), self.rdata_section_index.?, decl.navSrcLoc(mod))) {
11831185 .ok => |atom_index| atom_index,
11841186 .fail => |em| {
11851187 decl.analysis = .codegen_failure;
......@@ -1197,7 +1199,15 @@ const LowerConstResult = union(enum) {
11971199 fail: *Module.ErrorMsg,
11981200};
11991201
1200fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: InternPool.Alignment, sect_id: u16, src_loc: Module.LazySrcLoc) !LowerConstResult {
1202fn lowerConst(
1203 self: *Coff,
1204 pt: Zcu.PerThread,
1205 name: []const u8,
1206 val: Value,
1207 required_alignment: InternPool.Alignment,
1208 sect_id: u16,
1209 src_loc: Module.LazySrcLoc,
1210) !LowerConstResult {
12011211 const gpa = self.base.comp.gpa;
12021212
12031213 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1208,7 +1218,7 @@ fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: Int
12081218 try self.setSymbolName(sym, name);
12091219 sym.section_number = @as(coff.SectionNumber, @enumFromInt(sect_id + 1));
12101220
1211 const res = try codegen.generateSymbol(&self.base, src_loc, val, &code_buffer, .none, .{
1221 const res = try codegen.generateSymbol(&self.base, pt, src_loc, val, &code_buffer, .none, .{
12121222 .parent_atom_index = self.getAtom(atom_index).getSymbolIndex().?,
12131223 });
12141224 const code = switch (res) {
......@@ -1235,13 +1245,14 @@ fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: Int
12351245
12361246pub fn updateDecl(
12371247 self: *Coff,
1238 mod: *Module,
1248 pt: Zcu.PerThread,
12391249 decl_index: InternPool.DeclIndex,
12401250) link.File.UpdateDeclError!void {
1251 const mod = pt.zcu;
12411252 if (build_options.skip_non_native and builtin.object_format != .coff) {
12421253 @panic("Attempted to compile for object format that was disabled by build configuration");
12431254 }
1244 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
1255 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
12451256 const tracy = trace(@src());
12461257 defer tracy.end();
12471258
......@@ -1270,7 +1281,7 @@ pub fn updateDecl(
12701281 defer code_buffer.deinit();
12711282
12721283 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
1273 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
1284 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
12741285 .parent_atom_index = atom.getSymbolIndex().?,
12751286 });
12761287 const code = switch (res) {
......@@ -1282,19 +1293,20 @@ pub fn updateDecl(
12821293 },
12831294 };
12841295
1285 try self.updateDeclCode(decl_index, code, .NULL);
1296 try self.updateDeclCode(pt, decl_index, code, .NULL);
12861297
12871298 // Exports will be updated by `Zcu.processExports` after the update.
12881299}
12891300
12901301fn updateLazySymbolAtom(
12911302 self: *Coff,
1303 pt: Zcu.PerThread,
12921304 sym: link.File.LazySymbol,
12931305 atom_index: Atom.Index,
12941306 section_index: u16,
12951307) !void {
1296 const gpa = self.base.comp.gpa;
1297 const mod = self.base.comp.module.?;
1308 const mod = pt.zcu;
1309 const gpa = mod.gpa;
12981310
12991311 var required_alignment: InternPool.Alignment = .none;
13001312 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1302,7 +1314,7 @@ fn updateLazySymbolAtom(
13021314
13031315 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
13041316 @tagName(sym.kind),
1305 sym.ty.fmt(mod),
1317 sym.ty.fmt(pt),
13061318 });
13071319 defer gpa.free(name);
13081320
......@@ -1312,6 +1324,7 @@ fn updateLazySymbolAtom(
13121324 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
13131325 const res = try codegen.generateLazySymbol(
13141326 &self.base,
1327 pt,
13151328 src,
13161329 sym,
13171330 &required_alignment,
......@@ -1346,7 +1359,7 @@ fn updateLazySymbolAtom(
13461359 try self.writeAtom(atom_index, code);
13471360}
13481361
1349pub fn getOrCreateAtomForLazySymbol(self: *Coff, sym: link.File.LazySymbol) !Atom.Index {
1362pub fn getOrCreateAtomForLazySymbol(self: *Coff, pt: Zcu.PerThread, sym: link.File.LazySymbol) !Atom.Index {
13501363 const gpa = self.base.comp.gpa;
13511364 const mod = self.base.comp.module.?;
13521365 const gop = try self.lazy_syms.getOrPut(gpa, sym.getDecl(mod));
......@@ -1364,7 +1377,7 @@ pub fn getOrCreateAtomForLazySymbol(self: *Coff, sym: link.File.LazySymbol) !Ato
13641377 metadata.state.* = .pending_flush;
13651378 const atom = metadata.atom.*;
13661379 // anyerror needs to be deferred until flushModule
1367 if (sym.getDecl(mod) != .none) try self.updateLazySymbolAtom(sym, atom, switch (sym.kind) {
1380 if (sym.getDecl(mod) != .none) try self.updateLazySymbolAtom(pt, sym, atom, switch (sym.kind) {
13681381 .code => self.text_section_index.?,
13691382 .const_data => self.rdata_section_index.?,
13701383 });
......@@ -1410,14 +1423,14 @@ fn getDeclOutputSection(self: *Coff, decl_index: InternPool.DeclIndex) u16 {
14101423 return index;
14111424}
14121425
1413fn updateDeclCode(self: *Coff, decl_index: InternPool.DeclIndex, code: []u8, complex_type: coff.ComplexType) !void {
1414 const mod = self.base.comp.module.?;
1426fn updateDeclCode(self: *Coff, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex, code: []u8, complex_type: coff.ComplexType) !void {
1427 const mod = pt.zcu;
14151428 const decl = mod.declPtr(decl_index);
14161429
14171430 const decl_name = try decl.fullyQualifiedName(mod);
14181431
14191432 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
1420 const required_alignment: u32 = @intCast(decl.getAlignment(mod).toByteUnits() orelse 0);
1433 const required_alignment: u32 = @intCast(decl.getAlignment(pt).toByteUnits() orelse 0);
14211434
14221435 const decl_metadata = self.decls.get(decl_index).?;
14231436 const atom_index = decl_metadata.atom;
......@@ -1496,7 +1509,7 @@ pub fn freeDecl(self: *Coff, decl_index: InternPool.DeclIndex) void {
14961509
14971510pub fn updateExports(
14981511 self: *Coff,
1499 mod: *Module,
1512 pt: Zcu.PerThread,
15001513 exported: Module.Exported,
15011514 export_indices: []const u32,
15021515) link.File.UpdateExportsError!void {
......@@ -1504,6 +1517,7 @@ pub fn updateExports(
15041517 @panic("Attempted to compile for object format that was disabled by build configuration");
15051518 }
15061519
1520 const mod = pt.zcu;
15071521 const ip = &mod.intern_pool;
15081522 const comp = self.base.comp;
15091523 const target = comp.root_mod.resolved_target.result;
......@@ -1542,7 +1556,7 @@ pub fn updateExports(
15421556 }
15431557 }
15441558
1545 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
1559 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
15461560
15471561 const gpa = comp.gpa;
15481562
......@@ -1553,7 +1567,7 @@ pub fn updateExports(
15531567 },
15541568 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
15551569 const first_exp = mod.all_exports.items[export_indices[0]];
1556 const res = try self.lowerAnonDecl(value, .none, first_exp.src);
1570 const res = try self.lowerAnonDecl(pt, value, .none, first_exp.src);
15571571 switch (res) {
15581572 .ok => {},
15591573 .fail => |em| {
......@@ -1696,19 +1710,19 @@ fn resolveGlobalSymbol(self: *Coff, current: SymbolWithLoc) !void {
16961710 gop.value_ptr.* = current;
16971711}
16981712
1699pub fn flush(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1713pub fn flush(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
17001714 const comp = self.base.comp;
17011715 const use_lld = build_options.have_llvm and comp.config.use_lld;
17021716 if (use_lld) {
1703 return lld.linkWithLLD(self, arena, prog_node);
1717 return lld.linkWithLLD(self, arena, tid, prog_node);
17041718 }
17051719 switch (comp.config.output_mode) {
1706 .Exe, .Obj => return self.flushModule(arena, prog_node),
1720 .Exe, .Obj => return self.flushModule(arena, tid, prog_node),
17071721 .Lib => return error.TODOImplementWritingLibFiles,
17081722 }
17091723}
17101724
1711pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1725pub fn flushModule(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
17121726 const tracy = trace(@src());
17131727 defer tracy.end();
17141728
......@@ -1723,13 +1737,17 @@ pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
17231737 const sub_prog_node = prog_node.start("COFF Flush", 0);
17241738 defer sub_prog_node.end();
17251739
1726 const module = comp.module orelse return error.LinkingWithoutZigSourceUnimplemented;
1740 const pt: Zcu.PerThread = .{
1741 .zcu = comp.module orelse return error.LinkingWithoutZigSourceUnimplemented,
1742 .tid = tid,
1743 };
17271744
17281745 if (self.lazy_syms.getPtr(.none)) |metadata| {
17291746 // Most lazy symbols can be updated on first use, but
17301747 // anyerror needs to wait for everything to be flushed.
17311748 if (metadata.text_state != .unused) self.updateLazySymbolAtom(
1732 link.File.LazySymbol.initDecl(.code, null, module),
1749 pt,
1750 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
17331751 metadata.text_atom,
17341752 self.text_section_index.?,
17351753 ) catch |err| return switch (err) {
......@@ -1737,7 +1755,8 @@ pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
17371755 else => |e| e,
17381756 };
17391757 if (metadata.rdata_state != .unused) self.updateLazySymbolAtom(
1740 link.File.LazySymbol.initDecl(.const_data, null, module),
1758 pt,
1759 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
17411760 metadata.rdata_atom,
17421761 self.rdata_section_index.?,
17431762 ) catch |err| return switch (err) {
......@@ -1858,6 +1877,7 @@ pub fn getDeclVAddr(self: *Coff, decl_index: InternPool.DeclIndex, reloc_info: l
18581877
18591878pub fn lowerAnonDecl(
18601879 self: *Coff,
1880 pt: Zcu.PerThread,
18611881 decl_val: InternPool.Index,
18621882 explicit_alignment: InternPool.Alignment,
18631883 src_loc: Module.LazySrcLoc,
......@@ -1866,7 +1886,7 @@ pub fn lowerAnonDecl(
18661886 const mod = self.base.comp.module.?;
18671887 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
18681888 const decl_alignment = switch (explicit_alignment) {
1869 .none => ty.abiAlignment(mod),
1889 .none => ty.abiAlignment(pt),
18701890 else => explicit_alignment,
18711891 };
18721892 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -1881,6 +1901,7 @@ pub fn lowerAnonDecl(
18811901 @intFromEnum(decl_val),
18821902 }) catch unreachable;
18831903 const res = self.lowerConst(
1904 pt,
18841905 name,
18851906 val,
18861907 decl_alignment,
src/link/Coff/lld.zig+3-2
......@@ -15,8 +15,9 @@ const Allocator = mem.Allocator;
1515
1616const Coff = @import("../Coff.zig");
1717const Compilation = @import("../../Compilation.zig");
18const Zcu = @import("../../Zcu.zig");
1819
19pub fn linkWithLLD(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) !void {
20pub fn linkWithLLD(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
2021 const tracy = trace(@src());
2122 defer tracy.end();
2223
......@@ -29,7 +30,7 @@ pub fn linkWithLLD(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
2930 // If there is no Zig code to compile, then we should skip flushing the output file because it
3031 // will not be part of the linker line anyway.
3132 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
32 try self.flushModule(arena, prog_node);
33 try self.flushModule(arena, tid, prog_node);
3334
3435 if (fs.path.dirname(full_out_path)) |dirname| {
3536 break :blk try fs.path.join(arena, &.{ dirname, self.base.zcu_object_sub_path.? });
src/link/Dwarf.zig+112-110
......@@ -31,7 +31,7 @@ strtab: StringTable = .{},
3131/// They will end up in the DWARF debug_line header as two lists:
3232/// * []include_directory
3333/// * []file_names
34di_files: std.AutoArrayHashMapUnmanaged(*const Module.File, void) = .{},
34di_files: std.AutoArrayHashMapUnmanaged(*const Zcu.File, void) = .{},
3535
3636global_abbrev_relocs: std.ArrayListUnmanaged(AbbrevRelocation) = .{},
3737
......@@ -67,7 +67,7 @@ const DbgLineHeader = struct {
6767/// Decl's inner Atom is assigned an offset within the DWARF section.
6868pub const DeclState = struct {
6969 dwarf: *Dwarf,
70 mod: *Module,
70 pt: Zcu.PerThread,
7171 di_atom_decls: *const AtomTable,
7272 dbg_line_func: InternPool.Index,
7373 dbg_line: std.ArrayList(u8),
......@@ -113,7 +113,7 @@ pub const DeclState = struct {
113113 .type = ty,
114114 .offset = undefined,
115115 });
116 log.debug("%{d}: {}", .{ sym_index, ty.fmt(self.mod) });
116 log.debug("%{d}: {}", .{ sym_index, ty.fmt(self.pt) });
117117 try self.abbrev_resolver.putNoClobber(gpa, ty.toIntern(), sym_index);
118118 break :blk sym_index;
119119 };
......@@ -128,16 +128,17 @@ pub const DeclState = struct {
128128
129129 fn addDbgInfoType(
130130 self: *DeclState,
131 mod: *Module,
131 pt: Zcu.PerThread,
132132 atom_index: Atom.Index,
133133 ty: Type,
134134 ) error{OutOfMemory}!void {
135 const zcu = pt.zcu;
135136 const dbg_info_buffer = &self.dbg_info;
136 const target = mod.getTarget();
137 const target = zcu.getTarget();
137138 const target_endian = target.cpu.arch.endian();
138 const ip = &mod.intern_pool;
139 const ip = &zcu.intern_pool;
139140
140 switch (ty.zigTypeTag(mod)) {
141 switch (ty.zigTypeTag(zcu)) {
141142 .NoReturn => unreachable,
142143 .Void => {
143144 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
......@@ -148,12 +149,12 @@ pub const DeclState = struct {
148149 // DW.AT.encoding, DW.FORM.data1
149150 dbg_info_buffer.appendAssumeCapacity(DW.ATE.boolean);
150151 // DW.AT.byte_size, DW.FORM.udata
151 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
152 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
152153 // DW.AT.name, DW.FORM.string
153 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
154 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
154155 },
155156 .Int => {
156 const info = ty.intInfo(mod);
157 const info = ty.intInfo(zcu);
157158 try dbg_info_buffer.ensureUnusedCapacity(12);
158159 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
159160 // DW.AT.encoding, DW.FORM.data1
......@@ -162,30 +163,30 @@ pub const DeclState = struct {
162163 .unsigned => DW.ATE.unsigned,
163164 });
164165 // DW.AT.byte_size, DW.FORM.udata
165 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
166 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
166167 // DW.AT.name, DW.FORM.string
167 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
168 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
168169 },
169170 .Optional => {
170 if (ty.isPtrLikeOptional(mod)) {
171 if (ty.isPtrLikeOptional(zcu)) {
171172 try dbg_info_buffer.ensureUnusedCapacity(12);
172173 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
173174 // DW.AT.encoding, DW.FORM.data1
174175 dbg_info_buffer.appendAssumeCapacity(DW.ATE.address);
175176 // DW.AT.byte_size, DW.FORM.udata
176 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
177 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
177178 // DW.AT.name, DW.FORM.string
178 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
179 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
179180 } else {
180181 // Non-pointer optionals are structs: struct { .maybe = *, .val = * }
181 const payload_ty = ty.optionalChild(mod);
182 const payload_ty = ty.optionalChild(zcu);
182183 // DW.AT.structure_type
183184 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
184185 // DW.AT.byte_size, DW.FORM.udata
185 const abi_size = ty.abiSize(mod);
186 const abi_size = ty.abiSize(pt);
186187 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
187188 // DW.AT.name, DW.FORM.string
188 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
189 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
189190 // DW.AT.member
190191 try dbg_info_buffer.ensureUnusedCapacity(21);
191192 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -208,14 +209,14 @@ pub const DeclState = struct {
208209 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
209210 try self.addTypeRelocGlobal(atom_index, payload_ty, @intCast(index));
210211 // DW.AT.data_member_location, DW.FORM.udata
211 const offset = abi_size - payload_ty.abiSize(mod);
212 const offset = abi_size - payload_ty.abiSize(pt);
212213 try leb128.writeUleb128(dbg_info_buffer.writer(), offset);
213214 // DW.AT.structure_type delimit children
214215 try dbg_info_buffer.append(0);
215216 }
216217 },
217218 .Pointer => {
218 if (ty.isSlice(mod)) {
219 if (ty.isSlice(zcu)) {
219220 // Slices are structs: struct { .ptr = *, .len = N }
220221 const ptr_bits = target.ptrBitWidth();
221222 const ptr_bytes: u8 = @intCast(@divExact(ptr_bits, 8));
......@@ -223,9 +224,9 @@ pub const DeclState = struct {
223224 try dbg_info_buffer.ensureUnusedCapacity(2);
224225 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_type));
225226 // DW.AT.byte_size, DW.FORM.udata
226 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
227 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
227228 // DW.AT.name, DW.FORM.string
228 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
229 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
229230 // DW.AT.member
230231 try dbg_info_buffer.ensureUnusedCapacity(21);
231232 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -235,7 +236,7 @@ pub const DeclState = struct {
235236 // DW.AT.type, DW.FORM.ref4
236237 var index = dbg_info_buffer.items.len;
237238 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
238 const ptr_ty = ty.slicePtrFieldType(mod);
239 const ptr_ty = ty.slicePtrFieldType(zcu);
239240 try self.addTypeRelocGlobal(atom_index, ptr_ty, @intCast(index));
240241 // DW.AT.data_member_location, DW.FORM.udata
241242 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -258,19 +259,19 @@ pub const DeclState = struct {
258259 // DW.AT.type, DW.FORM.ref4
259260 const index = dbg_info_buffer.items.len;
260261 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
261 try self.addTypeRelocGlobal(atom_index, ty.childType(mod), @intCast(index));
262 try self.addTypeRelocGlobal(atom_index, ty.childType(zcu), @intCast(index));
262263 }
263264 },
264265 .Array => {
265266 // DW.AT.array_type
266267 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.array_type));
267268 // DW.AT.name, DW.FORM.string
268 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
269 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
269270 // DW.AT.type, DW.FORM.ref4
270271 var index = dbg_info_buffer.items.len;
271272 try dbg_info_buffer.ensureUnusedCapacity(9);
272273 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
273 try self.addTypeRelocGlobal(atom_index, ty.childType(mod), @intCast(index));
274 try self.addTypeRelocGlobal(atom_index, ty.childType(zcu), @intCast(index));
274275 // DW.AT.subrange_type
275276 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.array_dim));
276277 // DW.AT.type, DW.FORM.ref4
......@@ -278,7 +279,7 @@ pub const DeclState = struct {
278279 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
279280 try self.addTypeRelocGlobal(atom_index, Type.usize, @intCast(index));
280281 // DW.AT.count, DW.FORM.udata
281 const len = ty.arrayLenIncludingSentinel(mod);
282 const len = ty.arrayLenIncludingSentinel(pt.zcu);
282283 try leb128.writeUleb128(dbg_info_buffer.writer(), len);
283284 // DW.AT.array_type delimit children
284285 try dbg_info_buffer.append(0);
......@@ -287,13 +288,13 @@ pub const DeclState = struct {
287288 // DW.AT.structure_type
288289 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
289290 // DW.AT.byte_size, DW.FORM.udata
290 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
291 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
291292
292293 blk: {
293294 switch (ip.indexToKey(ty.ip_index)) {
294295 .anon_struct_type => |fields| {
295296 // DW.AT.name, DW.FORM.string
296 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
297 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
297298
298299 for (fields.types.get(ip), 0..) |field_ty, field_index| {
299300 // DW.AT.member
......@@ -305,14 +306,14 @@ pub const DeclState = struct {
305306 try dbg_info_buffer.appendNTimes(0, 4);
306307 try self.addTypeRelocGlobal(atom_index, Type.fromInterned(field_ty), @intCast(index));
307308 // DW.AT.data_member_location, DW.FORM.udata
308 const field_off = ty.structFieldOffset(field_index, mod);
309 const field_off = ty.structFieldOffset(field_index, pt);
309310 try leb128.writeUleb128(dbg_info_buffer.writer(), field_off);
310311 }
311312 },
312313 .struct_type => {
313314 const struct_type = ip.loadStructType(ty.toIntern());
314315 // DW.AT.name, DW.FORM.string
315 try ty.print(dbg_info_buffer.writer(), mod);
316 try ty.print(dbg_info_buffer.writer(), pt);
316317 try dbg_info_buffer.append(0);
317318
318319 if (struct_type.layout == .@"packed") {
......@@ -322,7 +323,7 @@ pub const DeclState = struct {
322323
323324 if (struct_type.isTuple(ip)) {
324325 for (struct_type.field_types.get(ip), struct_type.offsets.get(ip), 0..) |field_ty, field_off, field_index| {
325 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
326 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
326327 // DW.AT.member
327328 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
328329 // DW.AT.name, DW.FORM.string
......@@ -340,7 +341,7 @@ pub const DeclState = struct {
340341 struct_type.field_types.get(ip),
341342 struct_type.offsets.get(ip),
342343 ) |field_name, field_ty, field_off| {
343 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
344 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
344345 const field_name_slice = field_name.toSlice(ip);
345346 // DW.AT.member
346347 try dbg_info_buffer.ensureUnusedCapacity(field_name_slice.len + 2);
......@@ -367,9 +368,9 @@ pub const DeclState = struct {
367368 // DW.AT.enumeration_type
368369 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
369370 // DW.AT.byte_size, DW.FORM.udata
370 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
371 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
371372 // DW.AT.name, DW.FORM.string
372 try ty.print(dbg_info_buffer.writer(), mod);
373 try ty.print(dbg_info_buffer.writer(), pt);
373374 try dbg_info_buffer.append(0);
374375
375376 const enum_type = ip.loadEnumType(ty.ip_index);
......@@ -386,8 +387,8 @@ pub const DeclState = struct {
386387 const value = enum_type.values.get(ip)[field_i];
387388 // TODO do not assume a 64bit enum value - could be bigger.
388389 // See https://github.com/ziglang/zig/issues/645
389 const field_int_val = try Value.fromInterned(value).intFromEnum(ty, mod);
390 break :value @bitCast(field_int_val.toSignedInt(mod));
390 const field_int_val = try Value.fromInterned(value).intFromEnum(ty, pt);
391 break :value @bitCast(field_int_val.toSignedInt(pt));
391392 };
392393 mem.writeInt(u64, dbg_info_buffer.addManyAsArrayAssumeCapacity(8), value, target_endian);
393394 }
......@@ -396,8 +397,8 @@ pub const DeclState = struct {
396397 try dbg_info_buffer.append(0);
397398 },
398399 .Union => {
399 const union_obj = mod.typeToUnion(ty).?;
400 const layout = mod.getUnionLayout(union_obj);
400 const union_obj = zcu.typeToUnion(ty).?;
401 const layout = pt.getUnionLayout(union_obj);
401402 const payload_offset = if (layout.tag_align.compare(.gte, layout.payload_align)) layout.tag_size else 0;
402403 const tag_offset = if (layout.tag_align.compare(.gte, layout.payload_align)) 0 else layout.payload_size;
403404 // TODO this is temporary to match current state of unions in Zig - we don't yet have
......@@ -410,7 +411,7 @@ pub const DeclState = struct {
410411 // DW.AT.byte_size, DW.FORM.udata
411412 try leb128.writeUleb128(dbg_info_buffer.writer(), layout.abi_size);
412413 // DW.AT.name, DW.FORM.string
413 try ty.print(dbg_info_buffer.writer(), mod);
414 try ty.print(dbg_info_buffer.writer(), pt);
414415 try dbg_info_buffer.append(0);
415416
416417 // DW.AT.member
......@@ -435,12 +436,12 @@ pub const DeclState = struct {
435436 if (is_tagged) {
436437 try dbg_info_buffer.writer().print("AnonUnion\x00", .{});
437438 } else {
438 try ty.print(dbg_info_buffer.writer(), mod);
439 try ty.print(dbg_info_buffer.writer(), pt);
439440 try dbg_info_buffer.append(0);
440441 }
441442
442443 for (union_obj.field_types.get(ip), union_obj.loadTagType(ip).names.get(ip)) |field_ty, field_name| {
443 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
444 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
444445 const field_name_slice = field_name.toSlice(ip);
445446 // DW.AT.member
446447 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
......@@ -474,25 +475,25 @@ pub const DeclState = struct {
474475 try dbg_info_buffer.append(0);
475476 }
476477 },
477 .ErrorSet => try addDbgInfoErrorSet(mod, ty, target, &self.dbg_info),
478 .ErrorSet => try addDbgInfoErrorSet(pt, ty, target, &self.dbg_info),
478479 .ErrorUnion => {
479 const error_ty = ty.errorUnionSet(mod);
480 const payload_ty = ty.errorUnionPayload(mod);
481 const payload_align = if (payload_ty.isNoReturn(mod)) .none else payload_ty.abiAlignment(mod);
482 const error_align = Type.anyerror.abiAlignment(mod);
483 const abi_size = ty.abiSize(mod);
484 const payload_off = if (error_align.compare(.gte, payload_align)) Type.anyerror.abiSize(mod) else 0;
485 const error_off = if (error_align.compare(.gte, payload_align)) 0 else payload_ty.abiSize(mod);
480 const error_ty = ty.errorUnionSet(zcu);
481 const payload_ty = ty.errorUnionPayload(zcu);
482 const payload_align = if (payload_ty.isNoReturn(zcu)) .none else payload_ty.abiAlignment(pt);
483 const error_align = Type.anyerror.abiAlignment(pt);
484 const abi_size = ty.abiSize(pt);
485 const payload_off = if (error_align.compare(.gte, payload_align)) Type.anyerror.abiSize(pt) else 0;
486 const error_off = if (error_align.compare(.gte, payload_align)) 0 else payload_ty.abiSize(pt);
486487
487488 // DW.AT.structure_type
488489 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
489490 // DW.AT.byte_size, DW.FORM.udata
490491 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
491492 // DW.AT.name, DW.FORM.string
492 try ty.print(dbg_info_buffer.writer(), mod);
493 try ty.print(dbg_info_buffer.writer(), pt);
493494 try dbg_info_buffer.append(0);
494495
495 if (!payload_ty.isNoReturn(mod)) {
496 if (!payload_ty.isNoReturn(zcu)) {
496497 // DW.AT.member
497498 try dbg_info_buffer.ensureUnusedCapacity(11);
498499 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -526,7 +527,7 @@ pub const DeclState = struct {
526527 try dbg_info_buffer.append(0);
527528 },
528529 else => {
529 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(self.mod)});
530 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(pt)});
530531 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
531532 },
532533 }
......@@ -555,6 +556,7 @@ pub const DeclState = struct {
555556 owner_decl: InternPool.DeclIndex,
556557 loc: DbgInfoLoc,
557558 ) error{OutOfMemory}!void {
559 const pt = self.pt;
558560 const dbg_info = &self.dbg_info;
559561 const atom_index = self.di_atom_decls.get(owner_decl).?;
560562 const name_with_null = name.ptr[0 .. name.len + 1];
......@@ -580,9 +582,9 @@ pub const DeclState = struct {
580582 }
581583 },
582584 .register_pair => |regs| {
583 const reg_bits = self.mod.getTarget().ptrBitWidth();
585 const reg_bits = pt.zcu.getTarget().ptrBitWidth();
584586 const reg_bytes: u8 = @intCast(@divExact(reg_bits, 8));
585 const abi_size = ty.abiSize(self.mod);
587 const abi_size = ty.abiSize(pt);
586588 try dbg_info.ensureUnusedCapacity(10);
587589 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevCode.parameter));
588590 // DW.AT.location, DW.FORM.exprloc
......@@ -675,10 +677,10 @@ pub const DeclState = struct {
675677 const name_with_null = name.ptr[0 .. name.len + 1];
676678 try dbg_info.append(@intFromEnum(AbbrevCode.variable));
677679 const gpa = self.dwarf.allocator;
678 const mod = self.mod;
679 const target = mod.getTarget();
680 const pt = self.pt;
681 const target = pt.zcu.getTarget();
680682 const endian = target.cpu.arch.endian();
681 const child_ty = if (is_ptr) ty.childType(mod) else ty;
683 const child_ty = if (is_ptr) ty.childType(pt.zcu) else ty;
682684
683685 switch (loc) {
684686 .register => |reg| {
......@@ -701,9 +703,9 @@ pub const DeclState = struct {
701703 },
702704
703705 .register_pair => |regs| {
704 const reg_bits = self.mod.getTarget().ptrBitWidth();
706 const reg_bits = pt.zcu.getTarget().ptrBitWidth();
705707 const reg_bytes: u8 = @intCast(@divExact(reg_bits, 8));
706 const abi_size = child_ty.abiSize(self.mod);
708 const abi_size = child_ty.abiSize(pt);
707709 try dbg_info.ensureUnusedCapacity(9);
708710 // DW.AT.location, DW.FORM.exprloc
709711 var expr_len = std.io.countingWriter(std.io.null_writer);
......@@ -829,9 +831,9 @@ pub const DeclState = struct {
829831 const fixup = dbg_info.items.len;
830832 dbg_info.appendSliceAssumeCapacity(&[2]u8{ // DW.AT.location, DW.FORM.exprloc
831833 1,
832 if (child_ty.isSignedInt(mod)) DW.OP.consts else DW.OP.constu,
834 if (child_ty.isSignedInt(pt.zcu)) DW.OP.consts else DW.OP.constu,
833835 });
834 if (child_ty.isSignedInt(mod)) {
836 if (child_ty.isSignedInt(pt.zcu)) {
835837 try leb128.writeIleb128(dbg_info.writer(), @as(i64, @bitCast(x)));
836838 } else {
837839 try leb128.writeUleb128(dbg_info.writer(), x);
......@@ -844,7 +846,7 @@ pub const DeclState = struct {
844846 // DW.AT.location, DW.FORM.exprloc
845847 // uleb128(exprloc_len)
846848 // DW.OP.implicit_value uleb128(len_of_bytes) bytes
847 const abi_size: u32 = @intCast(child_ty.abiSize(mod));
849 const abi_size: u32 = @intCast(child_ty.abiSize(self.pt));
848850 var implicit_value_len = std.ArrayList(u8).init(gpa);
849851 defer implicit_value_len.deinit();
850852 try leb128.writeUleb128(implicit_value_len.writer(), abi_size);
......@@ -934,22 +936,23 @@ pub const DeclState = struct {
934936 }
935937
936938 pub fn setInlineFunc(self: *DeclState, func: InternPool.Index) error{OutOfMemory}!void {
939 const zcu = self.pt.zcu;
937940 if (self.dbg_line_func == func) return;
938941
939942 try self.dbg_line.ensureUnusedCapacity((1 + 4) + (1 + 5));
940943
941 const old_func_info = self.mod.funcInfo(self.dbg_line_func);
942 const new_func_info = self.mod.funcInfo(func);
944 const old_func_info = zcu.funcInfo(self.dbg_line_func);
945 const new_func_info = zcu.funcInfo(func);
943946
944 const old_file = try self.dwarf.addDIFile(self.mod, old_func_info.owner_decl);
945 const new_file = try self.dwarf.addDIFile(self.mod, new_func_info.owner_decl);
947 const old_file = try self.dwarf.addDIFile(zcu, old_func_info.owner_decl);
948 const new_file = try self.dwarf.addDIFile(zcu, new_func_info.owner_decl);
946949 if (old_file != new_file) {
947950 self.dbg_line.appendAssumeCapacity(DW.LNS.set_file);
948951 leb128.writeUnsignedFixed(4, self.dbg_line.addManyAsArrayAssumeCapacity(4), new_file);
949952 }
950953
951 const old_src_line: i33 = self.mod.declPtr(old_func_info.owner_decl).navSrcLine(self.mod);
952 const new_src_line: i33 = self.mod.declPtr(new_func_info.owner_decl).navSrcLine(self.mod);
954 const old_src_line: i33 = zcu.declPtr(old_func_info.owner_decl).navSrcLine(zcu);
955 const new_src_line: i33 = zcu.declPtr(new_func_info.owner_decl).navSrcLine(zcu);
953956 if (new_src_line != old_src_line) {
954957 self.dbg_line.appendAssumeCapacity(DW.LNS.advance_line);
955958 leb128.writeSignedFixed(5, self.dbg_line.addManyAsArrayAssumeCapacity(5), new_src_line - old_src_line);
......@@ -1074,19 +1077,19 @@ pub fn deinit(self: *Dwarf) void {
10741077
10751078/// Initializes Decl's state and its matching output buffers.
10761079/// Call this before `commitDeclState`.
1077pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !DeclState {
1080pub fn initDeclState(self: *Dwarf, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !DeclState {
10781081 const tracy = trace(@src());
10791082 defer tracy.end();
10801083
1081 const decl = mod.declPtr(decl_index);
1082 const decl_linkage_name = try decl.fullyQualifiedName(mod);
1084 const decl = pt.zcu.declPtr(decl_index);
1085 const decl_linkage_name = try decl.fullyQualifiedName(pt.zcu);
10831086
1084 log.debug("initDeclState {}{*}", .{ decl_linkage_name.fmt(&mod.intern_pool), decl });
1087 log.debug("initDeclState {}{*}", .{ decl_linkage_name.fmt(&pt.zcu.intern_pool), decl });
10851088
10861089 const gpa = self.allocator;
10871090 var decl_state: DeclState = .{
10881091 .dwarf = self,
1089 .mod = mod,
1092 .pt = pt,
10901093 .di_atom_decls = &self.di_atom_decls,
10911094 .dbg_line_func = undefined,
10921095 .dbg_line = std.ArrayList(u8).init(gpa),
......@@ -1105,7 +1108,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11051108
11061109 assert(decl.has_tv);
11071110
1108 switch (decl.typeOf(mod).zigTypeTag(mod)) {
1111 switch (decl.typeOf(pt.zcu).zigTypeTag(pt.zcu)) {
11091112 .Fn => {
11101113 _ = try self.getOrCreateAtomForDecl(.src_fn, decl_index);
11111114
......@@ -1114,13 +1117,13 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11141117 try dbg_line_buffer.ensureTotalCapacity((3 + ptr_width_bytes) + (1 + 4) + (1 + 4) + (1 + 5) + 1);
11151118
11161119 decl_state.dbg_line_func = decl.val.toIntern();
1117 const func = decl.val.getFunction(mod).?;
1120 const func = decl.val.getFunction(pt.zcu).?;
11181121 log.debug("decl.src_line={d}, func.lbrace_line={d}, func.rbrace_line={d}", .{
1119 decl.navSrcLine(mod),
1122 decl.navSrcLine(pt.zcu),
11201123 func.lbrace_line,
11211124 func.rbrace_line,
11221125 });
1123 const line: u28 = @intCast(decl.navSrcLine(mod) + func.lbrace_line);
1126 const line: u28 = @intCast(decl.navSrcLine(pt.zcu) + func.lbrace_line);
11241127
11251128 dbg_line_buffer.appendSliceAssumeCapacity(&.{
11261129 DW.LNS.extended_op,
......@@ -1142,7 +1145,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11421145 assert(self.getRelocDbgFileIndex() == dbg_line_buffer.items.len);
11431146 // Once we support more than one source file, this will have the ability to be more
11441147 // than one possible value.
1145 const file_index = try self.addDIFile(mod, decl_index);
1148 const file_index = try self.addDIFile(pt.zcu, decl_index);
11461149 leb128.writeUnsignedFixed(4, dbg_line_buffer.addManyAsArrayAssumeCapacity(4), file_index);
11471150
11481151 dbg_line_buffer.appendAssumeCapacity(DW.LNS.set_column);
......@@ -1153,13 +1156,13 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11531156 dbg_line_buffer.appendAssumeCapacity(DW.LNS.copy);
11541157
11551158 // .debug_info subprogram
1156 const decl_name_slice = decl.name.toSlice(&mod.intern_pool);
1157 const decl_linkage_name_slice = decl_linkage_name.toSlice(&mod.intern_pool);
1159 const decl_name_slice = decl.name.toSlice(&pt.zcu.intern_pool);
1160 const decl_linkage_name_slice = decl_linkage_name.toSlice(&pt.zcu.intern_pool);
11581161 try dbg_info_buffer.ensureUnusedCapacity(1 + ptr_width_bytes + 4 + 4 +
11591162 (decl_name_slice.len + 1) + (decl_linkage_name_slice.len + 1));
11601163
1161 const fn_ret_type = decl.typeOf(mod).fnReturnType(mod);
1162 const fn_ret_has_bits = fn_ret_type.hasRuntimeBits(mod);
1164 const fn_ret_type = decl.typeOf(pt.zcu).fnReturnType(pt.zcu);
1165 const fn_ret_has_bits = fn_ret_type.hasRuntimeBits(pt);
11631166 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(
11641167 @as(AbbrevCode, if (fn_ret_has_bits) .subprogram else .subprogram_retvoid),
11651168 ));
......@@ -1191,7 +1194,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11911194
11921195pub fn commitDeclState(
11931196 self: *Dwarf,
1194 zcu: *Module,
1197 pt: Zcu.PerThread,
11951198 decl_index: InternPool.DeclIndex,
11961199 sym_addr: u64,
11971200 sym_size: u64,
......@@ -1201,6 +1204,7 @@ pub fn commitDeclState(
12011204 defer tracy.end();
12021205
12031206 const gpa = self.allocator;
1207 const zcu = pt.zcu;
12041208 const decl = zcu.declPtr(decl_index);
12051209 const ip = &zcu.intern_pool;
12061210 const namespace = zcu.namespacePtr(decl.src_namespace);
......@@ -1432,7 +1436,7 @@ pub fn commitDeclState(
14321436 if (ip.isErrorSetType(ty.toIntern())) continue;
14331437
14341438 symbol.offset = @intCast(dbg_info_buffer.items.len);
1435 try decl_state.addDbgInfoType(zcu, di_atom_index, ty);
1439 try decl_state.addDbgInfoType(pt, di_atom_index, ty);
14361440 }
14371441 }
14381442
......@@ -1457,7 +1461,7 @@ pub fn commitDeclState(
14571461 reloc.offset,
14581462 value,
14591463 reloc_target,
1460 ty.fmt(zcu),
1464 ty.fmt(pt),
14611465 });
14621466 mem.writeInt(
14631467 u32,
......@@ -1691,7 +1695,7 @@ fn writeDeclDebugInfo(self: *Dwarf, atom_index: Atom.Index, dbg_info_buf: []cons
16911695 }
16921696}
16931697
1694pub fn updateDeclLineNumber(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1698pub fn updateDeclLineNumber(self: *Dwarf, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
16951699 const tracy = trace(@src());
16961700 defer tracy.end();
16971701
......@@ -1699,14 +1703,14 @@ pub fn updateDeclLineNumber(self: *Dwarf, mod: *Module, decl_index: InternPool.D
16991703 const atom = self.getAtom(.src_fn, atom_index);
17001704 if (atom.len == 0) return;
17011705
1702 const decl = mod.declPtr(decl_index);
1703 const func = decl.val.getFunction(mod).?;
1706 const decl = zcu.declPtr(decl_index);
1707 const func = decl.val.getFunction(zcu).?;
17041708 log.debug("decl.src_line={d}, func.lbrace_line={d}, func.rbrace_line={d}", .{
1705 decl.navSrcLine(mod),
1709 decl.navSrcLine(zcu),
17061710 func.lbrace_line,
17071711 func.rbrace_line,
17081712 });
1709 const line: u28 = @intCast(decl.navSrcLine(mod) + func.lbrace_line);
1713 const line: u28 = @intCast(decl.navSrcLine(zcu) + func.lbrace_line);
17101714 var data: [4]u8 = undefined;
17111715 leb128.writeUnsignedFixed(4, &data, line);
17121716
......@@ -1969,7 +1973,7 @@ fn dbgInfoHeaderBytes(self: *Dwarf) usize {
19691973 return 120;
19701974}
19711975
1972pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64) !void {
1976pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Zcu, low_pc: u64, high_pc: u64) !void {
19731977 // If this value is null it means there is an error in the module;
19741978 // leave debug_info_header_dirty=true.
19751979 const first_dbg_info_off = self.getDebugInfoOff() orelse return;
......@@ -2058,14 +2062,14 @@ pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64)
20582062 }
20592063}
20602064
2061fn resolveCompilationDir(module: *Module, buffer: *[std.fs.max_path_bytes]u8) []const u8 {
2065fn resolveCompilationDir(zcu: *Zcu, buffer: *[std.fs.max_path_bytes]u8) []const u8 {
20622066 // We fully resolve all paths at this point to avoid lack of source line info in stack
20632067 // traces or lack of debugging information which, if relative paths were used, would
20642068 // be very location dependent.
20652069 // TODO: the only concern I have with this is WASI as either host or target, should
20662070 // we leave the paths as relative then?
2067 const root_dir_path = module.root_mod.root.root_dir.path orelse ".";
2068 const sub_path = module.root_mod.root.sub_path;
2071 const root_dir_path = zcu.root_mod.root.root_dir.path orelse ".";
2072 const sub_path = zcu.root_mod.root.sub_path;
20692073 const realpath = if (std.fs.path.isAbsolute(root_dir_path)) r: {
20702074 @memcpy(buffer[0..root_dir_path.len], root_dir_path);
20712075 break :r root_dir_path;
......@@ -2682,7 +2686,7 @@ fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
26822686 return actual_size +| (actual_size / ideal_factor);
26832687}
26842688
2685pub fn flushModule(self: *Dwarf, module: *Module) !void {
2689pub fn flushModule(self: *Dwarf, pt: Zcu.PerThread) !void {
26862690 const comp = self.bin_file.comp;
26872691 const target = comp.root_mod.resolved_target.result;
26882692
......@@ -2694,9 +2698,9 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
26942698
26952699 var dbg_info_buffer = std.ArrayList(u8).init(arena);
26962700 try addDbgInfoErrorSetNames(
2697 module,
2701 pt,
26982702 Type.anyerror,
2699 module.global_error_set.keys(),
2703 pt.zcu.global_error_set.keys(),
27002704 target,
27012705 &dbg_info_buffer,
27022706 );
......@@ -2759,9 +2763,9 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
27592763 }
27602764}
27612765
2762fn addDIFile(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !u28 {
2763 const decl = mod.declPtr(decl_index);
2764 const file_scope = decl.getFileScope(mod);
2766fn addDIFile(self: *Dwarf, zcu: *Zcu, decl_index: InternPool.DeclIndex) !u28 {
2767 const decl = zcu.declPtr(decl_index);
2768 const file_scope = decl.getFileScope(zcu);
27652769 const gop = try self.di_files.getOrPut(self.allocator, file_scope);
27662770 if (!gop.found_existing) {
27672771 switch (self.bin_file.tag) {
......@@ -2827,16 +2831,16 @@ fn genIncludeDirsAndFileNames(self: *Dwarf, arena: Allocator) !struct {
28272831}
28282832
28292833fn addDbgInfoErrorSet(
2830 mod: *Module,
2834 pt: Zcu.PerThread,
28312835 ty: Type,
28322836 target: std.Target,
28332837 dbg_info_buffer: *std.ArrayList(u8),
28342838) !void {
2835 return addDbgInfoErrorSetNames(mod, ty, ty.errorSetNames(mod).get(&mod.intern_pool), target, dbg_info_buffer);
2839 return addDbgInfoErrorSetNames(pt, ty, ty.errorSetNames(pt.zcu).get(&pt.zcu.intern_pool), target, dbg_info_buffer);
28362840}
28372841
28382842fn addDbgInfoErrorSetNames(
2839 mod: *Module,
2843 pt: Zcu.PerThread,
28402844 /// Used for printing the type name only.
28412845 ty: Type,
28422846 error_names: []const InternPool.NullTerminatedString,
......@@ -2848,10 +2852,10 @@ fn addDbgInfoErrorSetNames(
28482852 // DW.AT.enumeration_type
28492853 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
28502854 // DW.AT.byte_size, DW.FORM.udata
2851 const abi_size = Type.anyerror.abiSize(mod);
2855 const abi_size = Type.anyerror.abiSize(pt);
28522856 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
28532857 // DW.AT.name, DW.FORM.string
2854 try ty.print(dbg_info_buffer.writer(), mod);
2858 try ty.print(dbg_info_buffer.writer(), pt);
28552859 try dbg_info_buffer.append(0);
28562860
28572861 // DW.AT.enumerator
......@@ -2865,8 +2869,8 @@ fn addDbgInfoErrorSetNames(
28652869 mem.writeInt(u64, dbg_info_buffer.addManyAsArrayAssumeCapacity(8), 0, target_endian);
28662870
28672871 for (error_names) |error_name| {
2868 const int = try mod.getErrorValue(error_name);
2869 const error_name_slice = error_name.toSlice(&mod.intern_pool);
2872 const int = try pt.zcu.getErrorValue(error_name);
2873 const error_name_slice = error_name.toSlice(&pt.zcu.intern_pool);
28702874 // DW.AT.enumerator
28712875 try dbg_info_buffer.ensureUnusedCapacity(error_name_slice.len + 2 + @sizeOf(u64));
28722876 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.enum_variant));
......@@ -2965,8 +2969,6 @@ const LinkBlock = File.LinkBlock;
29652969const LinkFn = File.LinkFn;
29662970const LinkerLoad = @import("../codegen.zig").LinkerLoad;
29672971const Zcu = @import("../Zcu.zig");
2968/// Deprecated.
2969const Module = Zcu;
29702972const InternPool = @import("../InternPool.zig");
29712973const StringTable = @import("StringTable.zig");
29722974const Type = @import("../Type.zig");
src/link/Elf.zig+20-19
......@@ -550,11 +550,12 @@ pub fn getDeclVAddr(self: *Elf, decl_index: InternPool.DeclIndex, reloc_info: li
550550
551551pub fn lowerAnonDecl(
552552 self: *Elf,
553 pt: Zcu.PerThread,
553554 decl_val: InternPool.Index,
554555 explicit_alignment: InternPool.Alignment,
555556 src_loc: Module.LazySrcLoc,
556557) !codegen.Result {
557 return self.zigObjectPtr().?.lowerAnonDecl(self, decl_val, explicit_alignment, src_loc);
558 return self.zigObjectPtr().?.lowerAnonDecl(self, pt, decl_val, explicit_alignment, src_loc);
558559}
559560
560561pub fn getAnonDeclVAddr(self: *Elf, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
......@@ -1064,15 +1065,15 @@ pub fn markDirty(self: *Elf, shdr_index: u32) void {
10641065 }
10651066}
10661067
1067pub fn flush(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1068pub fn flush(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
10681069 const use_lld = build_options.have_llvm and self.base.comp.config.use_lld;
10691070 if (use_lld) {
1070 return self.linkWithLLD(arena, prog_node);
1071 return self.linkWithLLD(arena, tid, prog_node);
10711072 }
1072 try self.flushModule(arena, prog_node);
1073 try self.flushModule(arena, tid, prog_node);
10731074}
10741075
1075pub fn flushModule(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1076pub fn flushModule(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
10761077 const tracy = trace(@src());
10771078 defer tracy.end();
10781079
......@@ -1103,7 +1104,7 @@ pub fn flushModule(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) l
11031104 // --verbose-link
11041105 if (comp.verbose_link) try self.dumpArgv(comp);
11051106
1106 if (self.zigObjectPtr()) |zig_object| try zig_object.flushModule(self);
1107 if (self.zigObjectPtr()) |zig_object| try zig_object.flushModule(self, tid);
11071108 if (self.base.isStaticLib()) return relocatable.flushStaticLib(self, comp, module_obj_path);
11081109 if (self.base.isObject()) return relocatable.flushObject(self, comp, module_obj_path);
11091110
......@@ -2146,7 +2147,7 @@ fn scanRelocs(self: *Elf) !void {
21462147 }
21472148}
21482149
2149fn linkWithLLD(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) !void {
2150fn linkWithLLD(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
21502151 const tracy = trace(@src());
21512152 defer tracy.end();
21522153
......@@ -2159,7 +2160,7 @@ fn linkWithLLD(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) !void
21592160 // If there is no Zig code to compile, then we should skip flushing the output file because it
21602161 // will not be part of the linker line anyway.
21612162 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
2162 try self.flushModule(arena, prog_node);
2163 try self.flushModule(arena, tid, prog_node);
21632164
21642165 if (fs.path.dirname(full_out_path)) |dirname| {
21652166 break :blk try fs.path.join(arena, &.{ dirname, self.base.zcu_object_sub_path.? });
......@@ -2983,41 +2984,41 @@ pub fn freeDecl(self: *Elf, decl_index: InternPool.DeclIndex) void {
29832984 return self.zigObjectPtr().?.freeDecl(self, decl_index);
29842985}
29852986
2986pub fn updateFunc(self: *Elf, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
2987pub fn updateFunc(self: *Elf, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
29872988 if (build_options.skip_non_native and builtin.object_format != .elf) {
29882989 @panic("Attempted to compile for object format that was disabled by build configuration");
29892990 }
2990 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
2991 return self.zigObjectPtr().?.updateFunc(self, mod, func_index, air, liveness);
2991 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
2992 return self.zigObjectPtr().?.updateFunc(self, pt, func_index, air, liveness);
29922993}
29932994
29942995pub fn updateDecl(
29952996 self: *Elf,
2996 mod: *Module,
2997 pt: Zcu.PerThread,
29972998 decl_index: InternPool.DeclIndex,
29982999) link.File.UpdateDeclError!void {
29993000 if (build_options.skip_non_native and builtin.object_format != .elf) {
30003001 @panic("Attempted to compile for object format that was disabled by build configuration");
30013002 }
3002 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
3003 return self.zigObjectPtr().?.updateDecl(self, mod, decl_index);
3003 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
3004 return self.zigObjectPtr().?.updateDecl(self, pt, decl_index);
30043005}
30053006
3006pub fn lowerUnnamedConst(self: *Elf, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3007 return self.zigObjectPtr().?.lowerUnnamedConst(self, val, decl_index);
3007pub fn lowerUnnamedConst(self: *Elf, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3008 return self.zigObjectPtr().?.lowerUnnamedConst(self, pt, val, decl_index);
30083009}
30093010
30103011pub fn updateExports(
30113012 self: *Elf,
3012 mod: *Module,
3013 pt: Zcu.PerThread,
30133014 exported: Module.Exported,
30143015 export_indices: []const u32,
30153016) link.File.UpdateExportsError!void {
30163017 if (build_options.skip_non_native and builtin.object_format != .elf) {
30173018 @panic("Attempted to compile for object format that was disabled by build configuration");
30183019 }
3019 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
3020 return self.zigObjectPtr().?.updateExports(self, mod, exported, export_indices);
3020 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
3021 return self.zigObjectPtr().?.updateExports(self, pt, exported, export_indices);
30213022}
30223023
30233024pub fn updateDeclLineNumber(self: *Elf, mod: *Module, decl_index: InternPool.DeclIndex) !void {
src/link/Elf/ZigObject.zig+60-55
......@@ -158,16 +158,17 @@ pub fn deinit(self: *ZigObject, allocator: Allocator) void {
158158 }
159159}
160160
161pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
161pub fn flushModule(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !void {
162162 // Handle any lazy symbols that were emitted by incremental compilation.
163163 if (self.lazy_syms.getPtr(.none)) |metadata| {
164 const zcu = elf_file.base.comp.module.?;
164 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.module.?, .tid = tid };
165165
166166 // Most lazy symbols can be updated on first use, but
167167 // anyerror needs to wait for everything to be flushed.
168168 if (metadata.text_state != .unused) self.updateLazySymbol(
169169 elf_file,
170 link.File.LazySymbol.initDecl(.code, null, zcu),
170 pt,
171 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
171172 metadata.text_symbol_index,
172173 ) catch |err| return switch (err) {
173174 error.CodegenFail => error.FlushFailure,
......@@ -175,7 +176,8 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
175176 };
176177 if (metadata.rodata_state != .unused) self.updateLazySymbol(
177178 elf_file,
178 link.File.LazySymbol.initDecl(.const_data, null, zcu),
179 pt,
180 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
179181 metadata.rodata_symbol_index,
180182 ) catch |err| return switch (err) {
181183 error.CodegenFail => error.FlushFailure,
......@@ -188,8 +190,8 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
188190 }
189191
190192 if (self.dwarf) |*dw| {
191 const zcu = elf_file.base.comp.module.?;
192 try dw.flushModule(zcu);
193 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.module.?, .tid = tid };
194 try dw.flushModule(pt);
193195
194196 // TODO I need to re-think how to handle ZigObject's debug sections AND debug sections
195197 // extracted from input object files correctly.
......@@ -202,7 +204,7 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
202204 const text_shdr = elf_file.shdrs.items[elf_file.zig_text_section_index.?];
203205 const low_pc = text_shdr.sh_addr;
204206 const high_pc = text_shdr.sh_addr + text_shdr.sh_size;
205 try dw.writeDbgInfoHeader(zcu, low_pc, high_pc);
207 try dw.writeDbgInfoHeader(pt.zcu, low_pc, high_pc);
206208 self.debug_info_header_dirty = false;
207209 }
208210
......@@ -684,6 +686,7 @@ pub fn getAnonDeclVAddr(
684686pub fn lowerAnonDecl(
685687 self: *ZigObject,
686688 elf_file: *Elf,
689 pt: Zcu.PerThread,
687690 decl_val: InternPool.Index,
688691 explicit_alignment: InternPool.Alignment,
689692 src_loc: Module.LazySrcLoc,
......@@ -692,7 +695,7 @@ pub fn lowerAnonDecl(
692695 const mod = elf_file.base.comp.module.?;
693696 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
694697 const decl_alignment = switch (explicit_alignment) {
695 .none => ty.abiAlignment(mod),
698 .none => ty.abiAlignment(pt),
696699 else => explicit_alignment,
697700 };
698701 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -708,6 +711,7 @@ pub fn lowerAnonDecl(
708711 }) catch unreachable;
709712 const res = self.lowerConst(
710713 elf_file,
714 pt,
711715 name,
712716 val,
713717 decl_alignment,
......@@ -733,10 +737,11 @@ pub fn lowerAnonDecl(
733737pub fn getOrCreateMetadataForLazySymbol(
734738 self: *ZigObject,
735739 elf_file: *Elf,
740 pt: Zcu.PerThread,
736741 lazy_sym: link.File.LazySymbol,
737742) !Symbol.Index {
738 const gpa = elf_file.base.comp.gpa;
739 const mod = elf_file.base.comp.module.?;
743 const mod = pt.zcu;
744 const gpa = mod.gpa;
740745 const gop = try self.lazy_syms.getOrPut(gpa, lazy_sym.getDecl(mod));
741746 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
742747 if (!gop.found_existing) gop.value_ptr.* = .{};
......@@ -766,7 +771,7 @@ pub fn getOrCreateMetadataForLazySymbol(
766771 metadata.state.* = .pending_flush;
767772 const symbol_index = metadata.symbol_index.*;
768773 // anyerror needs to be deferred until flushModule
769 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(elf_file, lazy_sym, symbol_index);
774 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(elf_file, pt, lazy_sym, symbol_index);
770775 return symbol_index;
771776}
772777
......@@ -893,6 +898,7 @@ fn getDeclShdrIndex(
893898fn updateDeclCode(
894899 self: *ZigObject,
895900 elf_file: *Elf,
901 pt: Zcu.PerThread,
896902 decl_index: InternPool.DeclIndex,
897903 sym_index: Symbol.Index,
898904 shdr_index: u32,
......@@ -900,13 +906,13 @@ fn updateDeclCode(
900906 stt_bits: u8,
901907) !void {
902908 const gpa = elf_file.base.comp.gpa;
903 const mod = elf_file.base.comp.module.?;
909 const mod = pt.zcu;
904910 const decl = mod.declPtr(decl_index);
905911 const decl_name = try decl.fullyQualifiedName(mod);
906912
907913 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
908914
909 const required_alignment = decl.getAlignment(mod).max(
915 const required_alignment = decl.getAlignment(pt).max(
910916 target_util.minFunctionAlignment(mod.getTarget()),
911917 );
912918
......@@ -994,19 +1000,20 @@ fn updateDeclCode(
9941000fn updateTlv(
9951001 self: *ZigObject,
9961002 elf_file: *Elf,
1003 pt: Zcu.PerThread,
9971004 decl_index: InternPool.DeclIndex,
9981005 sym_index: Symbol.Index,
9991006 shndx: u32,
10001007 code: []const u8,
10011008) !void {
1002 const gpa = elf_file.base.comp.gpa;
1003 const mod = elf_file.base.comp.module.?;
1009 const mod = pt.zcu;
1010 const gpa = mod.gpa;
10041011 const decl = mod.declPtr(decl_index);
10051012 const decl_name = try decl.fullyQualifiedName(mod);
10061013
10071014 log.debug("updateTlv {} ({*})", .{ decl_name.fmt(&mod.intern_pool), decl });
10081015
1009 const required_alignment = decl.getAlignment(mod);
1016 const required_alignment = decl.getAlignment(pt);
10101017
10111018 const sym = elf_file.symbol(sym_index);
10121019 const esym = &self.local_esyms.items(.elf_sym)[sym.esym_index];
......@@ -1048,7 +1055,7 @@ fn updateTlv(
10481055pub fn updateFunc(
10491056 self: *ZigObject,
10501057 elf_file: *Elf,
1051 mod: *Module,
1058 pt: Zcu.PerThread,
10521059 func_index: InternPool.Index,
10531060 air: Air,
10541061 liveness: Liveness,
......@@ -1056,6 +1063,7 @@ pub fn updateFunc(
10561063 const tracy = trace(@src());
10571064 defer tracy.end();
10581065
1066 const mod = pt.zcu;
10591067 const gpa = elf_file.base.comp.gpa;
10601068 const func = mod.funcInfo(func_index);
10611069 const decl_index = func.owner_decl;
......@@ -1068,29 +1076,19 @@ pub fn updateFunc(
10681076 var code_buffer = std.ArrayList(u8).init(gpa);
10691077 defer code_buffer.deinit();
10701078
1071 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
1079 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
10721080 defer if (decl_state) |*ds| ds.deinit();
10731081
1074 const res = if (decl_state) |*ds|
1075 try codegen.generateFunction(
1076 &elf_file.base,
1077 decl.navSrcLoc(mod),
1078 func_index,
1079 air,
1080 liveness,
1081 &code_buffer,
1082 .{ .dwarf = ds },
1083 )
1084 else
1085 try codegen.generateFunction(
1086 &elf_file.base,
1087 decl.navSrcLoc(mod),
1088 func_index,
1089 air,
1090 liveness,
1091 &code_buffer,
1092 .none,
1093 );
1082 const res = try codegen.generateFunction(
1083 &elf_file.base,
1084 pt,
1085 decl.navSrcLoc(mod),
1086 func_index,
1087 air,
1088 liveness,
1089 &code_buffer,
1090 if (decl_state) |*ds| .{ .dwarf = ds } else .none,
1091 );
10941092
10951093 const code = switch (res) {
10961094 .ok => code_buffer.items,
......@@ -1102,12 +1100,12 @@ pub fn updateFunc(
11021100 };
11031101
11041102 const shndx = try self.getDeclShdrIndex(elf_file, decl, code);
1105 try self.updateDeclCode(elf_file, decl_index, sym_index, shndx, code, elf.STT_FUNC);
1103 try self.updateDeclCode(elf_file, pt, decl_index, sym_index, shndx, code, elf.STT_FUNC);
11061104
11071105 if (decl_state) |*ds| {
11081106 const sym = elf_file.symbol(sym_index);
11091107 try self.dwarf.?.commitDeclState(
1110 mod,
1108 pt,
11111109 decl_index,
11121110 @intCast(sym.address(.{}, elf_file)),
11131111 sym.atom(elf_file).?.size,
......@@ -1121,12 +1119,13 @@ pub fn updateFunc(
11211119pub fn updateDecl(
11221120 self: *ZigObject,
11231121 elf_file: *Elf,
1124 mod: *Module,
1122 pt: Zcu.PerThread,
11251123 decl_index: InternPool.DeclIndex,
11261124) link.File.UpdateDeclError!void {
11271125 const tracy = trace(@src());
11281126 defer tracy.end();
11291127
1128 const mod = pt.zcu;
11301129 const decl = mod.declPtr(decl_index);
11311130
11321131 if (decl.val.getExternFunc(mod)) |_| {
......@@ -1150,19 +1149,19 @@ pub fn updateDecl(
11501149 var code_buffer = std.ArrayList(u8).init(gpa);
11511150 defer code_buffer.deinit();
11521151
1153 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
1152 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
11541153 defer if (decl_state) |*ds| ds.deinit();
11551154
11561155 // TODO implement .debug_info for global variables
11571156 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
11581157 const res = if (decl_state) |*ds|
1159 try codegen.generateSymbol(&elf_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .{
1158 try codegen.generateSymbol(&elf_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .{
11601159 .dwarf = ds,
11611160 }, .{
11621161 .parent_atom_index = sym_index,
11631162 })
11641163 else
1165 try codegen.generateSymbol(&elf_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
1164 try codegen.generateSymbol(&elf_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
11661165 .parent_atom_index = sym_index,
11671166 });
11681167
......@@ -1177,14 +1176,14 @@ pub fn updateDecl(
11771176
11781177 const shndx = try self.getDeclShdrIndex(elf_file, decl, code);
11791178 if (elf_file.shdrs.items[shndx].sh_flags & elf.SHF_TLS != 0)
1180 try self.updateTlv(elf_file, decl_index, sym_index, shndx, code)
1179 try self.updateTlv(elf_file, pt, decl_index, sym_index, shndx, code)
11811180 else
1182 try self.updateDeclCode(elf_file, decl_index, sym_index, shndx, code, elf.STT_OBJECT);
1181 try self.updateDeclCode(elf_file, pt, decl_index, sym_index, shndx, code, elf.STT_OBJECT);
11831182
11841183 if (decl_state) |*ds| {
11851184 const sym = elf_file.symbol(sym_index);
11861185 try self.dwarf.?.commitDeclState(
1187 mod,
1186 pt,
11881187 decl_index,
11891188 @intCast(sym.address(.{}, elf_file)),
11901189 sym.atom(elf_file).?.size,
......@@ -1198,11 +1197,12 @@ pub fn updateDecl(
11981197fn updateLazySymbol(
11991198 self: *ZigObject,
12001199 elf_file: *Elf,
1200 pt: Zcu.PerThread,
12011201 sym: link.File.LazySymbol,
12021202 symbol_index: Symbol.Index,
12031203) !void {
1204 const gpa = elf_file.base.comp.gpa;
1205 const mod = elf_file.base.comp.module.?;
1204 const mod = pt.zcu;
1205 const gpa = mod.gpa;
12061206
12071207 var required_alignment: InternPool.Alignment = .none;
12081208 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1211,7 +1211,7 @@ fn updateLazySymbol(
12111211 const name_str_index = blk: {
12121212 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12131213 @tagName(sym.kind),
1214 sym.ty.fmt(mod),
1214 sym.ty.fmt(pt),
12151215 });
12161216 defer gpa.free(name);
12171217 break :blk try self.strtab.insert(gpa, name);
......@@ -1220,6 +1220,7 @@ fn updateLazySymbol(
12201220 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
12211221 const res = try codegen.generateLazySymbol(
12221222 &elf_file.base,
1223 pt,
12231224 src,
12241225 sym,
12251226 &required_alignment,
......@@ -1273,6 +1274,7 @@ fn updateLazySymbol(
12731274pub fn lowerUnnamedConst(
12741275 self: *ZigObject,
12751276 elf_file: *Elf,
1277 pt: Zcu.PerThread,
12761278 val: Value,
12771279 decl_index: InternPool.DeclIndex,
12781280) !u32 {
......@@ -1291,9 +1293,10 @@ pub fn lowerUnnamedConst(
12911293 const ty = val.typeOf(mod);
12921294 const sym_index = switch (try self.lowerConst(
12931295 elf_file,
1296 pt,
12941297 name,
12951298 val,
1296 ty.abiAlignment(mod),
1299 ty.abiAlignment(pt),
12971300 elf_file.zig_data_rel_ro_section_index.?,
12981301 decl.navSrcLoc(mod),
12991302 )) {
......@@ -1318,20 +1321,21 @@ const LowerConstResult = union(enum) {
13181321fn lowerConst(
13191322 self: *ZigObject,
13201323 elf_file: *Elf,
1324 pt: Zcu.PerThread,
13211325 name: []const u8,
13221326 val: Value,
13231327 required_alignment: InternPool.Alignment,
13241328 output_section_index: u32,
13251329 src_loc: Module.LazySrcLoc,
13261330) !LowerConstResult {
1327 const gpa = elf_file.base.comp.gpa;
1331 const gpa = pt.zcu.gpa;
13281332
13291333 var code_buffer = std.ArrayList(u8).init(gpa);
13301334 defer code_buffer.deinit();
13311335
13321336 const sym_index = try self.addAtom(elf_file);
13331337
1334 const res = try codegen.generateSymbol(&elf_file.base, src_loc, val, &code_buffer, .{
1338 const res = try codegen.generateSymbol(&elf_file.base, pt, src_loc, val, &code_buffer, .{
13351339 .none = {},
13361340 }, .{
13371341 .parent_atom_index = sym_index,
......@@ -1373,13 +1377,14 @@ fn lowerConst(
13731377pub fn updateExports(
13741378 self: *ZigObject,
13751379 elf_file: *Elf,
1376 mod: *Module,
1380 pt: Zcu.PerThread,
13771381 exported: Module.Exported,
13781382 export_indices: []const u32,
13791383) link.File.UpdateExportsError!void {
13801384 const tracy = trace(@src());
13811385 defer tracy.end();
13821386
1387 const mod = pt.zcu;
13831388 const gpa = elf_file.base.comp.gpa;
13841389 const metadata = switch (exported) {
13851390 .decl_index => |decl_index| blk: {
......@@ -1388,7 +1393,7 @@ pub fn updateExports(
13881393 },
13891394 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
13901395 const first_exp = mod.all_exports.items[export_indices[0]];
1391 const res = try self.lowerAnonDecl(elf_file, value, .none, first_exp.src);
1396 const res = try self.lowerAnonDecl(elf_file, pt, value, .none, first_exp.src);
13921397 switch (res) {
13931398 .ok => {},
13941399 .fail => |em| {
src/link/MachO.zig+17-16
......@@ -360,11 +360,11 @@ pub fn deinit(self: *MachO) void {
360360 self.unwind_records.deinit(gpa);
361361}
362362
363pub fn flush(self: *MachO, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
364 try self.flushModule(arena, prog_node);
363pub fn flush(self: *MachO, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
364 try self.flushModule(arena, tid, prog_node);
365365}
366366
367pub fn flushModule(self: *MachO, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
367pub fn flushModule(self: *MachO, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
368368 const tracy = trace(@src());
369369 defer tracy.end();
370370
......@@ -391,7 +391,7 @@ pub fn flushModule(self: *MachO, arena: Allocator, prog_node: std.Progress.Node)
391391 // --verbose-link
392392 if (comp.verbose_link) try self.dumpArgv(comp);
393393
394 if (self.getZigObject()) |zo| try zo.flushModule(self);
394 if (self.getZigObject()) |zo| try zo.flushModule(self, tid);
395395 if (self.base.isStaticLib()) return relocatable.flushStaticLib(self, comp, module_obj_path);
396396 if (self.base.isObject()) return relocatable.flushObject(self, comp, module_obj_path);
397397
......@@ -3178,24 +3178,24 @@ pub fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature) !void {
31783178 try self.base.file.?.pwriteAll(buffer.items, offset);
31793179}
31803180
3181pub fn updateFunc(self: *MachO, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
3181pub fn updateFunc(self: *MachO, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
31823182 if (build_options.skip_non_native and builtin.object_format != .macho) {
31833183 @panic("Attempted to compile for object format that was disabled by build configuration");
31843184 }
3185 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
3186 return self.getZigObject().?.updateFunc(self, mod, func_index, air, liveness);
3185 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
3186 return self.getZigObject().?.updateFunc(self, pt, func_index, air, liveness);
31873187}
31883188
3189pub fn lowerUnnamedConst(self: *MachO, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3190 return self.getZigObject().?.lowerUnnamedConst(self, val, decl_index);
3189pub fn lowerUnnamedConst(self: *MachO, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3190 return self.getZigObject().?.lowerUnnamedConst(self, pt, val, decl_index);
31913191}
31923192
3193pub fn updateDecl(self: *MachO, mod: *Module, decl_index: InternPool.DeclIndex) !void {
3193pub fn updateDecl(self: *MachO, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
31943194 if (build_options.skip_non_native and builtin.object_format != .macho) {
31953195 @panic("Attempted to compile for object format that was disabled by build configuration");
31963196 }
3197 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
3198 return self.getZigObject().?.updateDecl(self, mod, decl_index);
3197 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
3198 return self.getZigObject().?.updateDecl(self, pt, decl_index);
31993199}
32003200
32013201pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl_index: InternPool.DeclIndex) !void {
......@@ -3205,15 +3205,15 @@ pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl_index: InternPoo
32053205
32063206pub fn updateExports(
32073207 self: *MachO,
3208 mod: *Module,
3208 pt: Zcu.PerThread,
32093209 exported: Module.Exported,
32103210 export_indices: []const u32,
32113211) link.File.UpdateExportsError!void {
32123212 if (build_options.skip_non_native and builtin.object_format != .macho) {
32133213 @panic("Attempted to compile for object format that was disabled by build configuration");
32143214 }
3215 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
3216 return self.getZigObject().?.updateExports(self, mod, exported, export_indices);
3215 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
3216 return self.getZigObject().?.updateExports(self, pt, exported, export_indices);
32173217}
32183218
32193219pub fn deleteExport(
......@@ -3237,11 +3237,12 @@ pub fn getDeclVAddr(self: *MachO, decl_index: InternPool.DeclIndex, reloc_info:
32373237
32383238pub fn lowerAnonDecl(
32393239 self: *MachO,
3240 pt: Zcu.PerThread,
32403241 decl_val: InternPool.Index,
32413242 explicit_alignment: InternPool.Alignment,
32423243 src_loc: Module.LazySrcLoc,
32433244) !codegen.Result {
3244 return self.getZigObject().?.lowerAnonDecl(self, decl_val, explicit_alignment, src_loc);
3245 return self.getZigObject().?.lowerAnonDecl(self, pt, decl_val, explicit_alignment, src_loc);
32453246}
32463247
32473248pub fn getAnonDeclVAddr(self: *MachO, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
src/link/MachO/ZigObject.zig+49-33
......@@ -425,16 +425,17 @@ pub fn getInputSection(self: ZigObject, atom: Atom, macho_file: *MachO) macho.se
425425 return sect;
426426}
427427
428pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
428pub fn flushModule(self: *ZigObject, macho_file: *MachO, tid: Zcu.PerThread.Id) !void {
429429 // Handle any lazy symbols that were emitted by incremental compilation.
430430 if (self.lazy_syms.getPtr(.none)) |metadata| {
431 const zcu = macho_file.base.comp.module.?;
431 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.module.?, .tid = tid };
432432
433433 // Most lazy symbols can be updated on first use, but
434434 // anyerror needs to wait for everything to be flushed.
435435 if (metadata.text_state != .unused) self.updateLazySymbol(
436436 macho_file,
437 link.File.LazySymbol.initDecl(.code, null, zcu),
437 pt,
438 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
438439 metadata.text_symbol_index,
439440 ) catch |err| return switch (err) {
440441 error.CodegenFail => error.FlushFailure,
......@@ -442,7 +443,8 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
442443 };
443444 if (metadata.const_state != .unused) self.updateLazySymbol(
444445 macho_file,
445 link.File.LazySymbol.initDecl(.const_data, null, zcu),
446 pt,
447 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
446448 metadata.const_symbol_index,
447449 ) catch |err| return switch (err) {
448450 error.CodegenFail => error.FlushFailure,
......@@ -455,8 +457,8 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
455457 }
456458
457459 if (self.dwarf) |*dw| {
458 const zcu = macho_file.base.comp.module.?;
459 try dw.flushModule(zcu);
460 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.module.?, .tid = tid };
461 try dw.flushModule(pt);
460462
461463 if (self.debug_abbrev_dirty) {
462464 try dw.writeDbgAbbrev();
......@@ -469,7 +471,7 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
469471 const text_section = macho_file.sections.items(.header)[macho_file.zig_text_sect_index.?];
470472 const low_pc = text_section.addr;
471473 const high_pc = text_section.addr + text_section.size;
472 try dw.writeDbgInfoHeader(zcu, low_pc, high_pc);
474 try dw.writeDbgInfoHeader(pt.zcu, low_pc, high_pc);
473475 self.debug_info_header_dirty = false;
474476 }
475477
......@@ -570,6 +572,7 @@ pub fn getAnonDeclVAddr(
570572pub fn lowerAnonDecl(
571573 self: *ZigObject,
572574 macho_file: *MachO,
575 pt: Zcu.PerThread,
573576 decl_val: InternPool.Index,
574577 explicit_alignment: Atom.Alignment,
575578 src_loc: Module.LazySrcLoc,
......@@ -578,7 +581,7 @@ pub fn lowerAnonDecl(
578581 const mod = macho_file.base.comp.module.?;
579582 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
580583 const decl_alignment = switch (explicit_alignment) {
581 .none => ty.abiAlignment(mod),
584 .none => ty.abiAlignment(pt),
582585 else => explicit_alignment,
583586 };
584587 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -593,6 +596,7 @@ pub fn lowerAnonDecl(
593596 }) catch unreachable;
594597 const res = self.lowerConst(
595598 macho_file,
599 pt,
596600 name,
597601 Value.fromInterned(decl_val),
598602 decl_alignment,
......@@ -656,7 +660,7 @@ pub fn freeDecl(self: *ZigObject, macho_file: *MachO, decl_index: InternPool.Dec
656660pub fn updateFunc(
657661 self: *ZigObject,
658662 macho_file: *MachO,
659 mod: *Module,
663 pt: Zcu.PerThread,
660664 func_index: InternPool.Index,
661665 air: Air,
662666 liveness: Liveness,
......@@ -664,7 +668,8 @@ pub fn updateFunc(
664668 const tracy = trace(@src());
665669 defer tracy.end();
666670
667 const gpa = macho_file.base.comp.gpa;
671 const mod = pt.zcu;
672 const gpa = mod.gpa;
668673 const func = mod.funcInfo(func_index);
669674 const decl_index = func.owner_decl;
670675 const decl = mod.declPtr(decl_index);
......@@ -676,12 +681,13 @@ pub fn updateFunc(
676681 var code_buffer = std.ArrayList(u8).init(gpa);
677682 defer code_buffer.deinit();
678683
679 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
684 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
680685 defer if (decl_state) |*ds| ds.deinit();
681686
682687 const dio: codegen.DebugInfoOutput = if (decl_state) |*ds| .{ .dwarf = ds } else .none;
683688 const res = try codegen.generateFunction(
684689 &macho_file.base,
690 pt,
685691 decl.navSrcLoc(mod),
686692 func_index,
687693 air,
......@@ -700,12 +706,12 @@ pub fn updateFunc(
700706 };
701707
702708 const sect_index = try self.getDeclOutputSection(macho_file, decl, code);
703 try self.updateDeclCode(macho_file, decl_index, sym_index, sect_index, code);
709 try self.updateDeclCode(macho_file, pt, decl_index, sym_index, sect_index, code);
704710
705711 if (decl_state) |*ds| {
706712 const sym = macho_file.getSymbol(sym_index);
707713 try self.dwarf.?.commitDeclState(
708 mod,
714 pt,
709715 decl_index,
710716 sym.getAddress(.{}, macho_file),
711717 sym.getAtom(macho_file).?.size,
......@@ -719,12 +725,13 @@ pub fn updateFunc(
719725pub fn updateDecl(
720726 self: *ZigObject,
721727 macho_file: *MachO,
722 mod: *Module,
728 pt: Zcu.PerThread,
723729 decl_index: InternPool.DeclIndex,
724730) link.File.UpdateDeclError!void {
725731 const tracy = trace(@src());
726732 defer tracy.end();
727733
734 const mod = pt.zcu;
728735 const decl = mod.declPtr(decl_index);
729736
730737 if (decl.val.getExternFunc(mod)) |_| {
......@@ -749,12 +756,12 @@ pub fn updateDecl(
749756 var code_buffer = std.ArrayList(u8).init(gpa);
750757 defer code_buffer.deinit();
751758
752 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
759 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
753760 defer if (decl_state) |*ds| ds.deinit();
754761
755762 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
756763 const dio: codegen.DebugInfoOutput = if (decl_state) |*ds| .{ .dwarf = ds } else .none;
757 const res = try codegen.generateSymbol(&macho_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, dio, .{
764 const res = try codegen.generateSymbol(&macho_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, dio, .{
758765 .parent_atom_index = sym_index,
759766 });
760767
......@@ -772,15 +779,15 @@ pub fn updateDecl(
772779 else => false,
773780 };
774781 if (is_threadlocal) {
775 try self.updateTlv(macho_file, decl_index, sym_index, sect_index, code);
782 try self.updateTlv(macho_file, pt, decl_index, sym_index, sect_index, code);
776783 } else {
777 try self.updateDeclCode(macho_file, decl_index, sym_index, sect_index, code);
784 try self.updateDeclCode(macho_file, pt, decl_index, sym_index, sect_index, code);
778785 }
779786
780787 if (decl_state) |*ds| {
781788 const sym = macho_file.getSymbol(sym_index);
782789 try self.dwarf.?.commitDeclState(
783 mod,
790 pt,
784791 decl_index,
785792 sym.getAddress(.{}, macho_file),
786793 sym.getAtom(macho_file).?.size,
......@@ -794,19 +801,20 @@ pub fn updateDecl(
794801fn updateDeclCode(
795802 self: *ZigObject,
796803 macho_file: *MachO,
804 pt: Zcu.PerThread,
797805 decl_index: InternPool.DeclIndex,
798806 sym_index: Symbol.Index,
799807 sect_index: u8,
800808 code: []const u8,
801809) !void {
802810 const gpa = macho_file.base.comp.gpa;
803 const mod = macho_file.base.comp.module.?;
811 const mod = pt.zcu;
804812 const decl = mod.declPtr(decl_index);
805813 const decl_name = try decl.fullyQualifiedName(mod);
806814
807815 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
808816
809 const required_alignment = decl.getAlignment(mod);
817 const required_alignment = decl.getAlignment(pt);
810818
811819 const sect = &macho_file.sections.items(.header)[sect_index];
812820 const sym = macho_file.getSymbol(sym_index);
......@@ -879,19 +887,20 @@ fn updateDeclCode(
879887fn updateTlv(
880888 self: *ZigObject,
881889 macho_file: *MachO,
890 pt: Zcu.PerThread,
882891 decl_index: InternPool.DeclIndex,
883892 sym_index: Symbol.Index,
884893 sect_index: u8,
885894 code: []const u8,
886895) !void {
887 const mod = macho_file.base.comp.module.?;
896 const mod = pt.zcu;
888897 const decl = mod.declPtr(decl_index);
889898 const decl_name = try decl.fullyQualifiedName(mod);
890899
891900 log.debug("updateTlv {} ({*})", .{ decl_name.fmt(&mod.intern_pool), decl });
892901
893902 const decl_name_slice = decl_name.toSlice(&mod.intern_pool);
894 const required_alignment = decl.getAlignment(mod);
903 const required_alignment = decl.getAlignment(pt);
895904
896905 // 1. Lower TLV initializer
897906 const init_sym_index = try self.createTlvInitializer(
......@@ -1079,11 +1088,12 @@ fn getDeclOutputSection(
10791088pub fn lowerUnnamedConst(
10801089 self: *ZigObject,
10811090 macho_file: *MachO,
1091 pt: Zcu.PerThread,
10821092 val: Value,
10831093 decl_index: InternPool.DeclIndex,
10841094) !u32 {
1085 const gpa = macho_file.base.comp.gpa;
1086 const mod = macho_file.base.comp.module.?;
1095 const mod = pt.zcu;
1096 const gpa = mod.gpa;
10871097 const gop = try self.unnamed_consts.getOrPut(gpa, decl_index);
10881098 if (!gop.found_existing) {
10891099 gop.value_ptr.* = .{};
......@@ -1096,9 +1106,10 @@ pub fn lowerUnnamedConst(
10961106 defer gpa.free(name);
10971107 const sym_index = switch (try self.lowerConst(
10981108 macho_file,
1109 pt,
10991110 name,
11001111 val,
1101 val.typeOf(mod).abiAlignment(mod),
1112 val.typeOf(mod).abiAlignment(pt),
11021113 macho_file.zig_const_sect_index.?,
11031114 decl.navSrcLoc(mod),
11041115 )) {
......@@ -1123,6 +1134,7 @@ const LowerConstResult = union(enum) {
11231134fn lowerConst(
11241135 self: *ZigObject,
11251136 macho_file: *MachO,
1137 pt: Zcu.PerThread,
11261138 name: []const u8,
11271139 val: Value,
11281140 required_alignment: Atom.Alignment,
......@@ -1136,7 +1148,7 @@ fn lowerConst(
11361148
11371149 const sym_index = try self.addAtom(macho_file);
11381150
1139 const res = try codegen.generateSymbol(&macho_file.base, src_loc, val, &code_buffer, .{
1151 const res = try codegen.generateSymbol(&macho_file.base, pt, src_loc, val, &code_buffer, .{
11401152 .none = {},
11411153 }, .{
11421154 .parent_atom_index = sym_index,
......@@ -1181,13 +1193,14 @@ fn lowerConst(
11811193pub fn updateExports(
11821194 self: *ZigObject,
11831195 macho_file: *MachO,
1184 mod: *Module,
1196 pt: Zcu.PerThread,
11851197 exported: Module.Exported,
11861198 export_indices: []const u32,
11871199) link.File.UpdateExportsError!void {
11881200 const tracy = trace(@src());
11891201 defer tracy.end();
11901202
1203 const mod = pt.zcu;
11911204 const gpa = macho_file.base.comp.gpa;
11921205 const metadata = switch (exported) {
11931206 .decl_index => |decl_index| blk: {
......@@ -1196,7 +1209,7 @@ pub fn updateExports(
11961209 },
11971210 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
11981211 const first_exp = mod.all_exports.items[export_indices[0]];
1199 const res = try self.lowerAnonDecl(macho_file, value, .none, first_exp.src);
1212 const res = try self.lowerAnonDecl(macho_file, pt, value, .none, first_exp.src);
12001213 switch (res) {
12011214 .ok => {},
12021215 .fail => |em| {
......@@ -1272,6 +1285,7 @@ pub fn updateExports(
12721285fn updateLazySymbol(
12731286 self: *ZigObject,
12741287 macho_file: *MachO,
1288 pt: Zcu.PerThread,
12751289 lazy_sym: link.File.LazySymbol,
12761290 symbol_index: Symbol.Index,
12771291) !void {
......@@ -1285,7 +1299,7 @@ fn updateLazySymbol(
12851299 const name_str_index = blk: {
12861300 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12871301 @tagName(lazy_sym.kind),
1288 lazy_sym.ty.fmt(mod),
1302 lazy_sym.ty.fmt(pt),
12891303 });
12901304 defer gpa.free(name);
12911305 break :blk try self.strtab.insert(gpa, name);
......@@ -1294,6 +1308,7 @@ fn updateLazySymbol(
12941308 const src = lazy_sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
12951309 const res = try codegen.generateLazySymbol(
12961310 &macho_file.base,
1311 pt,
12971312 src,
12981313 lazy_sym,
12991314 &required_alignment,
......@@ -1431,10 +1446,11 @@ pub fn getOrCreateMetadataForDecl(
14311446pub fn getOrCreateMetadataForLazySymbol(
14321447 self: *ZigObject,
14331448 macho_file: *MachO,
1449 pt: Zcu.PerThread,
14341450 lazy_sym: link.File.LazySymbol,
14351451) !Symbol.Index {
1436 const gpa = macho_file.base.comp.gpa;
1437 const mod = macho_file.base.comp.module.?;
1452 const mod = pt.zcu;
1453 const gpa = mod.gpa;
14381454 const gop = try self.lazy_syms.getOrPut(gpa, lazy_sym.getDecl(mod));
14391455 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
14401456 if (!gop.found_existing) gop.value_ptr.* = .{};
......@@ -1464,7 +1480,7 @@ pub fn getOrCreateMetadataForLazySymbol(
14641480 metadata.state.* = .pending_flush;
14651481 const symbol_index = metadata.symbol_index.*;
14661482 // anyerror needs to be deferred until flushModule
1467 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(macho_file, lazy_sym, symbol_index);
1483 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(macho_file, pt, lazy_sym, symbol_index);
14681484 return symbol_index;
14691485}
14701486
src/link/NvPtx.zig+11-12
......@@ -13,8 +13,6 @@ const assert = std.debug.assert;
1313const log = std.log.scoped(.link);
1414
1515const Zcu = @import("../Zcu.zig");
16/// Deprecated.
17const Module = Zcu;
1816const InternPool = @import("../InternPool.zig");
1917const Compilation = @import("../Compilation.zig");
2018const link = @import("../link.zig");
......@@ -84,35 +82,35 @@ pub fn deinit(self: *NvPtx) void {
8482 self.llvm_object.deinit();
8583}
8684
87pub fn updateFunc(self: *NvPtx, module: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
88 try self.llvm_object.updateFunc(module, func_index, air, liveness);
85pub fn updateFunc(self: *NvPtx, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
86 try self.llvm_object.updateFunc(pt, func_index, air, liveness);
8987}
9088
91pub fn updateDecl(self: *NvPtx, module: *Module, decl_index: InternPool.DeclIndex) !void {
92 return self.llvm_object.updateDecl(module, decl_index);
89pub fn updateDecl(self: *NvPtx, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
90 return self.llvm_object.updateDecl(pt, decl_index);
9391}
9492
9593pub fn updateExports(
9694 self: *NvPtx,
97 module: *Module,
98 exported: Module.Exported,
95 pt: Zcu.PerThread,
96 exported: Zcu.Exported,
9997 export_indices: []const u32,
10098) !void {
10199 if (build_options.skip_non_native and builtin.object_format != .nvptx)
102100 @panic("Attempted to compile for object format that was disabled by build configuration");
103101
104 return self.llvm_object.updateExports(module, exported, export_indices);
102 return self.llvm_object.updateExports(pt, exported, export_indices);
105103}
106104
107105pub fn freeDecl(self: *NvPtx, decl_index: InternPool.DeclIndex) void {
108106 return self.llvm_object.freeDecl(decl_index);
109107}
110108
111pub fn flush(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
112 return self.flushModule(arena, prog_node);
109pub fn flush(self: *NvPtx, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
110 return self.flushModule(arena, tid, prog_node);
113111}
114112
115pub fn flushModule(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
113pub fn flushModule(self: *NvPtx, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
116114 if (build_options.skip_non_native)
117115 @panic("Attempted to compile for architecture that was disabled by build configuration");
118116
......@@ -121,5 +119,6 @@ pub fn flushModule(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node)
121119 _ = arena;
122120 _ = self;
123121 _ = prog_node;
122 _ = tid;
124123 @panic("TODO: rewrite the NvPtx.flushModule function");
125124}
src/link/Plan9.zig+47-40
......@@ -4,8 +4,6 @@
44const Plan9 = @This();
55const link = @import("../link.zig");
66const Zcu = @import("../Zcu.zig");
7/// Deprecated.
8const Module = Zcu;
97const InternPool = @import("../InternPool.zig");
108const Compilation = @import("../Compilation.zig");
119const aout = @import("Plan9/aout.zig");
......@@ -56,7 +54,7 @@ path_arena: std.heap.ArenaAllocator,
5654/// of the function to know what file it came from.
5755/// If we group the decls by file, it makes it really easy to do this (put the symbol in the correct place)
5856fn_decl_table: std.AutoArrayHashMapUnmanaged(
59 *Module.File,
57 *Zcu.File,
6058 struct { sym_index: u32, functions: std.AutoArrayHashMapUnmanaged(InternPool.DeclIndex, FnDeclOutput) = .{} },
6159) = .{},
6260/// the code is modified when relocated, so that is why it is mutable
......@@ -411,12 +409,13 @@ fn addPathComponents(self: *Plan9, path: []const u8, a: *std.ArrayList(u8)) !voi
411409 }
412410}
413411
414pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
412pub fn updateFunc(self: *Plan9, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
415413 if (build_options.skip_non_native and builtin.object_format != .plan9) {
416414 @panic("Attempted to compile for object format that was disabled by build configuration");
417415 }
418416
419 const gpa = self.base.comp.gpa;
417 const mod = pt.zcu;
418 const gpa = mod.gpa;
420419 const target = self.base.comp.root_mod.resolved_target.result;
421420 const func = mod.funcInfo(func_index);
422421 const decl_index = func.owner_decl;
......@@ -439,6 +438,7 @@ pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air:
439438
440439 const res = try codegen.generateFunction(
441440 &self.base,
441 pt,
442442 decl.navSrcLoc(mod),
443443 func_index,
444444 air,
......@@ -468,13 +468,13 @@ pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air:
468468 return self.updateFinish(decl_index);
469469}
470470
471pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIndex) !u32 {
472 const gpa = self.base.comp.gpa;
471pub fn lowerUnnamedConst(self: *Plan9, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
472 const mod = pt.zcu;
473 const gpa = mod.gpa;
473474 _ = try self.seeDecl(decl_index);
474475 var code_buffer = std.ArrayList(u8).init(gpa);
475476 defer code_buffer.deinit();
476477
477 const mod = self.base.comp.module.?;
478478 const decl = mod.declPtr(decl_index);
479479
480480 const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index);
......@@ -505,7 +505,7 @@ pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIn
505505 };
506506 self.syms.items[info.sym_index.?] = sym;
507507
508 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), val, &code_buffer, .{
508 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), val, &code_buffer, .{
509509 .none = {},
510510 }, .{
511511 .parent_atom_index = new_atom_idx,
......@@ -530,8 +530,9 @@ pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIn
530530 return new_atom_idx;
531531}
532532
533pub fn updateDecl(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex) !void {
533pub fn updateDecl(self: *Plan9, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
534534 const gpa = self.base.comp.gpa;
535 const mod = pt.zcu;
535536 const decl = mod.declPtr(decl_index);
536537
537538 if (decl.isExtern(mod)) {
......@@ -544,7 +545,7 @@ pub fn updateDecl(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex)
544545 defer code_buffer.deinit();
545546 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
546547 // TODO we need the symbol index for symbol in the table of locals for the containing atom
547 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .{ .none = {} }, .{
548 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .{ .none = {} }, .{
548549 .parent_atom_index = @as(Atom.Index, @intCast(atom_idx)),
549550 });
550551 const code = switch (res) {
......@@ -610,7 +611,7 @@ fn allocateGotIndex(self: *Plan9) usize {
610611 }
611612}
612613
613pub fn flush(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
614pub fn flush(self: *Plan9, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
614615 const comp = self.base.comp;
615616 const use_lld = build_options.have_llvm and comp.config.use_lld;
616617 assert(!use_lld);
......@@ -621,7 +622,7 @@ pub fn flush(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.
621622 .Obj => return error.TODOImplementPlan9Objs,
622623 .Lib => return error.TODOImplementWritingLibFiles,
623624 }
624 return self.flushModule(arena, prog_node);
625 return self.flushModule(arena, tid, prog_node);
625626}
626627
627628pub fn changeLine(l: *std.ArrayList(u8), delta_line: i32) !void {
......@@ -669,20 +670,20 @@ fn atomCount(self: *Plan9) usize {
669670 return data_decl_count + fn_decl_count + unnamed_const_count + lazy_atom_count + extern_atom_count + anon_atom_count;
670671}
671672
672pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
673pub fn flushModule(self: *Plan9, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
673674 if (build_options.skip_non_native and builtin.object_format != .plan9) {
674675 @panic("Attempted to compile for object format that was disabled by build configuration");
675676 }
676677
678 const tracy = trace(@src());
679 defer tracy.end();
680
677681 _ = arena; // Has the same lifetime as the call to Compilation.update.
678682
679683 const comp = self.base.comp;
680684 const gpa = comp.gpa;
681685 const target = comp.root_mod.resolved_target.result;
682686
683 const tracy = trace(@src());
684 defer tracy.end();
685
686687 const sub_prog_node = prog_node.start("Flush Module", 0);
687688 defer sub_prog_node.end();
688689
......@@ -690,21 +691,26 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
690691
691692 defer assert(self.hdr.entry != 0x0);
692693
693 const mod = self.base.comp.module orelse return error.LinkingWithoutZigSourceUnimplemented;
694 const pt: Zcu.PerThread = .{
695 .zcu = self.base.comp.module orelse return error.LinkingWithoutZigSourceUnimplemented,
696 .tid = tid,
697 };
694698
695699 // finish up the lazy syms
696700 if (self.lazy_syms.getPtr(.none)) |metadata| {
697701 // Most lazy symbols can be updated on first use, but
698702 // anyerror needs to wait for everything to be flushed.
699703 if (metadata.text_state != .unused) self.updateLazySymbolAtom(
700 File.LazySymbol.initDecl(.code, null, mod),
704 pt,
705 File.LazySymbol.initDecl(.code, null, pt.zcu),
701706 metadata.text_atom,
702707 ) catch |err| return switch (err) {
703708 error.CodegenFail => error.FlushFailure,
704709 else => |e| e,
705710 };
706711 if (metadata.rodata_state != .unused) self.updateLazySymbolAtom(
707 File.LazySymbol.initDecl(.const_data, null, mod),
712 pt,
713 File.LazySymbol.initDecl(.const_data, null, pt.zcu),
708714 metadata.rodata_atom,
709715 ) catch |err| return switch (err) {
710716 error.CodegenFail => error.FlushFailure,
......@@ -747,7 +753,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
747753 var it = fentry.value_ptr.functions.iterator();
748754 while (it.next()) |entry| {
749755 const decl_index = entry.key_ptr.*;
750 const decl = mod.declPtr(decl_index);
756 const decl = pt.zcu.declPtr(decl_index);
751757 const atom = self.getAtomPtr(self.decls.get(decl_index).?.index);
752758 const out = entry.value_ptr.*;
753759 {
......@@ -767,7 +773,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
767773 const off = self.getAddr(text_i, .t);
768774 text_i += out.code.len;
769775 atom.offset = off;
770 log.debug("write text decl {*} ({}), lines {d} to {d}.;__GOT+0x{x} vaddr: 0x{x}", .{ decl, decl.name.fmt(&mod.intern_pool), out.start_line + 1, out.end_line, atom.got_index.? * 8, off });
776 log.debug("write text decl {*} ({}), lines {d} to {d}.;__GOT+0x{x} vaddr: 0x{x}", .{ decl, decl.name.fmt(&pt.zcu.intern_pool), out.start_line + 1, out.end_line, atom.got_index.? * 8, off });
771777 if (!self.sixtyfour_bit) {
772778 mem.writeInt(u32, got_table[atom.got_index.? * 4 ..][0..4], @as(u32, @intCast(off)), target.cpu.arch.endian());
773779 } else {
......@@ -775,7 +781,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
775781 }
776782 self.syms.items[atom.sym_index.?].value = off;
777783 if (self.decl_exports.get(decl_index)) |export_indices| {
778 try self.addDeclExports(mod, decl_index, export_indices);
784 try self.addDeclExports(pt.zcu, decl_index, export_indices);
779785 }
780786 }
781787 }
......@@ -841,7 +847,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
841847 }
842848 self.syms.items[atom.sym_index.?].value = off;
843849 if (self.decl_exports.get(decl_index)) |export_indices| {
844 try self.addDeclExports(mod, decl_index, export_indices);
850 try self.addDeclExports(pt.zcu, decl_index, export_indices);
845851 }
846852 }
847853 // write the unnamed constants after the other data decls
......@@ -1009,7 +1015,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
10091015}
10101016fn addDeclExports(
10111017 self: *Plan9,
1012 mod: *Module,
1018 mod: *Zcu,
10131019 decl_index: InternPool.DeclIndex,
10141020 export_indices: []const u32,
10151021) !void {
......@@ -1025,7 +1031,7 @@ fn addDeclExports(
10251031 if (!section_name.eqlSlice(".text", &mod.intern_pool) and
10261032 !section_name.eqlSlice(".data", &mod.intern_pool))
10271033 {
1028 try mod.failed_exports.put(mod.gpa, export_idx, try Module.ErrorMsg.create(
1034 try mod.failed_exports.put(mod.gpa, export_idx, try Zcu.ErrorMsg.create(
10291035 gpa,
10301036 mod.declPtr(decl_index).navSrcLoc(mod),
10311037 "plan9 does not support extra sections",
......@@ -1155,8 +1161,8 @@ pub fn seeDecl(self: *Plan9, decl_index: InternPool.DeclIndex) !Atom.Index {
11551161
11561162pub fn updateExports(
11571163 self: *Plan9,
1158 module: *Module,
1159 exported: Module.Exported,
1164 pt: Zcu.PerThread,
1165 exported: Zcu.Exported,
11601166 export_indices: []const u32,
11611167) !void {
11621168 const gpa = self.base.comp.gpa;
......@@ -1173,11 +1179,11 @@ pub fn updateExports(
11731179 },
11741180 }
11751181 // all proper work is done in flush
1176 _ = module;
1182 _ = pt;
11771183}
11781184
1179pub fn getOrCreateAtomForLazySymbol(self: *Plan9, sym: File.LazySymbol) !Atom.Index {
1180 const gpa = self.base.comp.gpa;
1185pub fn getOrCreateAtomForLazySymbol(self: *Plan9, pt: Zcu.PerThread, sym: File.LazySymbol) !Atom.Index {
1186 const gpa = pt.zcu.gpa;
11811187 const gop = try self.lazy_syms.getOrPut(gpa, sym.getDecl(self.base.comp.module.?));
11821188 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
11831189
......@@ -1198,14 +1204,13 @@ pub fn getOrCreateAtomForLazySymbol(self: *Plan9, sym: File.LazySymbol) !Atom.In
11981204 _ = self.getAtomPtr(atom).getOrCreateOffsetTableEntry(self);
11991205 // anyerror needs to be deferred until flushModule
12001206 if (sym.getDecl(self.base.comp.module.?) != .none) {
1201 try self.updateLazySymbolAtom(sym, atom);
1207 try self.updateLazySymbolAtom(pt, sym, atom);
12021208 }
12031209 return atom;
12041210}
12051211
1206fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Index) !void {
1207 const gpa = self.base.comp.gpa;
1208 const mod = self.base.comp.module.?;
1212fn updateLazySymbolAtom(self: *Plan9, pt: Zcu.PerThread, sym: File.LazySymbol, atom_index: Atom.Index) !void {
1213 const gpa = pt.zcu.gpa;
12091214
12101215 var required_alignment: InternPool.Alignment = .none;
12111216 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1214,7 +1219,7 @@ fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Ind
12141219 // create the symbol for the name
12151220 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12161221 @tagName(sym.kind),
1217 sym.ty.fmt(mod),
1222 sym.ty.fmt(pt),
12181223 });
12191224
12201225 const symbol: aout.Sym = .{
......@@ -1225,9 +1230,10 @@ fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Ind
12251230 self.syms.items[self.getAtomPtr(atom_index).sym_index.?] = symbol;
12261231
12271232 // generate the code
1228 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
1233 const src = sym.ty.srcLocOrNull(pt.zcu) orelse Zcu.LazySrcLoc.unneeded;
12291234 const res = try codegen.generateLazySymbol(
12301235 &self.base,
1236 pt,
12311237 src,
12321238 sym,
12331239 &required_alignment,
......@@ -1490,7 +1496,7 @@ pub fn writeSyms(self: *Plan9, buf: *std.ArrayList(u8)) !void {
14901496}
14911497
14921498/// Must be called only after a successful call to `updateDecl`.
1493pub fn updateDeclLineNumber(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1499pub fn updateDeclLineNumber(self: *Plan9, mod: *Zcu, decl_index: InternPool.DeclIndex) !void {
14941500 _ = self;
14951501 _ = mod;
14961502 _ = decl_index;
......@@ -1544,9 +1550,10 @@ pub fn getDeclVAddr(
15441550
15451551pub fn lowerAnonDecl(
15461552 self: *Plan9,
1553 pt: Zcu.PerThread,
15471554 decl_val: InternPool.Index,
15481555 explicit_alignment: InternPool.Alignment,
1549 src_loc: Module.LazySrcLoc,
1556 src_loc: Zcu.LazySrcLoc,
15501557) !codegen.Result {
15511558 _ = explicit_alignment;
15521559 // This is basically the same as lowerUnnamedConst.
......@@ -1569,7 +1576,7 @@ pub fn lowerAnonDecl(
15691576 gop.value_ptr.* = index;
15701577 // we need to free name latex
15711578 var code_buffer = std.ArrayList(u8).init(gpa);
1572 const res = try codegen.generateSymbol(&self.base, src_loc, val, &code_buffer, .{ .none = {} }, .{ .parent_atom_index = index });
1579 const res = try codegen.generateSymbol(&self.base, pt, src_loc, val, &code_buffer, .{ .none = {} }, .{ .parent_atom_index = index });
15731580 const code = switch (res) {
15741581 .ok => code_buffer.items,
15751582 .fail => |em| return .{ .fail = em },
src/link/SpirV.zig+16-16
......@@ -28,8 +28,6 @@ const assert = std.debug.assert;
2828const log = std.log.scoped(.link);
2929
3030const Zcu = @import("../Zcu.zig");
31/// Deprecated.
32const Module = Zcu;
3331const InternPool = @import("../InternPool.zig");
3432const Compilation = @import("../Compilation.zig");
3533const link = @import("../link.zig");
......@@ -125,35 +123,36 @@ pub fn deinit(self: *SpirV) void {
125123 self.object.deinit();
126124}
127125
128pub fn updateFunc(self: *SpirV, module: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
126pub fn updateFunc(self: *SpirV, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
129127 if (build_options.skip_non_native) {
130128 @panic("Attempted to compile for architecture that was disabled by build configuration");
131129 }
132130
133 const func = module.funcInfo(func_index);
134 const decl = module.declPtr(func.owner_decl);
135 log.debug("lowering function {}", .{decl.name.fmt(&module.intern_pool)});
131 const func = pt.zcu.funcInfo(func_index);
132 const decl = pt.zcu.declPtr(func.owner_decl);
133 log.debug("lowering function {}", .{decl.name.fmt(&pt.zcu.intern_pool)});
136134
137 try self.object.updateFunc(module, func_index, air, liveness);
135 try self.object.updateFunc(pt, func_index, air, liveness);
138136}
139137
140pub fn updateDecl(self: *SpirV, module: *Module, decl_index: InternPool.DeclIndex) !void {
138pub fn updateDecl(self: *SpirV, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
141139 if (build_options.skip_non_native) {
142140 @panic("Attempted to compile for architecture that was disabled by build configuration");
143141 }
144142
145 const decl = module.declPtr(decl_index);
146 log.debug("lowering declaration {}", .{decl.name.fmt(&module.intern_pool)});
143 const decl = pt.zcu.declPtr(decl_index);
144 log.debug("lowering declaration {}", .{decl.name.fmt(&pt.zcu.intern_pool)});
147145
148 try self.object.updateDecl(module, decl_index);
146 try self.object.updateDecl(pt, decl_index);
149147}
150148
151149pub fn updateExports(
152150 self: *SpirV,
153 mod: *Module,
154 exported: Module.Exported,
151 pt: Zcu.PerThread,
152 exported: Zcu.Exported,
155153 export_indices: []const u32,
156154) !void {
155 const mod = pt.zcu;
157156 const decl_index = switch (exported) {
158157 .decl_index => |i| i,
159158 .value => |val| {
......@@ -196,11 +195,11 @@ pub fn freeDecl(self: *SpirV, decl_index: InternPool.DeclIndex) void {
196195 _ = decl_index;
197196}
198197
199pub fn flush(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
200 return self.flushModule(arena, prog_node);
198pub fn flush(self: *SpirV, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
199 return self.flushModule(arena, tid, prog_node);
201200}
202201
203pub fn flushModule(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
202pub fn flushModule(self: *SpirV, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
204203 if (build_options.skip_non_native) {
205204 @panic("Attempted to compile for architecture that was disabled by build configuration");
206205 }
......@@ -216,6 +215,7 @@ pub fn flushModule(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node)
216215 const comp = self.base.comp;
217216 const gpa = comp.gpa;
218217 const target = comp.getTarget();
218 _ = tid;
219219
220220 try writeCapabilities(spv, target);
221221 try writeMemoryModel(spv, target);
src/link/Wasm.zig+25-26
......@@ -29,8 +29,6 @@ const InternPool = @import("../InternPool.zig");
2929const Liveness = @import("../Liveness.zig");
3030const LlvmObject = @import("../codegen/llvm.zig").Object;
3131const Zcu = @import("../Zcu.zig");
32/// Deprecated.
33const Module = Zcu;
3432const Object = @import("Wasm/Object.zig");
3533const Symbol = @import("Wasm/Symbol.zig");
3634const Type = @import("../Type.zig");
......@@ -1441,25 +1439,25 @@ pub fn deinit(wasm: *Wasm) void {
14411439 wasm.files.deinit(gpa);
14421440}
14431441
1444pub fn updateFunc(wasm: *Wasm, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
1442pub fn updateFunc(wasm: *Wasm, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
14451443 if (build_options.skip_non_native and builtin.object_format != .wasm) {
14461444 @panic("Attempted to compile for object format that was disabled by build configuration");
14471445 }
1448 if (wasm.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
1449 try wasm.zigObjectPtr().?.updateFunc(wasm, mod, func_index, air, liveness);
1446 if (wasm.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
1447 try wasm.zigObjectPtr().?.updateFunc(wasm, pt, func_index, air, liveness);
14501448}
14511449
14521450// Generate code for the Decl, storing it in memory to be later written to
14531451// the file on flush().
1454pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1452pub fn updateDecl(wasm: *Wasm, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
14551453 if (build_options.skip_non_native and builtin.object_format != .wasm) {
14561454 @panic("Attempted to compile for object format that was disabled by build configuration");
14571455 }
1458 if (wasm.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
1459 try wasm.zigObjectPtr().?.updateDecl(wasm, mod, decl_index);
1456 if (wasm.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
1457 try wasm.zigObjectPtr().?.updateDecl(wasm, pt, decl_index);
14601458}
14611459
1462pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1460pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Zcu, decl_index: InternPool.DeclIndex) !void {
14631461 if (wasm.llvm_object) |_| return;
14641462 try wasm.zigObjectPtr().?.updateDeclLineNumber(mod, decl_index);
14651463}
......@@ -1506,8 +1504,8 @@ fn getFunctionSignature(wasm: *const Wasm, loc: SymbolLoc) std.wasm.Type {
15061504/// Lowers a constant typed value to a local symbol and atom.
15071505/// Returns the symbol index of the local
15081506/// The given `decl` is the parent decl whom owns the constant.
1509pub fn lowerUnnamedConst(wasm: *Wasm, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1510 return wasm.zigObjectPtr().?.lowerUnnamedConst(wasm, val, decl_index);
1507pub fn lowerUnnamedConst(wasm: *Wasm, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1508 return wasm.zigObjectPtr().?.lowerUnnamedConst(wasm, pt, val, decl_index);
15111509}
15121510
15131511/// Returns the symbol index from a symbol of which its flag is set global,
......@@ -1531,11 +1529,12 @@ pub fn getDeclVAddr(
15311529
15321530pub fn lowerAnonDecl(
15331531 wasm: *Wasm,
1532 pt: Zcu.PerThread,
15341533 decl_val: InternPool.Index,
15351534 explicit_alignment: Alignment,
1536 src_loc: Module.LazySrcLoc,
1535 src_loc: Zcu.LazySrcLoc,
15371536) !codegen.Result {
1538 return wasm.zigObjectPtr().?.lowerAnonDecl(wasm, decl_val, explicit_alignment, src_loc);
1537 return wasm.zigObjectPtr().?.lowerAnonDecl(wasm, pt, decl_val, explicit_alignment, src_loc);
15391538}
15401539
15411540pub fn getAnonDeclVAddr(wasm: *Wasm, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
......@@ -1553,15 +1552,15 @@ pub fn deleteExport(
15531552
15541553pub fn updateExports(
15551554 wasm: *Wasm,
1556 mod: *Module,
1557 exported: Module.Exported,
1555 pt: Zcu.PerThread,
1556 exported: Zcu.Exported,
15581557 export_indices: []const u32,
15591558) !void {
15601559 if (build_options.skip_non_native and builtin.object_format != .wasm) {
15611560 @panic("Attempted to compile for object format that was disabled by build configuration");
15621561 }
1563 if (wasm.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
1564 return wasm.zigObjectPtr().?.updateExports(wasm, mod, exported, export_indices);
1562 if (wasm.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
1563 return wasm.zigObjectPtr().?.updateExports(wasm, pt, exported, export_indices);
15651564}
15661565
15671566pub fn freeDecl(wasm: *Wasm, decl_index: InternPool.DeclIndex) void {
......@@ -2466,18 +2465,18 @@ fn appendDummySegment(wasm: *Wasm) !void {
24662465 });
24672466}
24682467
2469pub fn flush(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
2468pub fn flush(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
24702469 const comp = wasm.base.comp;
24712470 const use_lld = build_options.have_llvm and comp.config.use_lld;
24722471
24732472 if (use_lld) {
2474 return wasm.linkWithLLD(arena, prog_node);
2473 return wasm.linkWithLLD(arena, tid, prog_node);
24752474 }
2476 return wasm.flushModule(arena, prog_node);
2475 return wasm.flushModule(arena, tid, prog_node);
24772476}
24782477
24792478/// Uses the in-house linker to link one or multiple object -and archive files into a WebAssembly binary.
2480pub fn flushModule(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
2479pub fn flushModule(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
24812480 const tracy = trace(@src());
24822481 defer tracy.end();
24832482
......@@ -2513,7 +2512,7 @@ pub fn flushModule(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node)
25132512 const wasi_exec_model = comp.config.wasi_exec_model;
25142513
25152514 if (wasm.zigObjectPtr()) |zig_object| {
2516 try zig_object.flushModule(wasm);
2515 try zig_object.flushModule(wasm, tid);
25172516 }
25182517
25192518 // When the target os is WASI, we allow linking with WASI-LIBC
......@@ -3324,7 +3323,7 @@ fn emitImport(wasm: *Wasm, writer: anytype, import: types.Import) !void {
33243323 }
33253324}
33263325
3327fn linkWithLLD(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) !void {
3326fn linkWithLLD(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
33283327 const tracy = trace(@src());
33293328 defer tracy.end();
33303329
......@@ -3342,7 +3341,7 @@ fn linkWithLLD(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) !voi
33423341 // If there is no Zig code to compile, then we should skip flushing the output file because it
33433342 // will not be part of the linker line anyway.
33443343 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
3345 try wasm.flushModule(arena, prog_node);
3344 try wasm.flushModule(arena, tid, prog_node);
33463345
33473346 if (fs.path.dirname(full_out_path)) |dirname| {
33483347 break :blk try fs.path.join(arena, &.{ dirname, wasm.base.zcu_object_sub_path.? });
......@@ -4009,8 +4008,8 @@ pub fn storeDeclType(wasm: *Wasm, decl_index: InternPool.DeclIndex, func_type: s
40094008/// Returns the symbol index of the error name table.
40104009///
40114010/// When the symbol does not yet exist, it will create a new one instead.
4012pub fn getErrorTableSymbol(wasm_file: *Wasm) !u32 {
4013 const sym_index = try wasm_file.zigObjectPtr().?.getErrorTableSymbol(wasm_file);
4011pub fn getErrorTableSymbol(wasm_file: *Wasm, pt: Zcu.PerThread) !u32 {
4012 const sym_index = try wasm_file.zigObjectPtr().?.getErrorTableSymbol(wasm_file, pt);
40144013 return @intFromEnum(sym_index);
40154014}
40164015
src/link/Wasm/ZigObject.zig+59-41
......@@ -241,9 +241,10 @@ pub fn allocateSymbol(zig_object: *ZigObject, gpa: std.mem.Allocator) !Symbol.In
241241pub fn updateDecl(
242242 zig_object: *ZigObject,
243243 wasm_file: *Wasm,
244 mod: *Module,
244 pt: Zcu.PerThread,
245245 decl_index: InternPool.DeclIndex,
246246) !void {
247 const mod = pt.zcu;
247248 const decl = mod.declPtr(decl_index);
248249 if (decl.val.getFunction(mod)) |_| {
249250 return;
......@@ -269,6 +270,7 @@ pub fn updateDecl(
269270
270271 const res = try codegen.generateSymbol(
271272 &wasm_file.base,
273 pt,
272274 decl.navSrcLoc(mod),
273275 val,
274276 &code_writer,
......@@ -285,21 +287,21 @@ pub fn updateDecl(
285287 },
286288 };
287289
288 return zig_object.finishUpdateDecl(wasm_file, decl_index, code);
290 return zig_object.finishUpdateDecl(wasm_file, pt, decl_index, code);
289291}
290292
291293pub fn updateFunc(
292294 zig_object: *ZigObject,
293295 wasm_file: *Wasm,
294 mod: *Module,
296 pt: Zcu.PerThread,
295297 func_index: InternPool.Index,
296298 air: Air,
297299 liveness: Liveness,
298300) !void {
299301 const gpa = wasm_file.base.comp.gpa;
300 const func = mod.funcInfo(func_index);
302 const func = pt.zcu.funcInfo(func_index);
301303 const decl_index = func.owner_decl;
302 const decl = mod.declPtr(decl_index);
304 const decl = pt.zcu.declPtr(decl_index);
303305 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
304306 const atom = wasm_file.getAtomPtr(atom_index);
305307 atom.clear();
......@@ -308,7 +310,8 @@ pub fn updateFunc(
308310 defer code_writer.deinit();
309311 const result = try codegen.generateFunction(
310312 &wasm_file.base,
311 decl.navSrcLoc(mod),
313 pt,
314 decl.navSrcLoc(pt.zcu),
312315 func_index,
313316 air,
314317 liveness,
......@@ -320,29 +323,31 @@ pub fn updateFunc(
320323 .ok => code_writer.items,
321324 .fail => |em| {
322325 decl.analysis = .codegen_failure;
323 try mod.failed_analysis.put(mod.gpa, AnalUnit.wrap(.{ .decl = decl_index }), em);
326 try pt.zcu.failed_analysis.put(gpa, AnalUnit.wrap(.{ .decl = decl_index }), em);
324327 return;
325328 },
326329 };
327330
328 return zig_object.finishUpdateDecl(wasm_file, decl_index, code);
331 return zig_object.finishUpdateDecl(wasm_file, pt, decl_index, code);
329332}
330333
331334fn finishUpdateDecl(
332335 zig_object: *ZigObject,
333336 wasm_file: *Wasm,
337 pt: Zcu.PerThread,
334338 decl_index: InternPool.DeclIndex,
335339 code: []const u8,
336340) !void {
337 const gpa = wasm_file.base.comp.gpa;
338 const zcu = wasm_file.base.comp.module.?;
341 const zcu = pt.zcu;
342 const ip = &zcu.intern_pool;
343 const gpa = zcu.gpa;
339344 const decl = zcu.declPtr(decl_index);
340345 const decl_info = zig_object.decls_map.get(decl_index).?;
341346 const atom_index = decl_info.atom;
342347 const atom = wasm_file.getAtomPtr(atom_index);
343348 const sym = zig_object.symbol(atom.sym_index);
344349 const full_name = try decl.fullyQualifiedName(zcu);
345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&zcu.intern_pool));
350 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(ip));
346351 try atom.code.appendSlice(gpa, code);
347352 atom.size = @intCast(code.len);
348353
......@@ -382,7 +387,7 @@ fn finishUpdateDecl(
382387 // Will be freed upon freeing of decl or after cleanup of Wasm binary.
383388 const full_segment_name = try std.mem.concat(gpa, u8, &.{
384389 segment_name,
385 full_name.toSlice(&zcu.intern_pool),
390 full_name.toSlice(ip),
386391 });
387392 errdefer gpa.free(full_segment_name);
388393 sym.tag = .data;
......@@ -390,7 +395,7 @@ fn finishUpdateDecl(
390395 },
391396 }
392397 if (code.len == 0) return;
393 atom.alignment = decl.getAlignment(zcu);
398 atom.alignment = decl.getAlignment(pt);
394399}
395400
396401/// Creates and initializes a new segment in the 'Data' section.
......@@ -437,9 +442,10 @@ pub fn getOrCreateAtomForDecl(zig_object: *ZigObject, wasm_file: *Wasm, decl_ind
437442pub fn lowerAnonDecl(
438443 zig_object: *ZigObject,
439444 wasm_file: *Wasm,
445 pt: Zcu.PerThread,
440446 decl_val: InternPool.Index,
441447 explicit_alignment: InternPool.Alignment,
442 src_loc: Module.LazySrcLoc,
448 src_loc: Zcu.LazySrcLoc,
443449) !codegen.Result {
444450 const gpa = wasm_file.base.comp.gpa;
445451 const gop = try zig_object.anon_decls.getOrPut(gpa, decl_val);
......@@ -449,7 +455,7 @@ pub fn lowerAnonDecl(
449455 @intFromEnum(decl_val),
450456 }) catch unreachable;
451457
452 switch (try zig_object.lowerConst(wasm_file, name, Value.fromInterned(decl_val), src_loc)) {
458 switch (try zig_object.lowerConst(wasm_file, pt, name, Value.fromInterned(decl_val), src_loc)) {
453459 .ok => |atom_index| zig_object.anon_decls.values()[gop.index] = atom_index,
454460 .fail => |em| return .{ .fail = em },
455461 }
......@@ -469,9 +475,15 @@ pub fn lowerAnonDecl(
469475/// Lowers a constant typed value to a local symbol and atom.
470476/// Returns the symbol index of the local
471477/// The given `decl` is the parent decl whom owns the constant.
472pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, decl_index: InternPool.DeclIndex) !u32 {
473 const gpa = wasm_file.base.comp.gpa;
474 const mod = wasm_file.base.comp.module.?;
478pub fn lowerUnnamedConst(
479 zig_object: *ZigObject,
480 wasm_file: *Wasm,
481 pt: Zcu.PerThread,
482 val: Value,
483 decl_index: InternPool.DeclIndex,
484) !u32 {
485 const mod = pt.zcu;
486 const gpa = mod.gpa;
475487 std.debug.assert(val.typeOf(mod).zigTypeTag(mod) != .Fn); // cannot create local symbols for functions
476488 const decl = mod.declPtr(decl_index);
477489
......@@ -494,7 +506,7 @@ pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, d
494506 else
495507 decl.navSrcLoc(mod);
496508
497 switch (try zig_object.lowerConst(wasm_file, name, val, decl_src)) {
509 switch (try zig_object.lowerConst(wasm_file, pt, name, val, decl_src)) {
498510 .ok => |atom_index| {
499511 try wasm_file.getAtomPtr(parent_atom_index).locals.append(gpa, atom_index);
500512 return @intFromEnum(wasm_file.getAtom(atom_index).sym_index);
......@@ -509,10 +521,17 @@ pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, d
509521
510522const LowerConstResult = union(enum) {
511523 ok: Atom.Index,
512 fail: *Module.ErrorMsg,
524 fail: *Zcu.ErrorMsg,
513525};
514526
515fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: Value, src_loc: Module.LazySrcLoc) !LowerConstResult {
527fn lowerConst(
528 zig_object: *ZigObject,
529 wasm_file: *Wasm,
530 pt: Zcu.PerThread,
531 name: []const u8,
532 val: Value,
533 src_loc: Zcu.LazySrcLoc,
534) !LowerConstResult {
516535 const gpa = wasm_file.base.comp.gpa;
517536 const mod = wasm_file.base.comp.module.?;
518537
......@@ -526,7 +545,7 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
526545
527546 const code = code: {
528547 const atom = wasm_file.getAtomPtr(atom_index);
529 atom.alignment = ty.abiAlignment(mod);
548 atom.alignment = ty.abiAlignment(pt);
530549 const segment_name = try std.mem.concat(gpa, u8, &.{ ".rodata.", name });
531550 errdefer gpa.free(segment_name);
532551 zig_object.symbol(sym_index).* = .{
......@@ -536,13 +555,14 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
536555 .index = try zig_object.createDataSegment(
537556 gpa,
538557 segment_name,
539 ty.abiAlignment(mod),
558 ty.abiAlignment(pt),
540559 ),
541560 .virtual_address = undefined,
542561 };
543562
544563 const result = try codegen.generateSymbol(
545564 &wasm_file.base,
565 pt,
546566 src_loc,
547567 val,
548568 &value_bytes,
......@@ -568,7 +588,7 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
568588/// Returns the symbol index of the error name table.
569589///
570590/// When the symbol does not yet exist, it will create a new one instead.
571pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Index {
591pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm, pt: Zcu.PerThread) !Symbol.Index {
572592 if (zig_object.error_table_symbol != .null) {
573593 return zig_object.error_table_symbol;
574594 }
......@@ -581,8 +601,7 @@ pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Ind
581601 const atom_index = try wasm_file.createAtom(sym_index, zig_object.index);
582602 const atom = wasm_file.getAtomPtr(atom_index);
583603 const slice_ty = Type.slice_const_u8_sentinel_0;
584 const mod = wasm_file.base.comp.module.?;
585 atom.alignment = slice_ty.abiAlignment(mod);
604 atom.alignment = slice_ty.abiAlignment(pt);
586605
587606 const sym_name = try zig_object.string_table.insert(gpa, "__zig_err_name_table");
588607 const segment_name = try gpa.dupe(u8, ".rodata.__zig_err_name_table");
......@@ -604,7 +623,7 @@ pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Ind
604623///
605624/// This creates a table that consists of pointers and length to each error name.
606625/// The table is what is being pointed to within the runtime bodies that are generated.
607fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
626fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm, tid: Zcu.PerThread.Id) !void {
608627 if (zig_object.error_table_symbol == .null) return;
609628 const gpa = wasm_file.base.comp.gpa;
610629 const atom_index = wasm_file.symbol_atom.get(.{ .file = zig_object.index, .index = zig_object.error_table_symbol }).?;
......@@ -631,11 +650,11 @@ fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
631650
632651 // Addend for each relocation to the table
633652 var addend: u32 = 0;
634 const mod = wasm_file.base.comp.module.?;
635 for (mod.global_error_set.keys()) |error_name| {
653 const pt: Zcu.PerThread = .{ .zcu = wasm_file.base.comp.module.?, .tid = tid };
654 for (pt.zcu.global_error_set.keys()) |error_name| {
636655 const atom = wasm_file.getAtomPtr(atom_index);
637656
638 const error_name_slice = error_name.toSlice(&mod.intern_pool);
657 const error_name_slice = error_name.toSlice(&pt.zcu.intern_pool);
639658 const len: u32 = @intCast(error_name_slice.len + 1); // names are 0-terminated
640659
641660 const slice_ty = Type.slice_const_u8_sentinel_0;
......@@ -650,14 +669,14 @@ fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
650669 .offset = offset,
651670 .addend = @intCast(addend),
652671 });
653 atom.size += @intCast(slice_ty.abiSize(mod));
672 atom.size += @intCast(slice_ty.abiSize(pt));
654673 addend += len;
655674
656675 // as we updated the error name table, we now store the actual name within the names atom
657676 try names_atom.code.ensureUnusedCapacity(gpa, len);
658677 names_atom.code.appendSliceAssumeCapacity(error_name_slice[0..len]);
659678
660 log.debug("Populated error name: '{}'", .{error_name.fmt(&mod.intern_pool)});
679 log.debug("Populated error name: '{}'", .{error_name.fmt(&pt.zcu.intern_pool)});
661680 }
662681 names_atom.size = addend;
663682 zig_object.error_names_atom = names_atom_index;
......@@ -858,10 +877,11 @@ pub fn deleteExport(
858877pub fn updateExports(
859878 zig_object: *ZigObject,
860879 wasm_file: *Wasm,
861 mod: *Module,
862 exported: Module.Exported,
880 pt: Zcu.PerThread,
881 exported: Zcu.Exported,
863882 export_indices: []const u32,
864883) !void {
884 const mod = pt.zcu;
865885 const decl_index = switch (exported) {
866886 .decl_index => |i| i,
867887 .value => |val| {
......@@ -880,7 +900,7 @@ pub fn updateExports(
880900 for (export_indices) |export_idx| {
881901 const exp = mod.all_exports.items[export_idx];
882902 if (exp.opts.section.toSlice(&mod.intern_pool)) |section| {
883 try mod.failed_exports.putNoClobber(gpa, export_idx, try Module.ErrorMsg.create(
903 try mod.failed_exports.putNoClobber(gpa, export_idx, try Zcu.ErrorMsg.create(
884904 gpa,
885905 decl.navSrcLoc(mod),
886906 "Unimplemented: ExportOptions.section '{s}'",
......@@ -913,7 +933,7 @@ pub fn updateExports(
913933 },
914934 .strong => {}, // symbols are strong by default
915935 .link_once => {
916 try mod.failed_exports.putNoClobber(gpa, export_idx, try Module.ErrorMsg.create(
936 try mod.failed_exports.putNoClobber(gpa, export_idx, try Zcu.ErrorMsg.create(
917937 gpa,
918938 decl.navSrcLoc(mod),
919939 "Unimplemented: LinkOnce",
......@@ -1096,7 +1116,7 @@ pub fn createDebugSectionForIndex(zig_object: *ZigObject, wasm_file: *Wasm, inde
10961116 return atom_index;
10971117}
10981118
1099pub fn updateDeclLineNumber(zig_object: *ZigObject, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1119pub fn updateDeclLineNumber(zig_object: *ZigObject, mod: *Zcu, decl_index: InternPool.DeclIndex) !void {
11001120 if (zig_object.dwarf) |*dw| {
11011121 const decl = mod.declPtr(decl_index);
11021122 const decl_name = try decl.fullyQualifiedName(mod);
......@@ -1228,8 +1248,8 @@ fn appendFunction(zig_object: *ZigObject, gpa: std.mem.Allocator, func: std.wasm
12281248 return index;
12291249}
12301250
1231pub fn flushModule(zig_object: *ZigObject, wasm_file: *Wasm) !void {
1232 try zig_object.populateErrorNameTable(wasm_file);
1251pub fn flushModule(zig_object: *ZigObject, wasm_file: *Wasm, tid: Zcu.PerThread.Id) !void {
1252 try zig_object.populateErrorNameTable(wasm_file, tid);
12331253 try zig_object.setupErrorsLen(wasm_file);
12341254}
12351255
......@@ -1248,8 +1268,6 @@ const File = @import("file.zig").File;
12481268const InternPool = @import("../../InternPool.zig");
12491269const Liveness = @import("../../Liveness.zig");
12501270const Zcu = @import("../../Zcu.zig");
1251/// Deprecated.
1252const Module = Zcu;
12531271const StringTable = @import("../StringTable.zig");
12541272const Symbol = @import("Symbol.zig");
12551273const Type = @import("../../Type.zig");
src/main.zig+4-4
......@@ -172,7 +172,7 @@ pub fn main() anyerror!void {
172172 }
173173 // We would prefer to use raw libc allocator here, but cannot
174174 // use it if it won't support the alignment we need.
175 if (@alignOf(std.c.max_align_t) < @alignOf(i128)) {
175 if (@alignOf(std.c.max_align_t) < @max(@alignOf(i128), std.atomic.cache_line)) {
176176 break :gpa std.heap.c_allocator;
177177 }
178178 break :gpa std.heap.raw_c_allocator;
......@@ -3092,7 +3092,7 @@ fn buildOutputType(
30923092 defer emit_implib_resolved.deinit();
30933093
30943094 var thread_pool: ThreadPool = undefined;
3095 try thread_pool.init(.{ .allocator = gpa });
3095 try thread_pool.init(.{ .allocator = gpa, .track_ids = true });
30963096 defer thread_pool.deinit();
30973097
30983098 var cleanup_local_cache_dir: ?fs.Dir = null;
......@@ -4895,7 +4895,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
48954895 child_argv.items[argv_index_cache_dir] = local_cache_directory.path orelse cwd_path;
48964896
48974897 var thread_pool: ThreadPool = undefined;
4898 try thread_pool.init(.{ .allocator = gpa });
4898 try thread_pool.init(.{ .allocator = gpa, .track_ids = true });
48994899 defer thread_pool.deinit();
49004900
49014901 // Dummy http client that is not actually used when only_core_functionality is enabled.
......@@ -5329,7 +5329,7 @@ fn jitCmd(
53295329 defer global_cache_directory.handle.close();
53305330
53315331 var thread_pool: ThreadPool = undefined;
5332 try thread_pool.init(.{ .allocator = gpa });
5332 try thread_pool.init(.{ .allocator = gpa, .track_ids = true });
53335333 defer thread_pool.deinit();
53345334
53355335 var child_argv: std.ArrayListUnmanaged([]const u8) = .{};
src/mutable_value.zig+48-52
......@@ -54,46 +54,44 @@ pub const MutableValue = union(enum) {
5454 payload: *MutableValue,
5555 };
5656
57 pub fn intern(mv: MutableValue, zcu: *Zcu, arena: Allocator) Allocator.Error!Value {
58 const ip = &zcu.intern_pool;
59 const gpa = zcu.gpa;
57 pub fn intern(mv: MutableValue, pt: Zcu.PerThread, arena: Allocator) Allocator.Error!Value {
6058 return Value.fromInterned(switch (mv) {
6159 .interned => |ip_index| ip_index,
62 .eu_payload => |sv| try ip.get(gpa, .{ .error_union = .{
60 .eu_payload => |sv| try pt.intern(.{ .error_union = .{
6361 .ty = sv.ty,
64 .val = .{ .payload = (try sv.child.intern(zcu, arena)).toIntern() },
62 .val = .{ .payload = (try sv.child.intern(pt, arena)).toIntern() },
6563 } }),
66 .opt_payload => |sv| try ip.get(gpa, .{ .opt = .{
64 .opt_payload => |sv| try pt.intern(.{ .opt = .{
6765 .ty = sv.ty,
68 .val = (try sv.child.intern(zcu, arena)).toIntern(),
66 .val = (try sv.child.intern(pt, arena)).toIntern(),
6967 } }),
70 .repeated => |sv| try ip.get(gpa, .{ .aggregate = .{
68 .repeated => |sv| try pt.intern(.{ .aggregate = .{
7169 .ty = sv.ty,
72 .storage = .{ .repeated_elem = (try sv.child.intern(zcu, arena)).toIntern() },
70 .storage = .{ .repeated_elem = (try sv.child.intern(pt, arena)).toIntern() },
7371 } }),
74 .bytes => |b| try ip.get(gpa, .{ .aggregate = .{
72 .bytes => |b| try pt.intern(.{ .aggregate = .{
7573 .ty = b.ty,
76 .storage = .{ .bytes = try ip.getOrPutString(gpa, b.data, .maybe_embedded_nulls) },
74 .storage = .{ .bytes = try pt.zcu.intern_pool.getOrPutString(pt.zcu.gpa, b.data, .maybe_embedded_nulls) },
7775 } }),
7876 .aggregate => |a| {
7977 const elems = try arena.alloc(InternPool.Index, a.elems.len);
8078 for (a.elems, elems) |mut_elem, *interned_elem| {
81 interned_elem.* = (try mut_elem.intern(zcu, arena)).toIntern();
79 interned_elem.* = (try mut_elem.intern(pt, arena)).toIntern();
8280 }
83 return Value.fromInterned(try ip.get(gpa, .{ .aggregate = .{
81 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
8482 .ty = a.ty,
8583 .storage = .{ .elems = elems },
8684 } }));
8785 },
88 .slice => |s| try ip.get(gpa, .{ .slice = .{
86 .slice => |s| try pt.intern(.{ .slice = .{
8987 .ty = s.ty,
90 .ptr = (try s.ptr.intern(zcu, arena)).toIntern(),
91 .len = (try s.len.intern(zcu, arena)).toIntern(),
88 .ptr = (try s.ptr.intern(pt, arena)).toIntern(),
89 .len = (try s.len.intern(pt, arena)).toIntern(),
9290 } }),
93 .un => |u| try ip.get(gpa, .{ .un = .{
91 .un => |u| try pt.intern(.{ .un = .{
9492 .ty = u.ty,
9593 .tag = u.tag,
96 .val = (try u.payload.intern(zcu, arena)).toIntern(),
94 .val = (try u.payload.intern(pt, arena)).toIntern(),
9795 } }),
9896 });
9997 }
......@@ -108,13 +106,13 @@ pub const MutableValue = union(enum) {
108106 /// If `!allow_repeated`, the `repeated` representation will not be used.
109107 pub fn unintern(
110108 mv: *MutableValue,
111 zcu: *Zcu,
109 pt: Zcu.PerThread,
112110 arena: Allocator,
113111 allow_bytes: bool,
114112 allow_repeated: bool,
115113 ) Allocator.Error!void {
114 const zcu = pt.zcu;
116115 const ip = &zcu.intern_pool;
117 const gpa = zcu.gpa;
118116 switch (mv.*) {
119117 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
120118 .opt => |opt| if (opt.val != .none) {
......@@ -170,7 +168,7 @@ pub const MutableValue = union(enum) {
170168 } else {
171169 const mut_elems = try arena.alloc(MutableValue, len);
172170 for (bytes.toSlice(len, ip), mut_elems) |b, *mut_elem| {
173 mut_elem.* = .{ .interned = try ip.get(gpa, .{ .int = .{
171 mut_elem.* = .{ .interned = try pt.intern(.{ .int = .{
174172 .ty = .u8_type,
175173 .storage = .{ .u64 = b },
176174 } }) };
......@@ -221,12 +219,12 @@ pub const MutableValue = union(enum) {
221219 switch (type_tag) {
222220 .Array, .Vector => {
223221 const elem_ty = ip.childType(ty_ip);
224 const undef_elem = try ip.get(gpa, .{ .undef = elem_ty });
222 const undef_elem = try pt.intern(.{ .undef = elem_ty });
225223 @memset(elems[0..@intCast(len_no_sent)], .{ .interned = undef_elem });
226224 },
227225 .Struct => for (elems[0..@intCast(len_no_sent)], 0..) |*mut_elem, i| {
228226 const field_ty = ty.structFieldType(i, zcu).toIntern();
229 mut_elem.* = .{ .interned = try ip.get(gpa, .{ .undef = field_ty }) };
227 mut_elem.* = .{ .interned = try pt.intern(.{ .undef = field_ty }) };
230228 },
231229 else => unreachable,
232230 }
......@@ -238,7 +236,7 @@ pub const MutableValue = union(enum) {
238236 } else {
239237 const repeated_val = try arena.create(MutableValue);
240238 repeated_val.* = .{
241 .interned = try ip.get(gpa, .{ .undef = ip.childType(ty_ip) }),
239 .interned = try pt.intern(.{ .undef = ip.childType(ty_ip) }),
242240 };
243241 mv.* = .{ .repeated = .{
244242 .ty = ty_ip,
......@@ -248,11 +246,8 @@ pub const MutableValue = union(enum) {
248246 },
249247 .Union => {
250248 const payload = try arena.create(MutableValue);
251 const backing_ty = try Type.fromInterned(ty_ip).unionBackingType(zcu);
252 payload.* = .{ .interned = try ip.get(
253 gpa,
254 .{ .undef = backing_ty.toIntern() },
255 ) };
249 const backing_ty = try Type.fromInterned(ty_ip).unionBackingType(pt);
250 payload.* = .{ .interned = try pt.intern(.{ .undef = backing_ty.toIntern() }) };
256251 mv.* = .{ .un = .{
257252 .ty = ty_ip,
258253 .tag = .none,
......@@ -264,8 +259,8 @@ pub const MutableValue = union(enum) {
264259 if (ptr_ty.flags.size != .Slice) return;
265260 const ptr = try arena.create(MutableValue);
266261 const len = try arena.create(MutableValue);
267 ptr.* = .{ .interned = try ip.get(gpa, .{ .undef = ip.slicePtrType(ty_ip) }) };
268 len.* = .{ .interned = try ip.get(gpa, .{ .undef = .usize_type }) };
262 ptr.* = .{ .interned = try pt.intern(.{ .undef = ip.slicePtrType(ty_ip) }) };
263 len.* = .{ .interned = try pt.intern(.{ .undef = .usize_type }) };
269264 mv.* = .{ .slice = .{
270265 .ty = ty_ip,
271266 .ptr = ptr,
......@@ -279,7 +274,7 @@ pub const MutableValue = union(enum) {
279274 .bytes => |bytes| if (!allow_bytes) {
280275 const elems = try arena.alloc(MutableValue, bytes.data.len);
281276 for (bytes.data, elems) |byte, *interned_byte| {
282 interned_byte.* = .{ .interned = try ip.get(gpa, .{ .int = .{
277 interned_byte.* = .{ .interned = try pt.intern(.{ .int = .{
283278 .ty = .u8_type,
284279 .storage = .{ .u64 = byte },
285280 } }) };
......@@ -298,22 +293,22 @@ pub const MutableValue = union(enum) {
298293 /// The returned pointer is valid until the representation of `mv` changes.
299294 pub fn elem(
300295 mv: *MutableValue,
301 zcu: *Zcu,
296 pt: Zcu.PerThread,
302297 arena: Allocator,
303298 field_idx: usize,
304299 ) Allocator.Error!*MutableValue {
300 const zcu = pt.zcu;
305301 const ip = &zcu.intern_pool;
306 const gpa = zcu.gpa;
307302 // Convert to the `aggregate` representation.
308303 switch (mv.*) {
309304 .eu_payload, .opt_payload, .un => unreachable,
310305 .interned => {
311 try mv.unintern(zcu, arena, false, false);
306 try mv.unintern(pt, arena, false, false);
312307 },
313308 .bytes => |bytes| {
314309 const elems = try arena.alloc(MutableValue, bytes.data.len);
315310 for (bytes.data, elems) |byte, *interned_byte| {
316 interned_byte.* = .{ .interned = try ip.get(gpa, .{ .int = .{
311 interned_byte.* = .{ .interned = try pt.intern(.{ .int = .{
317312 .ty = .u8_type,
318313 .storage = .{ .u64 = byte },
319314 } }) };
......@@ -351,14 +346,15 @@ pub const MutableValue = union(enum) {
351346 /// For slices, uses `Value.slice_ptr_index` and `Value.slice_len_index`.
352347 pub fn setElem(
353348 mv: *MutableValue,
354 zcu: *Zcu,
349 pt: Zcu.PerThread,
355350 arena: Allocator,
356351 field_idx: usize,
357352 field_val: MutableValue,
358353 ) Allocator.Error!void {
354 const zcu = pt.zcu;
359355 const ip = &zcu.intern_pool;
360356 const is_trivial_int = field_val.isTrivialInt(zcu);
361 try mv.unintern(zcu, arena, is_trivial_int, true);
357 try mv.unintern(pt, arena, is_trivial_int, true);
362358 switch (mv.*) {
363359 .interned,
364360 .eu_payload,
......@@ -373,7 +369,7 @@ pub const MutableValue = union(enum) {
373369 .bytes => |b| {
374370 assert(is_trivial_int);
375371 assert(field_val.typeOf(zcu).toIntern() == .u8_type);
376 b.data[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(zcu));
372 b.data[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(pt));
377373 },
378374 .repeated => |r| {
379375 if (field_val.eqlTrivial(r.child.*)) return;
......@@ -386,9 +382,9 @@ pub const MutableValue = union(enum) {
386382 {
387383 // We can use the `bytes` representation.
388384 const bytes = try arena.alloc(u8, @intCast(len_inc_sent));
389 const repeated_byte = Value.fromInterned(r.child.interned).toUnsignedInt(zcu);
385 const repeated_byte = Value.fromInterned(r.child.interned).toUnsignedInt(pt);
390386 @memset(bytes, @intCast(repeated_byte));
391 bytes[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(zcu));
387 bytes[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(pt));
392388 mv.* = .{ .bytes = .{
393389 .ty = r.ty,
394390 .data = bytes,
......@@ -435,7 +431,7 @@ pub const MutableValue = union(enum) {
435431 } else {
436432 const bytes = try arena.alloc(u8, a.elems.len);
437433 for (a.elems, bytes) |elem_val, *b| {
438 b.* = @intCast(Value.fromInterned(elem_val.interned).toUnsignedInt(zcu));
434 b.* = @intCast(Value.fromInterned(elem_val.interned).toUnsignedInt(pt));
439435 }
440436 mv.* = .{ .bytes = .{
441437 .ty = a.ty,
......@@ -451,7 +447,7 @@ pub const MutableValue = union(enum) {
451447 /// For slices, uses `Value.slice_ptr_index` and `Value.slice_len_index`.
452448 pub fn getElem(
453449 mv: MutableValue,
454 zcu: *Zcu,
450 pt: Zcu.PerThread,
455451 field_idx: usize,
456452 ) Allocator.Error!MutableValue {
457453 return switch (mv) {
......@@ -459,16 +455,16 @@ pub const MutableValue = union(enum) {
459455 .opt_payload,
460456 => unreachable,
461457 .interned => |ip_index| {
462 const ty = Type.fromInterned(zcu.intern_pool.typeOf(ip_index));
463 switch (ty.zigTypeTag(zcu)) {
464 .Array, .Vector => return .{ .interned = (try Value.fromInterned(ip_index).elemValue(zcu, field_idx)).toIntern() },
465 .Struct, .Union => return .{ .interned = (try Value.fromInterned(ip_index).fieldValue(zcu, field_idx)).toIntern() },
458 const ty = Type.fromInterned(pt.zcu.intern_pool.typeOf(ip_index));
459 switch (ty.zigTypeTag(pt.zcu)) {
460 .Array, .Vector => return .{ .interned = (try Value.fromInterned(ip_index).elemValue(pt, field_idx)).toIntern() },
461 .Struct, .Union => return .{ .interned = (try Value.fromInterned(ip_index).fieldValue(pt, field_idx)).toIntern() },
466462 .Pointer => {
467 assert(ty.isSlice(zcu));
463 assert(ty.isSlice(pt.zcu));
468464 return switch (field_idx) {
469 Value.slice_ptr_index => .{ .interned = Value.fromInterned(ip_index).slicePtr(zcu).toIntern() },
470 Value.slice_len_index => .{ .interned = switch (zcu.intern_pool.indexToKey(ip_index)) {
471 .undef => try zcu.intern(.{ .undef = .usize_type }),
465 Value.slice_ptr_index => .{ .interned = Value.fromInterned(ip_index).slicePtr(pt.zcu).toIntern() },
466 Value.slice_len_index => .{ .interned = switch (pt.zcu.intern_pool.indexToKey(ip_index)) {
467 .undef => try pt.intern(.{ .undef = .usize_type }),
472468 .slice => |s| s.len,
473469 else => unreachable,
474470 } },
......@@ -487,7 +483,7 @@ pub const MutableValue = union(enum) {
487483 Value.slice_len_index => s.len.*,
488484 else => unreachable,
489485 },
490 .bytes => |b| .{ .interned = try zcu.intern(.{ .int = .{
486 .bytes => |b| .{ .interned = try pt.intern(.{ .int = .{
491487 .ty = .u8_type,
492488 .storage = .{ .u64 = b.data[field_idx] },
493489 } }) },
src/print_air.zig+19-19
......@@ -9,7 +9,7 @@ const Air = @import("Air.zig");
99const Liveness = @import("Liveness.zig");
1010const InternPool = @import("InternPool.zig");
1111
12pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void {
12pub fn write(stream: anytype, pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
1313 const instruction_bytes = air.instructions.len *
1414 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
1515 // the debug safety tag but we want to measure release size.
......@@ -42,8 +42,8 @@ pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void
4242 // zig fmt: on
4343
4444 var writer: Writer = .{
45 .module = module,
46 .gpa = module.gpa,
45 .pt = pt,
46 .gpa = pt.zcu.gpa,
4747 .air = air,
4848 .liveness = liveness,
4949 .indent = 2,
......@@ -55,13 +55,13 @@ pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void
5555pub fn writeInst(
5656 stream: anytype,
5757 inst: Air.Inst.Index,
58 module: *Zcu,
58 pt: Zcu.PerThread,
5959 air: Air,
6060 liveness: ?Liveness,
6161) void {
6262 var writer: Writer = .{
63 .module = module,
64 .gpa = module.gpa,
63 .pt = pt,
64 .gpa = pt.zcu.gpa,
6565 .air = air,
6666 .liveness = liveness,
6767 .indent = 2,
......@@ -70,16 +70,16 @@ pub fn writeInst(
7070 writer.writeInst(stream, inst) catch return;
7171}
7272
73pub fn dump(module: *Zcu, air: Air, liveness: ?Liveness) void {
74 write(std.io.getStdErr().writer(), module, air, liveness);
73pub fn dump(pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
74 write(std.io.getStdErr().writer(), pt, air, liveness);
7575}
7676
77pub fn dumpInst(inst: Air.Inst.Index, module: *Zcu, air: Air, liveness: ?Liveness) void {
78 writeInst(std.io.getStdErr().writer(), inst, module, air, liveness);
77pub fn dumpInst(inst: Air.Inst.Index, pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
78 writeInst(std.io.getStdErr().writer(), inst, pt, air, liveness);
7979}
8080
8181const Writer = struct {
82 module: *Zcu,
82 pt: Zcu.PerThread,
8383 gpa: Allocator,
8484 air: Air,
8585 liveness: ?Liveness,
......@@ -345,7 +345,7 @@ const Writer = struct {
345345 }
346346
347347 fn writeType(w: *Writer, s: anytype, ty: Type) !void {
348 return ty.print(s, w.module);
348 return ty.print(s, w.pt);
349349 }
350350
351351 fn writeTy(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
......@@ -424,7 +424,7 @@ const Writer = struct {
424424 }
425425
426426 fn writeAggregateInit(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
427 const mod = w.module;
427 const mod = w.pt.zcu;
428428 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
429429 const vector_ty = ty_pl.ty.toType();
430430 const len = @as(usize, @intCast(vector_ty.arrayLen(mod)));
......@@ -504,7 +504,7 @@ const Writer = struct {
504504 }
505505
506506 fn writeSelect(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
507 const mod = w.module;
507 const mod = w.pt.zcu;
508508 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
509509 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
510510
......@@ -947,11 +947,11 @@ const Writer = struct {
947947 if (@intFromEnum(operand) < InternPool.static_len) {
948948 return s.print("@{}", .{operand});
949949 } else if (operand.toInterned()) |ip_index| {
950 const mod = w.module;
951 const ty = Type.fromInterned(mod.intern_pool.indexToKey(ip_index).typeOf());
950 const pt = w.pt;
951 const ty = Type.fromInterned(pt.zcu.intern_pool.indexToKey(ip_index).typeOf());
952952 try s.print("<{}, {}>", .{
953 ty.fmt(mod),
954 Value.fromInterned(ip_index).fmtValue(mod, null),
953 ty.fmt(pt),
954 Value.fromInterned(ip_index).fmtValue(pt, null),
955955 });
956956 } else {
957957 return w.writeInstIndex(s, operand.toIndex().?, dies);
......@@ -970,7 +970,7 @@ const Writer = struct {
970970 }
971971
972972 fn typeOfIndex(w: *Writer, inst: Air.Inst.Index) Type {
973 const mod = w.module;
973 const mod = w.pt.zcu;
974974 return w.air.typeOfIndex(inst, &mod.intern_pool);
975975 }
976976};
src/print_value.zig+53-52
......@@ -5,8 +5,6 @@ const std = @import("std");
55const Type = @import("Type.zig");
66const Value = @import("Value.zig");
77const Zcu = @import("Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108const Sema = @import("Sema.zig");
119const InternPool = @import("InternPool.zig");
1210const Allocator = std.mem.Allocator;
......@@ -17,7 +15,7 @@ const max_string_len = 256;
1715
1816pub const FormatContext = struct {
1917 val: Value,
20 mod: *Module,
18 pt: Zcu.PerThread,
2119 opt_sema: ?*Sema,
2220 depth: u8,
2321};
......@@ -30,7 +28,7 @@ pub fn format(
3028) !void {
3129 _ = options;
3230 comptime std.debug.assert(fmt.len == 0);
33 return print(ctx.val, writer, ctx.depth, ctx.mod, ctx.opt_sema) catch |err| switch (err) {
31 return print(ctx.val, writer, ctx.depth, ctx.pt, ctx.opt_sema) catch |err| switch (err) {
3432 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function
3533 error.ComptimeBreak, error.ComptimeReturn => unreachable,
3634 error.AnalysisFail => unreachable, // TODO: re-evaluate when we use `opt_sema` more fully
......@@ -42,10 +40,11 @@ pub fn print(
4240 val: Value,
4341 writer: anytype,
4442 level: u8,
45 mod: *Module,
43 pt: Zcu.PerThread,
4644 /// If this `Sema` is provided, we will recurse through pointers where possible to provide friendly output.
4745 opt_sema: ?*Sema,
48) (@TypeOf(writer).Error || Module.CompileError)!void {
46) (@TypeOf(writer).Error || Zcu.CompileError)!void {
47 const mod = pt.zcu;
4948 const ip = &mod.intern_pool;
5049 switch (ip.indexToKey(val.toIntern())) {
5150 .int_type,
......@@ -64,7 +63,7 @@ pub fn print(
6463 .func_type,
6564 .error_set_type,
6665 .inferred_error_set_type,
67 => try Type.print(val.toType(), writer, mod),
66 => try Type.print(val.toType(), writer, pt),
6867 .undef => try writer.writeAll("undefined"),
6968 .simple_value => |simple_value| switch (simple_value) {
7069 .void => try writer.writeAll("{}"),
......@@ -82,13 +81,13 @@ pub fn print(
8281 .int => |int| switch (int.storage) {
8382 inline .u64, .i64, .big_int => |x| try writer.print("{}", .{x}),
8483 .lazy_align => |ty| if (opt_sema != null) {
85 const a = (try Type.fromInterned(ty).abiAlignmentAdvanced(mod, .sema)).scalar;
84 const a = (try Type.fromInterned(ty).abiAlignmentAdvanced(pt, .sema)).scalar;
8685 try writer.print("{}", .{a.toByteUnits() orelse 0});
87 } else try writer.print("@alignOf({})", .{Type.fromInterned(ty).fmt(mod)}),
86 } else try writer.print("@alignOf({})", .{Type.fromInterned(ty).fmt(pt)}),
8887 .lazy_size => |ty| if (opt_sema != null) {
89 const s = (try Type.fromInterned(ty).abiSizeAdvanced(mod, .sema)).scalar;
88 const s = (try Type.fromInterned(ty).abiSizeAdvanced(pt, .sema)).scalar;
9089 try writer.print("{}", .{s});
91 } else try writer.print("@sizeOf({})", .{Type.fromInterned(ty).fmt(mod)}),
90 } else try writer.print("@sizeOf({})", .{Type.fromInterned(ty).fmt(pt)}),
9291 },
9392 .err => |err| try writer.print("error.{}", .{
9493 err.name.fmt(ip),
......@@ -97,7 +96,7 @@ pub fn print(
9796 .err_name => |err_name| try writer.print("error.{}", .{
9897 err_name.fmt(ip),
9998 }),
100 .payload => |payload| try print(Value.fromInterned(payload), writer, level, mod, opt_sema),
99 .payload => |payload| try print(Value.fromInterned(payload), writer, level, pt, opt_sema),
101100 },
102101 .enum_literal => |enum_literal| try writer.print(".{}", .{
103102 enum_literal.fmt(ip),
......@@ -111,7 +110,7 @@ pub fn print(
111110 return writer.writeAll("@enumFromInt(...)");
112111 }
113112 try writer.writeAll("@enumFromInt(");
114 try print(Value.fromInterned(enum_tag.int), writer, level - 1, mod, opt_sema);
113 try print(Value.fromInterned(enum_tag.int), writer, level - 1, pt, opt_sema);
115114 try writer.writeAll(")");
116115 },
117116 .empty_enum_value => try writer.writeAll("(empty enum value)"),
......@@ -128,12 +127,12 @@ pub fn print(
128127 // TODO: eventually we want to load the slice as an array with `opt_sema`, but that's
129128 // currently not possible without e.g. triggering compile errors.
130129 }
131 try printPtr(Value.fromInterned(slice.ptr), writer, level, mod, opt_sema);
130 try printPtr(Value.fromInterned(slice.ptr), writer, level, pt, opt_sema);
132131 try writer.writeAll("[0..");
133132 if (level == 0) {
134133 try writer.writeAll("(...)");
135134 } else {
136 try print(Value.fromInterned(slice.len), writer, level - 1, mod, opt_sema);
135 try print(Value.fromInterned(slice.len), writer, level - 1, pt, opt_sema);
137136 }
138137 try writer.writeAll("]");
139138 },
......@@ -147,28 +146,28 @@ pub fn print(
147146 // TODO: eventually we want to load the pointer with `opt_sema`, but that's
148147 // currently not possible without e.g. triggering compile errors.
149148 }
150 try printPtr(val, writer, level, mod, opt_sema);
149 try printPtr(val, writer, level, pt, opt_sema);
151150 },
152151 .opt => |opt| switch (opt.val) {
153152 .none => try writer.writeAll("null"),
154 else => |payload| try print(Value.fromInterned(payload), writer, level, mod, opt_sema),
153 else => |payload| try print(Value.fromInterned(payload), writer, level, pt, opt_sema),
155154 },
156 .aggregate => |aggregate| try printAggregate(val, aggregate, false, writer, level, mod, opt_sema),
155 .aggregate => |aggregate| try printAggregate(val, aggregate, false, writer, level, pt, opt_sema),
157156 .un => |un| {
158157 if (level == 0) {
159158 try writer.writeAll(".{ ... }");
160159 return;
161160 }
162161 if (un.tag == .none) {
163 const backing_ty = try val.typeOf(mod).unionBackingType(mod);
164 try writer.print("@bitCast(@as({}, ", .{backing_ty.fmt(mod)});
165 try print(Value.fromInterned(un.val), writer, level - 1, mod, opt_sema);
162 const backing_ty = try val.typeOf(mod).unionBackingType(pt);
163 try writer.print("@bitCast(@as({}, ", .{backing_ty.fmt(pt)});
164 try print(Value.fromInterned(un.val), writer, level - 1, pt, opt_sema);
166165 try writer.writeAll("))");
167166 } else {
168167 try writer.writeAll(".{ ");
169 try print(Value.fromInterned(un.tag), writer, level - 1, mod, opt_sema);
168 try print(Value.fromInterned(un.tag), writer, level - 1, pt, opt_sema);
170169 try writer.writeAll(" = ");
171 try print(Value.fromInterned(un.val), writer, level - 1, mod, opt_sema);
170 try print(Value.fromInterned(un.val), writer, level - 1, pt, opt_sema);
172171 try writer.writeAll(" }");
173172 }
174173 },
......@@ -182,13 +181,14 @@ fn printAggregate(
182181 is_ref: bool,
183182 writer: anytype,
184183 level: u8,
185 zcu: *Zcu,
184 pt: Zcu.PerThread,
186185 opt_sema: ?*Sema,
187) (@TypeOf(writer).Error || Module.CompileError)!void {
186) (@TypeOf(writer).Error || Zcu.CompileError)!void {
188187 if (level == 0) {
189188 if (is_ref) try writer.writeByte('&');
190189 return writer.writeAll(".{ ... }");
191190 }
191 const zcu = pt.zcu;
192192 const ip = &zcu.intern_pool;
193193 const ty = Type.fromInterned(aggregate.ty);
194194 switch (ty.zigTypeTag(zcu)) {
......@@ -203,7 +203,7 @@ fn printAggregate(
203203 if (i != 0) try writer.writeAll(", ");
204204 const field_name = ty.structFieldName(@intCast(i), zcu).unwrap().?;
205205 try writer.print(".{i} = ", .{field_name.fmt(ip)});
206 try print(try val.fieldValue(zcu, i), writer, level - 1, zcu, opt_sema);
206 try print(try val.fieldValue(pt, i), writer, level - 1, pt, opt_sema);
207207 }
208208 try writer.writeAll(" }");
209209 return;
......@@ -230,7 +230,7 @@ fn printAggregate(
230230 if (ty.childType(zcu).toIntern() != .u8_type) break :one_byte_str;
231231 const elem_val = Value.fromInterned(aggregate.storage.values()[0]);
232232 if (elem_val.isUndef(zcu)) break :one_byte_str;
233 const byte = elem_val.toUnsignedInt(zcu);
233 const byte = elem_val.toUnsignedInt(pt);
234234 try writer.print("\"{}\"", .{std.zig.fmtEscapes(&.{@intCast(byte)})});
235235 if (!is_ref) try writer.writeAll(".*");
236236 return;
......@@ -253,7 +253,7 @@ fn printAggregate(
253253 const max_len = @min(len, max_aggregate_items);
254254 for (0..max_len) |i| {
255255 if (i != 0) try writer.writeAll(", ");
256 try print(try val.fieldValue(zcu, i), writer, level - 1, zcu, opt_sema);
256 try print(try val.fieldValue(pt, i), writer, level - 1, pt, opt_sema);
257257 }
258258 if (len > max_aggregate_items) {
259259 try writer.writeAll(", ...");
......@@ -261,8 +261,8 @@ fn printAggregate(
261261 return writer.writeAll(" }");
262262}
263263
264fn printPtr(ptr_val: Value, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*Sema) (@TypeOf(writer).Error || Module.CompileError)!void {
265 const ptr = switch (zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
264fn printPtr(ptr_val: Value, writer: anytype, level: u8, pt: Zcu.PerThread, opt_sema: ?*Sema) (@TypeOf(writer).Error || Zcu.CompileError)!void {
265 const ptr = switch (pt.zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
266266 .undef => return writer.writeAll("undefined"),
267267 .ptr => |ptr| ptr,
268268 else => unreachable,
......@@ -270,32 +270,33 @@ fn printPtr(ptr_val: Value, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*S
270270
271271 if (ptr.base_addr == .anon_decl) {
272272 // If the value is an aggregate, we can potentially print it more nicely.
273 switch (zcu.intern_pool.indexToKey(ptr.base_addr.anon_decl.val)) {
273 switch (pt.zcu.intern_pool.indexToKey(ptr.base_addr.anon_decl.val)) {
274274 .aggregate => |agg| return printAggregate(
275275 Value.fromInterned(ptr.base_addr.anon_decl.val),
276276 agg,
277277 true,
278278 writer,
279279 level,
280 zcu,
280 pt,
281281 opt_sema,
282282 ),
283283 else => {},
284284 }
285285 }
286286
287 var arena = std.heap.ArenaAllocator.init(zcu.gpa);
287 var arena = std.heap.ArenaAllocator.init(pt.zcu.gpa);
288288 defer arena.deinit();
289 const derivation = try ptr_val.pointerDerivationAdvanced(arena.allocator(), zcu, opt_sema);
290 try printPtrDerivation(derivation, writer, level, zcu, opt_sema);
289 const derivation = try ptr_val.pointerDerivationAdvanced(arena.allocator(), pt, opt_sema);
290 try printPtrDerivation(derivation, writer, level, pt, opt_sema);
291291}
292292
293293/// Print `derivation` as an lvalue, i.e. such that writing `&` before this gives the pointer value.
294fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*Sema) (@TypeOf(writer).Error || Module.CompileError)!void {
294fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, level: u8, pt: Zcu.PerThread, opt_sema: ?*Sema) (@TypeOf(writer).Error || Zcu.CompileError)!void {
295 const zcu = pt.zcu;
295296 const ip = &zcu.intern_pool;
296297 switch (derivation) {
297298 .int => |int| try writer.print("@as({}, @ptrFromInt({x})).*", .{
298 int.ptr_ty.fmt(zcu),
299 int.ptr_ty.fmt(pt),
299300 int.addr,
300301 }),
301302 .decl_ptr => |decl| {
......@@ -303,33 +304,33 @@ fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, leve
303304 },
304305 .anon_decl_ptr => |anon| {
305306 const ty = Value.fromInterned(anon.val).typeOf(zcu);
306 try writer.print("@as({}, ", .{ty.fmt(zcu)});
307 try print(Value.fromInterned(anon.val), writer, level - 1, zcu, opt_sema);
307 try writer.print("@as({}, ", .{ty.fmt(pt)});
308 try print(Value.fromInterned(anon.val), writer, level - 1, pt, opt_sema);
308309 try writer.writeByte(')');
309310 },
310311 .comptime_alloc_ptr => |info| {
311 try writer.print("@as({}, ", .{info.val.typeOf(zcu).fmt(zcu)});
312 try print(info.val, writer, level - 1, zcu, opt_sema);
312 try writer.print("@as({}, ", .{info.val.typeOf(zcu).fmt(pt)});
313 try print(info.val, writer, level - 1, pt, opt_sema);
313314 try writer.writeByte(')');
314315 },
315316 .comptime_field_ptr => |val| {
316317 const ty = val.typeOf(zcu);
317 try writer.print("@as({}, ", .{ty.fmt(zcu)});
318 try print(val, writer, level - 1, zcu, opt_sema);
318 try writer.print("@as({}, ", .{ty.fmt(pt)});
319 try print(val, writer, level - 1, pt, opt_sema);
319320 try writer.writeByte(')');
320321 },
321322 .eu_payload_ptr => |info| {
322323 try writer.writeByte('(');
323 try printPtrDerivation(info.parent.*, writer, level, zcu, opt_sema);
324 try printPtrDerivation(info.parent.*, writer, level, pt, opt_sema);
324325 try writer.writeAll(" catch unreachable)");
325326 },
326327 .opt_payload_ptr => |info| {
327 try printPtrDerivation(info.parent.*, writer, level, zcu, opt_sema);
328 try printPtrDerivation(info.parent.*, writer, level, pt, opt_sema);
328329 try writer.writeAll(".?");
329330 },
330331 .field_ptr => |field| {
331 try printPtrDerivation(field.parent.*, writer, level, zcu, opt_sema);
332 const agg_ty = (try field.parent.ptrType(zcu)).childType(zcu);
332 try printPtrDerivation(field.parent.*, writer, level, pt, opt_sema);
333 const agg_ty = (try field.parent.ptrType(pt)).childType(zcu);
333334 switch (agg_ty.zigTypeTag(zcu)) {
334335 .Struct => if (agg_ty.structFieldName(field.field_idx, zcu).unwrap()) |field_name| {
335336 try writer.print(".{i}", .{field_name.fmt(ip)});
......@@ -350,16 +351,16 @@ fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, leve
350351 }
351352 },
352353 .elem_ptr => |elem| {
353 try printPtrDerivation(elem.parent.*, writer, level, zcu, opt_sema);
354 try printPtrDerivation(elem.parent.*, writer, level, pt, opt_sema);
354355 try writer.print("[{d}]", .{elem.elem_idx});
355356 },
356357 .offset_and_cast => |oac| if (oac.byte_offset == 0) {
357 try writer.print("@as({}, @ptrCast(", .{oac.new_ptr_ty.fmt(zcu)});
358 try printPtrDerivation(oac.parent.*, writer, level, zcu, opt_sema);
358 try writer.print("@as({}, @ptrCast(", .{oac.new_ptr_ty.fmt(pt)});
359 try printPtrDerivation(oac.parent.*, writer, level, pt, opt_sema);
359360 try writer.writeAll("))");
360361 } else {
361 try writer.print("@as({}, @ptrFromInt(@intFromPtr(", .{oac.new_ptr_ty.fmt(zcu)});
362 try printPtrDerivation(oac.parent.*, writer, level, zcu, opt_sema);
362 try writer.print("@as({}, @ptrFromInt(@intFromPtr(", .{oac.new_ptr_ty.fmt(pt)});
363 try printPtrDerivation(oac.parent.*, writer, level, pt, opt_sema);
363364 try writer.print(") + {d}))", .{oac.byte_offset});
364365 },
365366 }
src/print_zir.zig+4-5
......@@ -7,13 +7,12 @@ const InternPool = @import("InternPool.zig");
77
88const Zir = std.zig.Zir;
99const Zcu = @import("Zcu.zig");
10const Module = Zcu;
1110const LazySrcLoc = Zcu.LazySrcLoc;
1211
1312/// Write human-readable, debug formatted ZIR code to a file.
1413pub fn renderAsTextToFile(
1514 gpa: Allocator,
16 scope_file: *Module.File,
15 scope_file: *Zcu.File,
1716 fs_file: std.fs.File,
1817) !void {
1918 var arena = std.heap.ArenaAllocator.init(gpa);
......@@ -64,7 +63,7 @@ pub fn renderInstructionContext(
6463 gpa: Allocator,
6564 block: []const Zir.Inst.Index,
6665 block_index: usize,
67 scope_file: *Module.File,
66 scope_file: *Zcu.File,
6867 parent_decl_node: Ast.Node.Index,
6968 indent: u32,
7069 stream: anytype,
......@@ -96,7 +95,7 @@ pub fn renderInstructionContext(
9695pub fn renderSingleInstruction(
9796 gpa: Allocator,
9897 inst: Zir.Inst.Index,
99 scope_file: *Module.File,
98 scope_file: *Zcu.File,
10099 parent_decl_node: Ast.Node.Index,
101100 indent: u32,
102101 stream: anytype,
......@@ -122,7 +121,7 @@ pub fn renderSingleInstruction(
122121const Writer = struct {
123122 gpa: Allocator,
124123 arena: Allocator,
125 file: *Module.File,
124 file: *Zcu.File,
126125 code: Zir,
127126 indent: u32,
128127 parent_decl_node: Ast.Node.Index,
src/register_manager.zig-2
......@@ -7,8 +7,6 @@ const Air = @import("Air.zig");
77const StaticBitSet = std.bit_set.StaticBitSet;
88const Type = @import("Type.zig");
99const Zcu = @import("Zcu.zig");
10/// Deprecated.
11const Module = Zcu;
1210const expect = std.testing.expect;
1311const expectEqual = std.testing.expectEqual;
1412const expectEqualSlices = std.testing.expectEqualSlices;