authorgravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-03-28 20:14:16-04:00
committergravatar for jacobly@ziglang.orgJacob Young <jacobly@ziglang.org> 2024-03-30 20:50:48-04:00
log6f10b11658c002b26341bff10e1dd522f2465b5a
tree6c66b925c7b34f8496552eed3675d2c87a30fdf7
parentaff71c6132fd17c6fa455a6e7b9f53567e3e55b2

cbe: fix bugs revealed by an upcoming commit

Closes #18023

5 files changed, 1497 insertions(+), 1386 deletions(-)

lib/zig.h+6-3
...@@ -165,11 +165,14 @@ typedef char bool;...@@ -165,11 +165,14 @@ typedef char bool;
165#endif165#endif
166166
167#if zig_has_attribute(section)167#if zig_has_attribute(section)
168#define zig_linksection(name, def, ...) def __attribute__((section(name)))168#define zig_linksection(name) __attribute__((section(name)))
169#define zig_linksection_fn zig_linksection
169#elif _MSC_VER170#elif _MSC_VER
170#define zig_linksection(name, def, ...) __pragma(section(name, __VA_ARGS__)) __declspec(allocate(name)) def171#define zig_linksection(name) __pragma(section(name, read, write)) __declspec(allocate(name))
172#define zig_linksection_fn(name) __pragma(section(name, read, execute)) __declspec(code_seg(name))
171#else173#else
172#define zig_linksection(name, def, ...) zig_linksection_unavailable174#define zig_linksection(name) zig_linksection_unavailable
175#define zig_linksection_fn zig_linksection
173#endif176#endif
174177
175#if zig_has_builtin(unreachable) || defined(zig_gnuc)178#if zig_has_builtin(unreachable) || defined(zig_gnuc)
src/Compilation.zig+2-1
...@@ -3451,7 +3451,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: *std.Progress.Node) !v...@@ -3451,7 +3451,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: *std.Progress.Node) !v
34513451
3452 var dg: c_codegen.DeclGen = .{3452 var dg: c_codegen.DeclGen = .{
3453 .gpa = gpa,3453 .gpa = gpa,
3454 .module = module,3454 .zcu = module,
3455 .mod = module.namespacePtr(decl.src_namespace).file_scope.mod,
3455 .error_msg = null,3456 .error_msg = null,
3456 .pass = .{ .decl = decl_index },3457 .pass = .{ .decl = decl_index },
3457 .is_naked_fn = false,3458 .is_naked_fn = false,
src/codegen/c.zig+1267-1192
...@@ -5,12 +5,13 @@ const mem = std.mem;...@@ -5,12 +5,13 @@ const mem = std.mem;
5const log = std.log.scoped(.c);5const log = std.log.scoped(.c);
66
7const link = @import("../link.zig");7const link = @import("../link.zig");
8const Module = @import("../Module.zig");8const Zcu = @import("../Module.zig");
9const Module = @import("../Package/Module.zig");
9const Compilation = @import("../Compilation.zig");10const Compilation = @import("../Compilation.zig");
10const Value = @import("../Value.zig");11const Value = @import("../Value.zig");
11const Type = @import("../type.zig").Type;12const Type = @import("../type.zig").Type;
12const C = link.File.C;13const C = link.File.C;
13const Decl = Module.Decl;14const Decl = Zcu.Decl;
14const trace = @import("../tracy.zig").trace;15const trace = @import("../tracy.zig").trace;
15const LazySrcLoc = std.zig.LazySrcLoc;16const LazySrcLoc = std.zig.LazySrcLoc;
16const Air = @import("../Air.zig");17const Air = @import("../Air.zig");
...@@ -30,7 +31,7 @@ pub const CValue = union(enum) {...@@ -30,7 +31,7 @@ pub const CValue = union(enum) {
30 /// Address of a local.31 /// Address of a local.
31 local_ref: LocalIndex,32 local_ref: LocalIndex,
32 /// A constant instruction, to be rendered inline.33 /// A constant instruction, to be rendered inline.
33 constant: InternPool.Index,34 constant: Value,
34 /// Index into the parameters35 /// Index into the parameters
35 arg: usize,36 arg: usize,
36 /// The array field of a parameter37 /// The array field of a parameter
...@@ -72,13 +73,15 @@ pub const LazyFnValue = struct {...@@ -72,13 +73,15 @@ pub const LazyFnValue = struct {
72};73};
73pub const LazyFnMap = std.AutoArrayHashMapUnmanaged(LazyFnKey, LazyFnValue);74pub const LazyFnMap = std.AutoArrayHashMapUnmanaged(LazyFnKey, LazyFnValue);
7475
75const LoopDepth = u16;
76const Local = struct {76const Local = struct {
77 cty_idx: CType.Index,77 cty_idx: CType.Index,
78 alignas: CType.AlignAs,78 flags: packed struct(u32) {
79 alignas: CType.AlignAs,
80 _: u20 = undefined,
81 },
7982
80 pub fn getType(local: Local) LocalType {83 pub fn getType(local: Local) LocalType {
81 return .{ .cty_idx = local.cty_idx, .alignas = local.alignas };84 return .{ .cty_idx = local.cty_idx, .alignas = local.flags.alignas };
82 }85 }
83};86};
8487
...@@ -300,11 +303,11 @@ pub const Function = struct {...@@ -300,11 +303,11 @@ pub const Function = struct {
300 const gop = try f.value_map.getOrPut(ref);303 const gop = try f.value_map.getOrPut(ref);
301 if (gop.found_existing) return gop.value_ptr.*;304 if (gop.found_existing) return gop.value_ptr.*;
302305
303 const mod = f.object.dg.module;306 const zcu = f.object.dg.zcu;
304 const val = (try f.air.value(ref, mod)).?;307 const val = (try f.air.value(ref, zcu)).?;
305 const ty = f.typeOf(ref);308 const ty = f.typeOf(ref);
306309
307 const result: CValue = if (lowersToArray(ty, mod)) result: {310 const result: CValue = if (lowersToArray(ty, zcu)) result: {
308 const writer = f.object.codeHeaderWriter();311 const writer = f.object.codeHeaderWriter();
309 const alignment: Alignment = .none;312 const alignment: Alignment = .none;
310 const decl_c_value = try f.allocLocalValue(ty, alignment);313 const decl_c_value = try f.allocLocalValue(ty, alignment);
...@@ -313,17 +316,17 @@ pub const Function = struct {...@@ -313,17 +316,17 @@ pub const Function = struct {
313 try writer.writeAll("static ");316 try writer.writeAll("static ");
314 try f.object.dg.renderTypeAndName(writer, ty, decl_c_value, Const, alignment, .complete);317 try f.object.dg.renderTypeAndName(writer, ty, decl_c_value, Const, alignment, .complete);
315 try writer.writeAll(" = ");318 try writer.writeAll(" = ");
316 try f.object.dg.renderValue(writer, ty, val, .StaticInitializer);319 try f.object.dg.renderValue(writer, val, .StaticInitializer);
317 try writer.writeAll(";\n ");320 try writer.writeAll(";\n ");
318 break :result decl_c_value;321 break :result decl_c_value;
319 } else .{ .constant = val.toIntern() };322 } else .{ .constant = val };
320323
321 gop.value_ptr.* = result;324 gop.value_ptr.* = result;
322 return result;325 return result;
323 }326 }
324327
325 fn wantSafety(f: *Function) bool {328 fn wantSafety(f: *Function) bool {
326 return switch (f.object.dg.module.optimizeMode()) {329 return switch (f.object.dg.zcu.optimizeMode()) {
327 .Debug, .ReleaseSafe => true,330 .Debug, .ReleaseSafe => true,
328 .ReleaseFast, .ReleaseSmall => false,331 .ReleaseFast, .ReleaseSmall => false,
329 };332 };
...@@ -333,11 +336,13 @@ pub const Function = struct {...@@ -333,11 +336,13 @@ pub const Function = struct {
333 /// those which go into `allocs`. This function does not add the resulting local into `allocs`;336 /// those which go into `allocs`. This function does not add the resulting local into `allocs`;
334 /// that responsibility lies with the caller.337 /// that responsibility lies with the caller.
335 fn allocLocalValue(f: *Function, ty: Type, alignment: Alignment) !CValue {338 fn allocLocalValue(f: *Function, ty: Type, alignment: Alignment) !CValue {
336 const mod = f.object.dg.module;339 const zcu = f.object.dg.zcu;
337 const gpa = f.object.dg.gpa;340 const gpa = f.object.dg.gpa;
338 try f.locals.append(gpa, .{341 try f.locals.append(gpa, .{
339 .cty_idx = try f.typeToIndex(ty, .complete),342 .cty_idx = try f.typeToIndex(ty, .complete),
340 .alignas = CType.AlignAs.init(alignment, ty.abiAlignment(mod)),343 .flags = .{
344 .alignas = CType.AlignAs.init(alignment, ty.abiAlignment(zcu)),
345 },
341 });346 });
342 return .{ .new_local = @intCast(f.locals.items.len - 1) };347 return .{ .new_local = @intCast(f.locals.items.len - 1) };
343 }348 }
...@@ -355,79 +360,100 @@ pub const Function = struct {...@@ -355,79 +360,100 @@ pub const Function = struct {
355 /// Only allocates the local; does not print anything. Will attempt to re-use locals, so should360 /// Only allocates the local; does not print anything. Will attempt to re-use locals, so should
356 /// not be used for persistent locals (i.e. those in `allocs`).361 /// not be used for persistent locals (i.e. those in `allocs`).
357 fn allocAlignedLocal(f: *Function, ty: Type, _: CQualifiers, alignment: Alignment) !CValue {362 fn allocAlignedLocal(f: *Function, ty: Type, _: CQualifiers, alignment: Alignment) !CValue {
358 const mod = f.object.dg.module;363 const zcu = f.object.dg.zcu;
359 if (f.free_locals_map.getPtr(.{364 if (f.free_locals_map.getPtr(.{
360 .cty_idx = try f.typeToIndex(ty, .complete),365 .cty_idx = try f.typeToIndex(ty, .complete),
361 .alignas = CType.AlignAs.init(alignment, ty.abiAlignment(mod)),366 .alignas = CType.AlignAs.init(alignment, ty.abiAlignment(zcu)),
362 })) |locals_list| {367 })) |locals_list| {
363 if (locals_list.popOrNull()) |local_entry| {368 if (locals_list.popOrNull()) |local_entry| {
364 return .{ .new_local = local_entry.key };369 return .{ .new_local = local_entry.key };
365 }370 }
366 }371 }
367372
368 return try f.allocLocalValue(ty, alignment);373 return f.allocLocalValue(ty, alignment);
369 }374 }
370375
371 fn writeCValue(f: *Function, w: anytype, c_value: CValue, location: ValueRenderLocation) !void {376 fn writeCValue(f: *Function, w: anytype, c_value: CValue, location: ValueRenderLocation) !void {
372 switch (c_value) {377 switch (c_value) {
373 .constant => |val| try f.object.dg.renderValue(378 .none => unreachable,
374 w,379 .new_local, .local => |i| try w.print("t{d}", .{i}),
375 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),380 .local_ref => |i| {
376 Value.fromInterned(val),381 const local = &f.locals.items[i];
377 location,382 if (local.flags.alignas.abiOrder().compare(.lt)) {
378 ),383 const zcu = f.object.dg.zcu;
379 .undef => |ty| try f.object.dg.renderValue(w, ty, Value.undef, location),384 const pointee_ty = try zcu.intType(.unsigned, @min(
385 local.flags.alignas.@"align".toByteUnitsOptional().?,
386 f.object.dg.mod.resolved_target.result.maxIntAlignment(),
387 ) * 8);
388 const ptr_ty = try zcu.singleMutPtrType(pointee_ty);
389
390 try w.writeByte('(');
391 try f.renderType(w, ptr_ty);
392 try w.writeByte(')');
393 }
394 try w.print("&t{d}", .{i});
395 },
396 .constant => |val| try f.object.dg.renderValue(w, val, location),
397 .arg => |i| try w.print("a{d}", .{i}),
398 .arg_array => |i| try f.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" }),
399 .undef => |ty| try f.object.dg.renderUndefValue(w, ty, location),
380 else => try f.object.dg.writeCValue(w, c_value),400 else => try f.object.dg.writeCValue(w, c_value),
381 }401 }
382 }402 }
383403
384 fn writeCValueDeref(f: *Function, w: anytype, c_value: CValue) !void {404 fn writeCValueDeref(f: *Function, w: anytype, c_value: CValue) !void {
385 switch (c_value) {405 switch (c_value) {
386 .constant => |val| {406 .none => unreachable,
407 .new_local, .local, .constant => {
387 try w.writeAll("(*");408 try w.writeAll("(*");
388 try f.object.dg.renderValue(409 try f.writeCValue(w, c_value, .Other);
389 w,410 try w.writeByte(')');
390 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),411 },
391 Value.fromInterned(val),412 .local_ref => |i| try w.print("t{d}", .{i}),
392 .Other,413 .arg => |i| try w.print("(*a{d})", .{i}),
393 );414 .arg_array => |i| {
415 try w.writeAll("(*");
416 try f.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" });
394 try w.writeByte(')');417 try w.writeByte(')');
395 },418 },
396 else => try f.object.dg.writeCValueDeref(w, c_value),419 else => try f.object.dg.writeCValueDeref(w, c_value),
397 }420 }
398 }421 }
399422
400 fn writeCValueMember(f: *Function, w: anytype, c_value: CValue, member: CValue) !void {423 fn writeCValueMember(
424 f: *Function,
425 writer: anytype,
426 c_value: CValue,
427 member: CValue,
428 ) error{ OutOfMemory, AnalysisFail }!void {
401 switch (c_value) {429 switch (c_value) {
402 .constant => |val| {430 .new_local, .local, .local_ref, .constant, .arg, .arg_array => {
403 try f.object.dg.renderValue(431 try f.writeCValue(writer, c_value, .Other);
404 w,432 try writer.writeByte('.');
405 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),433 try f.writeCValue(writer, member, .Other);
406 Value.fromInterned(val),
407 .Other,
408 );
409 try w.writeByte('.');
410 try f.writeCValue(w, member, .Other);
411 },434 },
412 else => try f.object.dg.writeCValueMember(w, c_value, member),435 else => return f.object.dg.writeCValueMember(writer, c_value, member),
413 }436 }
414 }437 }
415438
416 fn writeCValueDerefMember(f: *Function, w: anytype, c_value: CValue, member: CValue) !void {439 fn writeCValueDerefMember(f: *Function, writer: anytype, c_value: CValue, member: CValue) !void {
417 switch (c_value) {440 switch (c_value) {
418 .constant => |val| {441 .new_local, .local, .arg, .arg_array => {
419 try w.writeByte('(');442 try f.writeCValue(writer, c_value, .Other);
420 try f.object.dg.renderValue(443 try writer.writeAll("->");
421 w,444 },
422 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),445 .constant => {
423 Value.fromInterned(val),446 try writer.writeByte('(');
424 .Other,447 try f.writeCValue(writer, c_value, .Other);
425 );448 try writer.writeAll(")->");
426 try w.writeAll(")->");449 },
427 try f.writeCValue(w, member, .Other);450 .local_ref => {
451 try f.writeCValueDeref(writer, c_value);
452 try writer.writeByte('.');
428 },453 },
429 else => try f.object.dg.writeCValueDerefMember(w, c_value, member),454 else => return f.object.dg.writeCValueDerefMember(writer, c_value, member),
430 }455 }
456 try f.writeCValue(writer, member, .Other);
431 }457 }
432458
433 fn fail(f: *Function, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {459 fn fail(f: *Function, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
...@@ -462,8 +488,8 @@ pub const Function = struct {...@@ -462,8 +488,8 @@ pub const Function = struct {
462 return f.object.dg.renderIntCast(w, dest_ty, .{ .c_value = .{ .f = f, .value = src, .v = v } }, src_ty, location);488 return f.object.dg.renderIntCast(w, dest_ty, .{ .c_value = .{ .f = f, .value = src, .v = v } }, src_ty, location);
463 }489 }
464490
465 fn fmtIntLiteral(f: *Function, ty: Type, val: Value) !std.fmt.Formatter(formatIntLiteral) {491 fn fmtIntLiteral(f: *Function, val: Value) !std.fmt.Formatter(formatIntLiteral) {
466 return f.object.dg.fmtIntLiteral(ty, val, .Other);492 return f.object.dg.fmtIntLiteral(val, .Other);
467 }493 }
468494
469 fn getLazyFnName(f: *Function, key: LazyFnKey, data: LazyFnValue.Data) ![]const u8 {495 fn getLazyFnName(f: *Function, key: LazyFnKey, data: LazyFnValue.Data) ![]const u8 {
...@@ -475,7 +501,7 @@ pub const Function = struct {...@@ -475,7 +501,7 @@ pub const Function = struct {
475 var promoted = f.object.dg.ctypes.promote(gpa);501 var promoted = f.object.dg.ctypes.promote(gpa);
476 defer f.object.dg.ctypes.demote(promoted);502 defer f.object.dg.ctypes.demote(promoted);
477 const arena = promoted.arena.allocator();503 const arena = promoted.arena.allocator();
478 const mod = f.object.dg.module;504 const zcu = f.object.dg.zcu;
479505
480 gop.value_ptr.* = .{506 gop.value_ptr.* = .{
481 .fn_name = switch (key) {507 .fn_name = switch (key) {
...@@ -484,7 +510,7 @@ pub const Function = struct {...@@ -484,7 +510,7 @@ pub const Function = struct {
484 .never_inline,510 .never_inline,
485 => |owner_decl| try std.fmt.allocPrint(arena, "zig_{s}_{}__{d}", .{511 => |owner_decl| try std.fmt.allocPrint(arena, "zig_{s}_{}__{d}", .{
486 @tagName(key),512 @tagName(key),
487 fmtIdent(mod.intern_pool.stringToSlice(mod.declPtr(owner_decl).name)),513 fmtIdent(zcu.intern_pool.stringToSlice(zcu.declPtr(owner_decl).name)),
488 @intFromEnum(owner_decl),514 @intFromEnum(owner_decl),
489 }),515 }),
490 },516 },
...@@ -510,17 +536,17 @@ pub const Function = struct {...@@ -510,17 +536,17 @@ pub const Function = struct {
510 }536 }
511537
512 fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {538 fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {
513 const mod = f.object.dg.module;539 const zcu = f.object.dg.zcu;
514 return f.air.typeOf(inst, &mod.intern_pool);540 return f.air.typeOf(inst, &zcu.intern_pool);
515 }541 }
516542
517 fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {543 fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {
518 const mod = f.object.dg.module;544 const zcu = f.object.dg.zcu;
519 return f.air.typeOfIndex(inst, &mod.intern_pool);545 return f.air.typeOfIndex(inst, &zcu.intern_pool);
520 }546 }
521};547};
522548
523/// This data is available when outputting .c code for a `Module`.549/// This data is available when outputting .c code for a `Zcu`.
524/// It is not available when generating .h file.550/// It is not available when generating .h file.
525pub const Object = struct {551pub const Object = struct {
526 dg: DeclGen,552 dg: DeclGen,
...@@ -542,12 +568,13 @@ pub const Object = struct {...@@ -542,12 +568,13 @@ pub const Object = struct {
542/// This data is available both when outputting .c code and when outputting an .h file.568/// This data is available both when outputting .c code and when outputting an .h file.
543pub const DeclGen = struct {569pub const DeclGen = struct {
544 gpa: mem.Allocator,570 gpa: mem.Allocator,
545 module: *Module,571 zcu: *Zcu,
572 mod: *Module,
546 pass: Pass,573 pass: Pass,
547 is_naked_fn: bool,574 is_naked_fn: bool,
548 /// This is a borrowed reference from `link.C`.575 /// This is a borrowed reference from `link.C`.
549 fwd_decl: std.ArrayList(u8),576 fwd_decl: std.ArrayList(u8),
550 error_msg: ?*Module.ErrorMsg,577 error_msg: ?*Zcu.ErrorMsg,
551 ctypes: CType.Store,578 ctypes: CType.Store,
552 /// Keeps track of anonymous decls that need to be rendered before this579 /// Keeps track of anonymous decls that need to be rendered before this
553 /// (named) Decl in the output C code.580 /// (named) Decl in the output C code.
...@@ -566,75 +593,70 @@ pub const DeclGen = struct {...@@ -566,75 +593,70 @@ pub const DeclGen = struct {
566593
567 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {594 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
568 @setCold(true);595 @setCold(true);
569 const mod = dg.module;596 const zcu = dg.zcu;
570 const decl_index = dg.pass.decl;597 const decl_index = dg.pass.decl;
571 const decl = mod.declPtr(decl_index);598 const decl = zcu.declPtr(decl_index);
572 const src_loc = decl.srcLoc(mod);599 const src_loc = decl.srcLoc(zcu);
573 dg.error_msg = try Module.ErrorMsg.create(dg.gpa, src_loc, format, args);600 dg.error_msg = try Zcu.ErrorMsg.create(dg.gpa, src_loc, format, args);
574 return error.AnalysisFail;601 return error.AnalysisFail;
575 }602 }
576603
577 fn renderAnonDeclValue(604 fn renderAnonDeclValue(
578 dg: *DeclGen,605 dg: *DeclGen,
579 writer: anytype,606 writer: anytype,
580 ty: Type,
581 ptr_val: Value,607 ptr_val: Value,
582 anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,608 anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,
583 location: ValueRenderLocation,609 location: ValueRenderLocation,
584 ) error{ OutOfMemory, AnalysisFail }!void {610 ) error{ OutOfMemory, AnalysisFail }!void {
585 const mod = dg.module;611 const zcu = dg.zcu;
586 const ip = &mod.intern_pool;612 const ip = &zcu.intern_pool;
587 const decl_val = anon_decl.val;613 const decl_val = Value.fromInterned(anon_decl.val);
588 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));614 const decl_ty = decl_val.typeOf(zcu);
589615
590 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.616 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
591 if (ty.isPtrAtRuntime(mod) and !decl_ty.isFnOrHasRuntimeBits(mod)) {617 const ptr_ty = ptr_val.typeOf(zcu);
592 return dg.writeCValue(writer, .{ .undef = ty });618 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(zcu)) {
619 return dg.writeCValue(writer, .{ .undef = ptr_ty });
593 }620 }
594621
595 // Chase function values in order to be able to reference the original function.622 // Chase function values in order to be able to reference the original function.
596 if (Value.fromInterned(decl_val).getFunction(mod)) |func| {623 if (decl_val.getFunction(zcu)) |func|
597 _ = func;624 return dg.renderDeclValue(writer, ptr_val, func.owner_decl, location);
598 _ = ptr_val;625 if (decl_val.getExternFunc(zcu)) |extern_func|
599 _ = location;626 return dg.renderDeclValue(writer, ptr_val, extern_func.decl, location);
600 @panic("TODO");
601 }
602 if (Value.fromInterned(decl_val).getExternFunc(mod)) |extern_func| {
603 _ = extern_func;
604 _ = ptr_val;
605 _ = location;
606 @panic("TODO");
607 }
608627
609 assert(Value.fromInterned(decl_val).getVariable(mod) == null);628 assert(decl_val.getVariable(zcu) == null);
610629
611 // We shouldn't cast C function pointers as this is UB (when you call630 // We shouldn't cast C function pointers as this is UB (when you call
612 // them). The analysis until now should ensure that the C function631 // them). The analysis until now should ensure that the C function
613 // pointers are compatible. If they are not, then there is a bug632 // pointers are compatible. If they are not, then there is a bug
614 // somewhere and we should let the C compiler tell us about it.633 // somewhere and we should let the C compiler tell us about it.
615 const need_typecast = if (ty.castPtrToFn(mod)) |_| false else !ty.childType(mod).eql(decl_ty, mod);634 const child_cty = (try dg.typeToCType(ptr_ty, .complete)).cast(CType.Payload.Child).?.data;
616 if (need_typecast) {635 const decl_cty = try dg.typeToIndex(decl_ty, .complete);
636 const need_cast = child_cty != decl_cty and
637 (dg.indexToCType(child_cty).tag() != .function or dg.indexToCType(decl_cty).tag() != .function);
638 if (need_cast) {
617 try writer.writeAll("((");639 try writer.writeAll("((");
618 try dg.renderType(writer, ty);640 try dg.renderType(writer, ptr_ty);
619 try writer.writeByte(')');641 try writer.writeByte(')');
620 }642 }
621 try writer.writeByte('&');643 try writer.writeByte('&');
622 try renderAnonDeclName(writer, decl_val);644 try renderAnonDeclName(writer, decl_val);
623 if (need_typecast) try writer.writeByte(')');645 if (need_cast) try writer.writeByte(')');
624646
625 // Indicate that the anon decl should be rendered to the output so that647 // Indicate that the anon decl should be rendered to the output so that
626 // our reference above is not undefined.648 // our reference above is not undefined.
627 const ptr_type = ip.indexToKey(anon_decl.orig_ty).ptr_type;649 const ptr_type = ip.indexToKey(anon_decl.orig_ty).ptr_type;
628 const gop = try dg.anon_decl_deps.getOrPut(dg.gpa, decl_val);650 const gop = try dg.anon_decl_deps.getOrPut(dg.gpa, anon_decl.val);
629 if (!gop.found_existing) gop.value_ptr.* = .{};651 if (!gop.found_existing) gop.value_ptr.* = .{};
630652
631 // Only insert an alignment entry if the alignment is greater than ABI653 // Only insert an alignment entry if the alignment is greater than ABI
632 // alignment. If there is already an entry, keep the greater alignment.654 // alignment. If there is already an entry, keep the greater alignment.
633 const explicit_alignment = ptr_type.flags.alignment;655 const explicit_alignment = ptr_type.flags.alignment;
634 if (explicit_alignment != .none) {656 if (explicit_alignment != .none) {
635 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(mod);657 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(zcu);
636 if (explicit_alignment.compareStrict(.gt, abi_alignment)) {658 if (explicit_alignment.compareStrict(.gt, abi_alignment)) {
637 const aligned_gop = try dg.aligned_anon_decls.getOrPut(dg.gpa, decl_val);659 const aligned_gop = try dg.aligned_anon_decls.getOrPut(dg.gpa, anon_decl.val);
638 aligned_gop.value_ptr.* = if (aligned_gop.found_existing)660 aligned_gop.value_ptr.* = if (aligned_gop.found_existing)
639 aligned_gop.value_ptr.maxStrict(explicit_alignment)661 aligned_gop.value_ptr.maxStrict(explicit_alignment)
640 else662 else
...@@ -646,41 +668,45 @@ pub const DeclGen = struct {...@@ -646,41 +668,45 @@ pub const DeclGen = struct {
646 fn renderDeclValue(668 fn renderDeclValue(
647 dg: *DeclGen,669 dg: *DeclGen,
648 writer: anytype,670 writer: anytype,
649 ty: Type,
650 val: Value,671 val: Value,
651 decl_index: InternPool.DeclIndex,672 decl_index: InternPool.DeclIndex,
652 location: ValueRenderLocation,673 location: ValueRenderLocation,
653 ) error{ OutOfMemory, AnalysisFail }!void {674 ) error{ OutOfMemory, AnalysisFail }!void {
654 const mod = dg.module;675 const zcu = dg.zcu;
655 const decl = mod.declPtr(decl_index);676 const decl = zcu.declPtr(decl_index);
656 assert(decl.has_tv);677 assert(decl.has_tv);
657678
658 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.679 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
659 if (ty.isPtrAtRuntime(mod) and !decl.typeOf(mod).isFnOrHasRuntimeBits(mod)) {680 const ty = val.typeOf(zcu);
681 const decl_ty = decl.typeOf(zcu);
682 if (ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(zcu)) {
660 return dg.writeCValue(writer, .{ .undef = ty });683 return dg.writeCValue(writer, .{ .undef = ty });
661 }684 }
662685
663 // Chase function values in order to be able to reference the original function.686 // Chase function values in order to be able to reference the original function.
664 if (decl.val.getFunction(mod)) |func| if (func.owner_decl != decl_index)687 if (decl.val.getFunction(zcu)) |func| if (func.owner_decl != decl_index)
665 return dg.renderDeclValue(writer, ty, val, func.owner_decl, location);688 return dg.renderDeclValue(writer, val, func.owner_decl, location);
666 if (decl.val.getExternFunc(mod)) |extern_func| if (extern_func.decl != decl_index)689 if (decl.val.getExternFunc(zcu)) |extern_func| if (extern_func.decl != decl_index)
667 return dg.renderDeclValue(writer, ty, val, extern_func.decl, location);690 return dg.renderDeclValue(writer, val, extern_func.decl, location);
668691
669 if (decl.val.getVariable(mod)) |variable| try dg.renderFwdDecl(decl_index, variable, .tentative);692 if (decl.val.getVariable(zcu)) |variable| try dg.renderFwdDecl(decl_index, variable, .tentative);
670693
671 // We shouldn't cast C function pointers as this is UB (when you call694 // We shouldn't cast C function pointers as this is UB (when you call
672 // them). The analysis until now should ensure that the C function695 // them). The analysis until now should ensure that the C function
673 // pointers are compatible. If they are not, then there is a bug696 // pointers are compatible. If they are not, then there is a bug
674 // somewhere and we should let the C compiler tell us about it.697 // somewhere and we should let the C compiler tell us about it.
675 const need_typecast = if (ty.castPtrToFn(mod)) |_| false else !ty.childType(mod).eql(decl.typeOf(mod), mod);698 const child_cty = (try dg.typeToCType(ty, .complete)).cast(CType.Payload.Child).?.data;
676 if (need_typecast) {699 const decl_cty = try dg.typeToIndex(decl_ty, .complete);
700 const need_cast = child_cty != decl_cty and
701 (dg.indexToCType(child_cty).tag() != .function or dg.indexToCType(decl_cty).tag() != .function);
702 if (need_cast) {
677 try writer.writeAll("((");703 try writer.writeAll("((");
678 try dg.renderType(writer, ty);704 try dg.renderType(writer, ty);
679 try writer.writeByte(')');705 try writer.writeByte(')');
680 }706 }
681 try writer.writeByte('&');707 try writer.writeByte('&');
682 try dg.renderDeclName(writer, decl_index, 0);708 try dg.renderDeclName(writer, decl_index, 0);
683 if (need_typecast) try writer.writeByte(')');709 if (need_cast) try writer.writeByte(')');
684 }710 }
685711
686 /// Renders a "parent" pointer by recursing to the root decl/variable712 /// Renders a "parent" pointer by recursing to the root decl/variable
...@@ -691,31 +717,32 @@ pub const DeclGen = struct {...@@ -691,31 +717,32 @@ pub const DeclGen = struct {
691 ptr_val: InternPool.Index,717 ptr_val: InternPool.Index,
692 location: ValueRenderLocation,718 location: ValueRenderLocation,
693 ) error{ OutOfMemory, AnalysisFail }!void {719 ) error{ OutOfMemory, AnalysisFail }!void {
694 const mod = dg.module;720 const zcu = dg.zcu;
695 const ptr_ty = Type.fromInterned(mod.intern_pool.typeOf(ptr_val));721 const ip = &zcu.intern_pool;
722 const ptr_ty = Type.fromInterned(ip.typeOf(ptr_val));
696 const ptr_cty = try dg.typeToIndex(ptr_ty, .complete);723 const ptr_cty = try dg.typeToIndex(ptr_ty, .complete);
697 const ptr = mod.intern_pool.indexToKey(ptr_val).ptr;724 const ptr_child_cty = dg.indexToCType(ptr_cty).cast(CType.Payload.Child).?.data;
725 const ptr = ip.indexToKey(ptr_val).ptr;
698 switch (ptr.addr) {726 switch (ptr.addr) {
699 .decl => |d| try dg.renderDeclValue(writer, ptr_ty, Value.fromInterned(ptr_val), d, location),727 .decl => |d| try dg.renderDeclValue(writer, Value.fromInterned(ptr_val), d, location),
700 .anon_decl => |anon_decl| try dg.renderAnonDeclValue(writer, ptr_ty, Value.fromInterned(ptr_val), anon_decl, location),728 .anon_decl => |anon_decl| try dg.renderAnonDeclValue(writer, Value.fromInterned(ptr_val), anon_decl, location),
701 .int => |int| {729 .int => |int| {
702 try writer.writeByte('(');730 try writer.writeByte('(');
703 try dg.renderCType(writer, ptr_cty);731 try dg.renderCType(writer, ptr_cty);
704 try writer.print("){x}", .{try dg.fmtIntLiteral(Type.usize, Value.fromInterned(int), .Other)});732 try writer.print("){x}", .{try dg.fmtIntLiteral(Value.fromInterned(int), .Other)});
705 },733 },
706 .eu_payload, .opt_payload => |base| {734 .eu_payload, .opt_payload => |base| {
707 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(base));735 const ptr_base_ty = Type.fromInterned(ip.typeOf(base));
708 const base_ty = ptr_base_ty.childType(mod);736 const base_ty = ptr_base_ty.childType(zcu);
709 // Ensure complete type definition is visible before accessing fields.737 // Ensure complete type definition is visible before accessing fields.
710 _ = try dg.typeToIndex(base_ty, .complete);738 _ = try dg.typeToIndex(base_ty, .complete);
711 const payload_ty = switch (ptr.addr) {739 const payload_ty = switch (ptr.addr) {
712 .eu_payload => base_ty.errorUnionPayload(mod),740 .eu_payload => base_ty.errorUnionPayload(zcu),
713 .opt_payload => base_ty.optionalChild(mod),741 .opt_payload => base_ty.optionalChild(zcu),
714 else => unreachable,742 else => unreachable,
715 };743 };
716 const ptr_payload_ty = try mod.adjustPtrTypeChild(ptr_base_ty, payload_ty);744 const payload_cty = try dg.typeToIndex(payload_ty, .forward);
717 const ptr_payload_cty = try dg.typeToIndex(ptr_payload_ty, .complete);745 if (ptr_child_cty != payload_cty) {
718 if (ptr_cty != ptr_payload_cty) {
719 try writer.writeByte('(');746 try writer.writeByte('(');
720 try dg.renderCType(writer, ptr_cty);747 try dg.renderCType(writer, ptr_cty);
721 try writer.writeByte(')');748 try writer.writeByte(')');
...@@ -725,70 +752,90 @@ pub const DeclGen = struct {...@@ -725,70 +752,90 @@ pub const DeclGen = struct {
725 try writer.writeAll(")->payload");752 try writer.writeAll(")->payload");
726 },753 },
727 .elem => |elem| {754 .elem => |elem| {
728 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(elem.base));755 const ptr_base_ty = Type.fromInterned(ip.typeOf(elem.base));
729 const elem_ty = ptr_base_ty.elemType2(mod);756 const elem_ty = ptr_base_ty.elemType2(zcu);
730 const ptr_elem_ty = try mod.adjustPtrTypeChild(ptr_base_ty, elem_ty);757 const elem_cty = try dg.typeToIndex(elem_ty, .forward);
731 const ptr_elem_cty = try dg.typeToIndex(ptr_elem_ty, .complete);758 if (ptr_child_cty != elem_cty) {
732 if (ptr_cty != ptr_elem_cty) {
733 try writer.writeByte('(');759 try writer.writeByte('(');
734 try dg.renderCType(writer, ptr_cty);760 try dg.renderCType(writer, ptr_cty);
735 try writer.writeByte(')');761 try writer.writeByte(')');
736 }762 }
737 try writer.writeAll("&(");763 try writer.writeAll("&(");
738 if (mod.intern_pool.indexToKey(ptr_base_ty.toIntern()).ptr_type.flags.size == .One)764 if (ip.indexToKey(ptr_base_ty.toIntern()).ptr_type.flags.size == .One)
739 try writer.writeByte('*');765 try writer.writeByte('*');
740 try dg.renderParentPtr(writer, elem.base, location);766 try dg.renderParentPtr(writer, elem.base, location);
741 try writer.print(")[{d}]", .{elem.index});767 try writer.print(")[{d}]", .{elem.index});
742 },768 },
743 .field => |field| {769 .field => |field| {
744 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(field.base));770 const ptr_base_ty = Type.fromInterned(ip.typeOf(field.base));
745 const base_ty = ptr_base_ty.childType(mod);771 const base_ty = ptr_base_ty.childType(zcu);
746 // Ensure complete type definition is visible before accessing fields.772 // Ensure complete type definition is visible before accessing fields.
747 _ = try dg.typeToIndex(base_ty, .complete);773 _ = try dg.typeToIndex(base_ty, .complete);
748 const field_ty = switch (mod.intern_pool.indexToKey(base_ty.toIntern())) {774 switch (fieldLocation(ptr_base_ty, ptr_ty, @as(u32, @intCast(field.index)), zcu)) {
749 .anon_struct_type, .struct_type, .union_type => base_ty.structFieldType(@as(usize, @intCast(field.index)), mod),775 .begin => {
750 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {776 const ptr_base_cty = try dg.typeToIndex(ptr_base_ty, .complete);
751 .One, .Many, .C => unreachable,777 if (ptr_cty != ptr_base_cty) {
752 .Slice => switch (field.index) {778 try writer.writeByte('(');
753 Value.slice_ptr_index => base_ty.slicePtrFieldType(mod),779 try dg.renderCType(writer, ptr_cty);
754 Value.slice_len_index => Type.usize,780 try writer.writeByte(')');
755 else => unreachable,781 }
756 },782 try dg.renderParentPtr(writer, field.base, location);
757 },783 },
758 else => unreachable,
759 };
760 const ptr_field_ty = try mod.adjustPtrTypeChild(ptr_base_ty, field_ty);
761 const ptr_field_cty = try dg.typeToIndex(ptr_field_ty, .complete);
762 if (ptr_cty != ptr_field_cty) {
763 try writer.writeByte('(');
764 try dg.renderCType(writer, ptr_cty);
765 try writer.writeByte(')');
766 }
767 switch (fieldLocation(ptr_base_ty, ptr_ty, @as(u32, @intCast(field.index)), mod)) {
768 .begin => try dg.renderParentPtr(writer, field.base, location),
769 .field => |name| {784 .field => |name| {
785 const field_ty = switch (ip.indexToKey(base_ty.toIntern())) {
786 .anon_struct_type,
787 .struct_type,
788 .union_type,
789 => base_ty.structFieldType(@as(usize, @intCast(field.index)), zcu),
790 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
791 .One, .Many, .C => unreachable,
792 .Slice => switch (field.index) {
793 Value.slice_ptr_index => base_ty.slicePtrFieldType(zcu),
794 Value.slice_len_index => Type.usize,
795 else => unreachable,
796 },
797 },
798 else => unreachable,
799 };
800 const field_cty = try dg.typeToIndex(field_ty, .forward);
801 if (ptr_child_cty != field_cty) {
802 try writer.writeByte('(');
803 try dg.renderCType(writer, ptr_cty);
804 try writer.writeByte(')');
805 }
770 try writer.writeAll("&(");806 try writer.writeAll("&(");
771 try dg.renderParentPtr(writer, field.base, location);807 try dg.renderParentPtr(writer, field.base, location);
772 try writer.writeAll(")->");808 try writer.writeAll(")->");
773 try dg.writeCValue(writer, name);809 try dg.writeCValue(writer, name);
774 },810 },
775 .byte_offset => |byte_offset| {811 .byte_offset => |byte_offset| {
776 const u8_ptr_ty = try mod.adjustPtrTypeChild(ptr_ty, Type.u8);812 const u8_ptr_ty = try zcu.adjustPtrTypeChild(ptr_ty, Type.u8);
777 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);813 const u8_ptr_cty = try dg.typeToIndex(u8_ptr_ty, .complete);
778814
815 if (ptr_cty != u8_ptr_cty) {
816 try writer.writeByte('(');
817 try dg.renderCType(writer, ptr_cty);
818 try writer.writeByte(')');
819 }
779 try writer.writeAll("((");820 try writer.writeAll("((");
780 try dg.renderType(writer, u8_ptr_ty);821 try dg.renderCType(writer, u8_ptr_cty);
781 try writer.writeByte(')');822 try writer.writeByte(')');
782 try dg.renderParentPtr(writer, field.base, location);823 try dg.renderParentPtr(writer, field.base, location);
783 try writer.print(" + {})", .{824 try writer.print(" + {})", .{
784 try dg.fmtIntLiteral(Type.usize, byte_offset_val, .Other),825 try dg.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset), .Other),
785 });826 });
786 },827 },
787 .end => {828 .end => {
829 const ptr_base_cty = try dg.typeToIndex(ptr_base_ty, .complete);
830 if (ptr_cty != ptr_base_cty) {
831 try writer.writeByte('(');
832 try dg.renderCType(writer, ptr_cty);
833 try writer.writeByte(')');
834 }
788 try writer.writeAll("((");835 try writer.writeAll("((");
789 try dg.renderParentPtr(writer, field.base, location);836 try dg.renderParentPtr(writer, field.base, location);
790 try writer.print(") + {})", .{837 try writer.print(") + {})", .{
791 try dg.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 1), .Other),838 try dg.fmtIntLiteral(try zcu.intValue(Type.usize, 1), .Other),
792 });839 });
793 },840 },
794 }841 }
...@@ -800,215 +847,21 @@ pub const DeclGen = struct {...@@ -800,215 +847,21 @@ pub const DeclGen = struct {
800 fn renderValue(847 fn renderValue(
801 dg: *DeclGen,848 dg: *DeclGen,
802 writer: anytype,849 writer: anytype,
803 ty: Type,
804 val: Value,850 val: Value,
805 location: ValueRenderLocation,851 location: ValueRenderLocation,
806 ) error{ OutOfMemory, AnalysisFail }!void {852 ) error{ OutOfMemory, AnalysisFail }!void {
807 const mod = dg.module;853 const zcu = dg.zcu;
808 const ip = &mod.intern_pool;854 const ip = &zcu.intern_pool;
855 const target = &dg.mod.resolved_target.result;
809856
810 const target = mod.getTarget();
811 const initializer_type: ValueRenderLocation = switch (location) {857 const initializer_type: ValueRenderLocation = switch (location) {
812 .StaticInitializer => .StaticInitializer,858 .StaticInitializer => .StaticInitializer,
813 else => .Initializer,859 else => .Initializer,
814 };860 };
815861
816 const safety_on = switch (mod.optimizeMode()) {862 const ty = val.typeOf(zcu);
817 .Debug, .ReleaseSafe => true,863 if (val.isUndefDeep(zcu)) return dg.renderUndefValue(writer, ty, location);
818 .ReleaseFast, .ReleaseSmall => false,864 switch (ip.indexToKey(val.toIntern())) {
819 };
820
821 if (val.isUndefDeep(mod)) {
822 switch (ty.zigTypeTag(mod)) {
823 .Bool => {
824 if (safety_on) {
825 return writer.writeAll("0xaa");
826 } else {
827 return writer.writeAll("false");
828 }
829 },
830 .Int, .Enum, .ErrorSet => return writer.print("{x}", .{try dg.fmtIntLiteral(ty, val, location)}),
831 .Float => {
832 const bits = ty.floatBits(target);
833 // All unsigned ints matching float types are pre-allocated.
834 const repr_ty = mod.intType(.unsigned, bits) catch unreachable;
835
836 try writer.writeAll("zig_make_");
837 try dg.renderTypeForBuiltinFnName(writer, ty);
838 try writer.writeByte('(');
839 switch (bits) {
840 16 => try writer.print("{x}", .{@as(f16, @bitCast(undefPattern(i16)))}),
841 32 => try writer.print("{x}", .{@as(f32, @bitCast(undefPattern(i32)))}),
842 64 => try writer.print("{x}", .{@as(f64, @bitCast(undefPattern(i64)))}),
843 80 => try writer.print("{x}", .{@as(f80, @bitCast(undefPattern(i80)))}),
844 128 => try writer.print("{x}", .{@as(f128, @bitCast(undefPattern(i128)))}),
845 else => unreachable,
846 }
847 try writer.writeAll(", ");
848 try dg.renderValue(writer, repr_ty, Value.undef, .FunctionArgument);
849 return writer.writeByte(')');
850 },
851 .Pointer => if (ty.isSlice(mod)) {
852 if (!location.isInitializer()) {
853 try writer.writeByte('(');
854 try dg.renderType(writer, ty);
855 try writer.writeByte(')');
856 }
857
858 try writer.writeAll("{(");
859 const ptr_ty = ty.slicePtrFieldType(mod);
860 try dg.renderType(writer, ptr_ty);
861 return writer.print("){x}, {0x}}}", .{try dg.fmtIntLiteral(Type.usize, val, .Other)});
862 } else {
863 try writer.writeAll("((");
864 try dg.renderType(writer, ty);
865 return writer.print("){x})", .{try dg.fmtIntLiteral(Type.usize, val, .Other)});
866 },
867 .Optional => {
868 const payload_ty = ty.optionalChild(mod);
869
870 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
871 return dg.renderValue(writer, Type.bool, val, location);
872 }
873
874 if (ty.optionalReprIsPayload(mod)) {
875 return dg.renderValue(writer, payload_ty, val, location);
876 }
877
878 if (!location.isInitializer()) {
879 try writer.writeByte('(');
880 try dg.renderType(writer, ty);
881 try writer.writeByte(')');
882 }
883
884 try writer.writeAll("{ .payload = ");
885 try dg.renderValue(writer, payload_ty, val, initializer_type);
886 try writer.writeAll(", .is_null = ");
887 try dg.renderValue(writer, Type.bool, val, initializer_type);
888 return writer.writeAll(" }");
889 },
890 .Struct => switch (ty.containerLayout(mod)) {
891 .auto, .@"extern" => {
892 if (!location.isInitializer()) {
893 try writer.writeByte('(');
894 try dg.renderType(writer, ty);
895 try writer.writeByte(')');
896 }
897
898 try writer.writeByte('{');
899 var empty = true;
900 for (0..ty.structFieldCount(mod)) |field_index| {
901 if (ty.structFieldIsComptime(field_index, mod)) continue;
902 const field_ty = ty.structFieldType(field_index, mod);
903 if (!field_ty.hasRuntimeBits(mod)) continue;
904
905 if (!empty) try writer.writeByte(',');
906 try dg.renderValue(writer, field_ty, val, initializer_type);
907
908 empty = false;
909 }
910
911 return writer.writeByte('}');
912 },
913 .@"packed" => return writer.print("{x}", .{try dg.fmtIntLiteral(ty, Value.undef, .Other)}),
914 },
915 .Union => {
916 if (!location.isInitializer()) {
917 try writer.writeByte('(');
918 try dg.renderType(writer, ty);
919 try writer.writeByte(')');
920 }
921
922 try writer.writeByte('{');
923 if (ty.unionTagTypeSafety(mod)) |tag_ty| {
924 const layout = ty.unionGetLayout(mod);
925 if (layout.tag_size != 0) {
926 try writer.writeAll(" .tag = ");
927 try dg.renderValue(writer, tag_ty, val, initializer_type);
928 }
929 if (ty.unionHasAllZeroBitFieldTypes(mod)) return try writer.writeByte('}');
930 if (layout.tag_size != 0) try writer.writeByte(',');
931 try writer.writeAll(" .payload = {");
932 }
933 const union_obj = mod.typeToUnion(ty).?;
934 for (0..union_obj.field_types.len) |field_index| {
935 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
936 if (!field_ty.hasRuntimeBits(mod)) continue;
937 try dg.renderValue(writer, field_ty, val, initializer_type);
938 break;
939 }
940 if (ty.unionTagTypeSafety(mod)) |_| try writer.writeByte('}');
941 return writer.writeByte('}');
942 },
943 .ErrorUnion => {
944 const payload_ty = ty.errorUnionPayload(mod);
945 const error_ty = ty.errorUnionSet(mod);
946
947 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
948 return dg.renderValue(writer, error_ty, val, location);
949 }
950
951 if (!location.isInitializer()) {
952 try writer.writeByte('(');
953 try dg.renderType(writer, ty);
954 try writer.writeByte(')');
955 }
956
957 try writer.writeAll("{ .payload = ");
958 try dg.renderValue(writer, payload_ty, val, initializer_type);
959 try writer.writeAll(", .error = ");
960 try dg.renderValue(writer, error_ty, val, initializer_type);
961 return writer.writeAll(" }");
962 },
963 .Array, .Vector => {
964 const ai = ty.arrayInfo(mod);
965 if (ai.elem_type.eql(Type.u8, mod)) {
966 const c_len = ty.arrayLenIncludingSentinel(mod);
967 var literal = stringLiteral(writer, c_len);
968 try literal.start();
969 var index: u64 = 0;
970 while (index < c_len) : (index += 1)
971 try literal.writeChar(0xaa);
972 return literal.end();
973 } else {
974 if (!location.isInitializer()) {
975 try writer.writeByte('(');
976 try dg.renderType(writer, ty);
977 try writer.writeByte(')');
978 }
979
980 try writer.writeByte('{');
981 const c_len = ty.arrayLenIncludingSentinel(mod);
982 var index: u64 = 0;
983 while (index < c_len) : (index += 1) {
984 if (index > 0) try writer.writeAll(", ");
985 try dg.renderValue(writer, ty.childType(mod), val, initializer_type);
986 }
987 return writer.writeByte('}');
988 }
989 },
990 .ComptimeInt,
991 .ComptimeFloat,
992 .Type,
993 .EnumLiteral,
994 .Void,
995 .NoReturn,
996 .Undefined,
997 .Null,
998 .Opaque,
999 => unreachable,
1000
1001 .Fn,
1002 .Frame,
1003 .AnyFrame,
1004 => |tag| return dg.fail("TODO: C backend: implement value of type {s}", .{
1005 @tagName(tag),
1006 }),
1007 }
1008 unreachable;
1009 }
1010
1011 switch (ip.indexToKey(val.ip_index)) {
1012 // types, not values865 // types, not values
1013 .int_type,866 .int_type,
1014 .ptr_type,867 .ptr_type,
...@@ -1050,26 +903,28 @@ pub const DeclGen = struct {...@@ -1050,26 +903,28 @@ pub const DeclGen = struct {
1050 .empty_enum_value,903 .empty_enum_value,
1051 => unreachable, // non-runtime values904 => unreachable, // non-runtime values
1052 .int => |int| switch (int.storage) {905 .int => |int| switch (int.storage) {
1053 .u64, .i64, .big_int => try writer.print("{}", .{try dg.fmtIntLiteral(ty, val, location)}),906 .u64, .i64, .big_int => try writer.print("{}", .{try dg.fmtIntLiteral(val, location)}),
1054 .lazy_align, .lazy_size => {907 .lazy_align, .lazy_size => {
1055 try writer.writeAll("((");908 try writer.writeAll("((");
1056 try dg.renderType(writer, ty);909 try dg.renderType(writer, ty);
1057 return writer.print("){x})", .{try dg.fmtIntLiteral(Type.usize, val, .Other)});910 try writer.print("){x})", .{try dg.fmtIntLiteral(
911 try zcu.intValue(Type.usize, val.toUnsignedInt(zcu)),
912 .Other,
913 )});
1058 },914 },
1059 },915 },
1060 .err => |err| try writer.print("zig_error_{}", .{916 .err => |err| try writer.print("zig_error_{}", .{
1061 fmtIdent(ip.stringToSlice(err.name)),917 fmtIdent(ip.stringToSlice(err.name)),
1062 }),918 }),
1063 .error_union => |error_union| {919 .error_union => |error_union| {
1064 const payload_ty = ty.errorUnionPayload(mod);920 const payload_ty = ty.errorUnionPayload(zcu);
1065 const error_ty = ty.errorUnionSet(mod);921 const error_ty = ty.errorUnionSet(zcu);
1066 const err_int_ty = try mod.errorIntType();922 const err_int_ty = try zcu.errorIntType();
1067 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {923 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1068 switch (error_union.val) {924 switch (error_union.val) {
1069 .err_name => |err_name| return dg.renderValue(925 .err_name => |err_name| return dg.renderValue(
1070 writer,926 writer,
1071 error_ty,927 Value.fromInterned((try zcu.intern(.{ .err = .{
1072 Value.fromInterned((try mod.intern(.{ .err = .{
1073 .ty = error_ty.toIntern(),928 .ty = error_ty.toIntern(),
1074 .name = err_name,929 .name = err_name,
1075 } }))),930 } }))),
...@@ -1077,8 +932,7 @@ pub const DeclGen = struct {...@@ -1077,8 +932,7 @@ pub const DeclGen = struct {
1077 ),932 ),
1078 .payload => return dg.renderValue(933 .payload => return dg.renderValue(
1079 writer,934 writer,
1080 err_int_ty,935 try zcu.intValue(err_int_ty, 0),
1081 try mod.intValue(err_int_ty, 0),
1082 location,936 location,
1083 ),937 ),
1084 }938 }
...@@ -1093,9 +947,8 @@ pub const DeclGen = struct {...@@ -1093,9 +947,8 @@ pub const DeclGen = struct {
1093 try writer.writeAll("{ .payload = ");947 try writer.writeAll("{ .payload = ");
1094 try dg.renderValue(948 try dg.renderValue(
1095 writer,949 writer,
1096 payload_ty,
1097 Value.fromInterned(switch (error_union.val) {950 Value.fromInterned(switch (error_union.val) {
1098 .err_name => try mod.intern(.{ .undef = payload_ty.ip_index }),951 .err_name => (try zcu.undefValue(payload_ty)).toIntern(),
1099 .payload => |payload| payload,952 .payload => |payload| payload,
1100 }),953 }),
1101 initializer_type,954 initializer_type,
...@@ -1104,8 +957,7 @@ pub const DeclGen = struct {...@@ -1104,8 +957,7 @@ pub const DeclGen = struct {
1104 switch (error_union.val) {957 switch (error_union.val) {
1105 .err_name => |err_name| try dg.renderValue(958 .err_name => |err_name| try dg.renderValue(
1106 writer,959 writer,
1107 error_ty,960 Value.fromInterned((try zcu.intern(.{ .err = .{
1108 Value.fromInterned((try mod.intern(.{ .err = .{
1109 .ty = error_ty.toIntern(),961 .ty = error_ty.toIntern(),
1110 .name = err_name,962 .name = err_name,
1111 } }))),963 } }))),
...@@ -1113,24 +965,23 @@ pub const DeclGen = struct {...@@ -1113,24 +965,23 @@ pub const DeclGen = struct {
1113 ),965 ),
1114 .payload => try dg.renderValue(966 .payload => try dg.renderValue(
1115 writer,967 writer,
1116 err_int_ty,968 try zcu.intValue(err_int_ty, 0),
1117 try mod.intValue(err_int_ty, 0),
1118 location,969 location,
1119 ),970 ),
1120 }971 }
1121 try writer.writeAll(" }");972 try writer.writeAll(" }");
1122 },973 },
1123 .enum_tag => {974 .enum_tag => |enum_tag| try dg.renderValue(
1124 const enum_tag = ip.indexToKey(val.ip_index).enum_tag;975 writer,
1125 const int_tag_ty = ip.typeOf(enum_tag.int);976 Value.fromInterned(enum_tag.int),
1126 try dg.renderValue(writer, Type.fromInterned(int_tag_ty), Value.fromInterned(enum_tag.int), location);977 location,
1127 },978 ),
1128 .float => {979 .float => {
1129 const bits = ty.floatBits(target);980 const bits = ty.floatBits(target.*);
1130 const f128_val = val.toFloat(f128, mod);981 const f128_val = val.toFloat(f128, zcu);
1131982
1132 // All unsigned ints matching float types are pre-allocated.983 // All unsigned ints matching float types are pre-allocated.
1133 const repr_ty = mod.intType(.unsigned, bits) catch unreachable;984 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
1134985
1135 assert(bits <= 128);986 assert(bits <= 128);
1136 var repr_val_limbs: [BigInt.calcTwosCompLimbCount(128)]BigIntLimb = undefined;987 var repr_val_limbs: [BigInt.calcTwosCompLimbCount(128)]BigIntLimb = undefined;
...@@ -1141,26 +992,24 @@ pub const DeclGen = struct {...@@ -1141,26 +992,24 @@ pub const DeclGen = struct {
1141 };992 };
1142993
1143 switch (bits) {994 switch (bits) {
1144 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, mod)))),995 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, zcu)))),
1145 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, mod)))),996 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, zcu)))),
1146 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, mod)))),997 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, zcu)))),
1147 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, mod)))),998 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, zcu)))),
1148 128 => repr_val_big.set(@as(u128, @bitCast(f128_val))),999 128 => repr_val_big.set(@as(u128, @bitCast(f128_val))),
1149 else => unreachable,1000 else => unreachable,
1150 }1001 }
11511002
1152 const repr_val = try mod.intValue_big(repr_ty, repr_val_big.toConst());
1153
1154 var empty = true;1003 var empty = true;
1155 if (std.math.isFinite(f128_val)) {1004 if (std.math.isFinite(f128_val)) {
1156 try writer.writeAll("zig_make_");1005 try writer.writeAll("zig_make_");
1157 try dg.renderTypeForBuiltinFnName(writer, ty);1006 try dg.renderTypeForBuiltinFnName(writer, ty);
1158 try writer.writeByte('(');1007 try writer.writeByte('(');
1159 switch (bits) {1008 switch (bits) {
1160 16 => try writer.print("{x}", .{val.toFloat(f16, mod)}),1009 16 => try writer.print("{x}", .{val.toFloat(f16, zcu)}),
1161 32 => try writer.print("{x}", .{val.toFloat(f32, mod)}),1010 32 => try writer.print("{x}", .{val.toFloat(f32, zcu)}),
1162 64 => try writer.print("{x}", .{val.toFloat(f64, mod)}),1011 64 => try writer.print("{x}", .{val.toFloat(f64, zcu)}),
1163 80 => try writer.print("{x}", .{val.toFloat(f80, mod)}),1012 80 => try writer.print("{x}", .{val.toFloat(f80, zcu)}),
1164 128 => try writer.print("{x}", .{f128_val}),1013 128 => try writer.print("{x}", .{f128_val}),
1165 else => unreachable,1014 else => unreachable,
1166 }1015 }
...@@ -1200,17 +1049,20 @@ pub const DeclGen = struct {...@@ -1200,17 +1049,20 @@ pub const DeclGen = struct {
1200 if (std.math.isNan(f128_val)) switch (bits) {1049 if (std.math.isNan(f128_val)) switch (bits) {
1201 // We only actually need to pass the significand, but it will get1050 // We only actually need to pass the significand, but it will get
1202 // properly masked anyway, so just pass the whole value.1051 // properly masked anyway, so just pass the whole value.
1203 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, mod)))}),1052 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, zcu)))}),
1204 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, mod)))}),1053 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, zcu)))}),
1205 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, mod)))}),1054 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, zcu)))}),
1206 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, mod)))}),1055 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, zcu)))}),
1207 128 => try writer.print("\"0x{x}\"", .{@as(u128, @bitCast(f128_val))}),1056 128 => try writer.print("\"0x{x}\"", .{@as(u128, @bitCast(f128_val))}),
1208 else => unreachable,1057 else => unreachable,
1209 };1058 };
1210 try writer.writeAll(", ");1059 try writer.writeAll(", ");
1211 empty = false;1060 empty = false;
1212 }1061 }
1213 try writer.print("{x}", .{try dg.fmtIntLiteral(repr_ty, repr_val, location)});1062 try writer.print("{x}", .{try dg.fmtIntLiteral(
1063 try zcu.intValue_big(repr_ty, repr_val_big.toConst()),
1064 location,
1065 )});
1214 if (!empty) try writer.writeByte(')');1066 if (!empty) try writer.writeByte(')');
1215 },1067 },
1216 .slice => |slice| {1068 .slice => |slice| {
...@@ -1220,42 +1072,39 @@ pub const DeclGen = struct {...@@ -1220,42 +1072,39 @@ pub const DeclGen = struct {
1220 try writer.writeByte(')');1072 try writer.writeByte(')');
1221 }1073 }
1222 try writer.writeByte('{');1074 try writer.writeByte('{');
1223 try dg.renderValue(writer, ty.slicePtrFieldType(mod), Value.fromInterned(slice.ptr), initializer_type);1075 try dg.renderValue(writer, Value.fromInterned(slice.ptr), initializer_type);
1224 try writer.writeAll(", ");1076 try writer.writeAll(", ");
1225 try dg.renderValue(writer, Type.usize, Value.fromInterned(slice.len), initializer_type);1077 try dg.renderValue(writer, Value.fromInterned(slice.len), initializer_type);
1226 try writer.writeByte('}');1078 try writer.writeByte('}');
1227 },1079 },
1228 .ptr => |ptr| switch (ptr.addr) {1080 .ptr => |ptr| switch (ptr.addr) {
1229 .decl => |d| try dg.renderDeclValue(writer, ty, val, d, location),1081 .decl => |d| try dg.renderDeclValue(writer, val, d, location),
1230 .anon_decl => |decl_val| try dg.renderAnonDeclValue(writer, ty, val, decl_val, location),1082 .anon_decl => |decl_val| try dg.renderAnonDeclValue(writer, val, decl_val, location),
1231 .int => |int| {1083 .int => |int| {
1232 try writer.writeAll("((");1084 try writer.writeAll("((");
1233 try dg.renderType(writer, ty);1085 try dg.renderType(writer, ty);
1234 try writer.print("){x})", .{1086 try writer.print("){x})", .{try dg.fmtIntLiteral(Value.fromInterned(int), location)});
1235 try dg.fmtIntLiteral(Type.usize, Value.fromInterned(int), location),
1236 });
1237 },1087 },
1238 .eu_payload,1088 .eu_payload,
1239 .opt_payload,1089 .opt_payload,
1240 .elem,1090 .elem,
1241 .field,1091 .field,
1242 => try dg.renderParentPtr(writer, val.ip_index, location),1092 => try dg.renderParentPtr(writer, val.toIntern(), location),
1243 .comptime_field, .comptime_alloc => unreachable,1093 .comptime_field, .comptime_alloc => unreachable,
1244 },1094 },
1245 .opt => |opt| {1095 .opt => |opt| {
1246 const payload_ty = ty.optionalChild(mod);1096 const payload_ty = ty.optionalChild(zcu);
12471097
1248 const is_null_val = Value.makeBool(opt.val == .none);1098 const is_null_val = Value.makeBool(opt.val == .none);
1249 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod))1099 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu))
1250 return dg.renderValue(writer, Type.bool, is_null_val, location);1100 return dg.renderValue(writer, is_null_val, location);
12511101
1252 if (ty.optionalReprIsPayload(mod)) return dg.renderValue(1102 if (ty.optionalReprIsPayload(zcu)) return dg.renderValue(
1253 writer,1103 writer,
1254 payload_ty,
1255 switch (opt.val) {1104 switch (opt.val) {
1256 .none => switch (payload_ty.zigTypeTag(mod)) {1105 .none => switch (payload_ty.zigTypeTag(zcu)) {
1257 .ErrorSet => try mod.intValue(try mod.errorIntType(), 0),1106 .ErrorSet => try zcu.intValue(try zcu.errorIntType(), 0),
1258 .Pointer => try mod.getCoerced(val, payload_ty),1107 .Pointer => try zcu.getCoerced(val, payload_ty),
1259 else => unreachable,1108 else => unreachable,
1260 },1109 },
1261 else => |payload| Value.fromInterned(payload),1110 else => |payload| Value.fromInterned(payload),
...@@ -1270,15 +1119,19 @@ pub const DeclGen = struct {...@@ -1270,15 +1119,19 @@ pub const DeclGen = struct {
1270 }1119 }
12711120
1272 try writer.writeAll("{ .payload = ");1121 try writer.writeAll("{ .payload = ");
1273 try dg.renderValue(writer, payload_ty, Value.fromInterned(switch (opt.val) {1122 switch (opt.val) {
1274 .none => try mod.intern(.{ .undef = payload_ty.ip_index }),1123 .none => try dg.renderUndefValue(writer, payload_ty, initializer_type),
1275 else => |payload| payload,1124 else => |payload| try dg.renderValue(
1276 }), initializer_type);1125 writer,
1126 Value.fromInterned(payload),
1127 initializer_type,
1128 ),
1129 }
1277 try writer.writeAll(", .is_null = ");1130 try writer.writeAll(", .is_null = ");
1278 try dg.renderValue(writer, Type.bool, is_null_val, initializer_type);1131 try dg.renderValue(writer, is_null_val, initializer_type);
1279 try writer.writeAll(" }");1132 try writer.writeAll(" }");
1280 },1133 },
1281 .aggregate => switch (ip.indexToKey(ty.ip_index)) {1134 .aggregate => switch (ip.indexToKey(ty.toIntern())) {
1282 .array_type, .vector_type => {1135 .array_type, .vector_type => {
1283 if (location == .FunctionArgument) {1136 if (location == .FunctionArgument) {
1284 try writer.writeByte('(');1137 try writer.writeByte('(');
...@@ -1287,21 +1140,21 @@ pub const DeclGen = struct {...@@ -1287,21 +1140,21 @@ pub const DeclGen = struct {
1287 }1140 }
1288 // Fall back to generic implementation.1141 // Fall back to generic implementation.
12891142
1290 const ai = ty.arrayInfo(mod);1143 const ai = ty.arrayInfo(zcu);
1291 if (ai.elem_type.eql(Type.u8, mod)) {1144 if (ai.elem_type.eql(Type.u8, zcu)) {
1292 var literal = stringLiteral(writer, ty.arrayLenIncludingSentinel(mod));1145 var literal = stringLiteral(writer, ty.arrayLenIncludingSentinel(zcu));
1293 try literal.start();1146 try literal.start();
1294 var index: usize = 0;1147 var index: usize = 0;
1295 while (index < ai.len) : (index += 1) {1148 while (index < ai.len) : (index += 1) {
1296 const elem_val = try val.elemValue(mod, index);1149 const elem_val = try val.elemValue(zcu, index);
1297 const elem_val_u8: u8 = if (elem_val.isUndef(mod))1150 const elem_val_u8: u8 = if (elem_val.isUndef(zcu))
1298 undefPattern(u8)1151 undefPattern(u8)
1299 else1152 else
1300 @intCast(elem_val.toUnsignedInt(mod));1153 @intCast(elem_val.toUnsignedInt(zcu));
1301 try literal.writeChar(elem_val_u8);1154 try literal.writeChar(elem_val_u8);
1302 }1155 }
1303 if (ai.sentinel) |s| {1156 if (ai.sentinel) |s| {
1304 const s_u8: u8 = @intCast(s.toUnsignedInt(mod));1157 const s_u8: u8 = @intCast(s.toUnsignedInt(zcu));
1305 if (s_u8 != 0) try literal.writeChar(s_u8);1158 if (s_u8 != 0) try literal.writeChar(s_u8);
1306 }1159 }
1307 try literal.end();1160 try literal.end();
...@@ -1310,12 +1163,12 @@ pub const DeclGen = struct {...@@ -1310,12 +1163,12 @@ pub const DeclGen = struct {
1310 var index: usize = 0;1163 var index: usize = 0;
1311 while (index < ai.len) : (index += 1) {1164 while (index < ai.len) : (index += 1) {
1312 if (index != 0) try writer.writeByte(',');1165 if (index != 0) try writer.writeByte(',');
1313 const elem_val = try val.elemValue(mod, index);1166 const elem_val = try val.elemValue(zcu, index);
1314 try dg.renderValue(writer, ai.elem_type, elem_val, initializer_type);1167 try dg.renderValue(writer, elem_val, initializer_type);
1315 }1168 }
1316 if (ai.sentinel) |s| {1169 if (ai.sentinel) |s| {
1317 if (index != 0) try writer.writeByte(',');1170 if (index != 0) try writer.writeByte(',');
1318 try dg.renderValue(writer, ai.elem_type, s, initializer_type);1171 try dg.renderValue(writer, s, initializer_type);
1319 }1172 }
1320 try writer.writeByte('}');1173 try writer.writeByte('}');
1321 }1174 }
...@@ -1333,19 +1186,21 @@ pub const DeclGen = struct {...@@ -1333,19 +1186,21 @@ pub const DeclGen = struct {
1333 const comptime_val = tuple.values.get(ip)[field_index];1186 const comptime_val = tuple.values.get(ip)[field_index];
1334 if (comptime_val != .none) continue;1187 if (comptime_val != .none) continue;
1335 const field_ty = Type.fromInterned(tuple.types.get(ip)[field_index]);1188 const field_ty = Type.fromInterned(tuple.types.get(ip)[field_index]);
1336 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1189 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
13371190
1338 if (!empty) try writer.writeByte(',');1191 if (!empty) try writer.writeByte(',');
13391192
1340 const field_val = Value.fromInterned(switch (ip.indexToKey(val.ip_index).aggregate.storage) {1193 const field_val = Value.fromInterned(
1341 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{1194 switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1342 .ty = field_ty.toIntern(),1195 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1343 .storage = .{ .u64 = bytes[field_index] },1196 .ty = field_ty.toIntern(),
1344 } }),1197 .storage = .{ .u64 = bytes[field_index] },
1345 .elems => |elems| elems[field_index],1198 } }),
1346 .repeated_elem => |elem| elem,1199 .elems => |elems| elems[field_index],
1347 });1200 .repeated_elem => |elem| elem,
1348 try dg.renderValue(writer, field_ty, field_val, initializer_type);1201 },
1202 );
1203 try dg.renderValue(writer, field_val, initializer_type);
13491204
1350 empty = false;1205 empty = false;
1351 }1206 }
...@@ -1366,43 +1221,43 @@ pub const DeclGen = struct {...@@ -1366,43 +1221,43 @@ pub const DeclGen = struct {
1366 for (0..struct_type.field_types.len) |field_index| {1221 for (0..struct_type.field_types.len) |field_index| {
1367 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);1222 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1368 if (struct_type.fieldIsComptime(ip, field_index)) continue;1223 if (struct_type.fieldIsComptime(ip, field_index)) continue;
1369 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1224 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
13701225
1371 if (!empty) try writer.writeByte(',');1226 if (!empty) try writer.writeByte(',');
1372 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {1227 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1373 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{1228 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1374 .ty = field_ty.toIntern(),1229 .ty = field_ty.toIntern(),
1375 .storage = .{ .u64 = bytes[field_index] },1230 .storage = .{ .u64 = bytes[field_index] },
1376 } }),1231 } }),
1377 .elems => |elems| elems[field_index],1232 .elems => |elems| elems[field_index],
1378 .repeated_elem => |elem| elem,1233 .repeated_elem => |elem| elem,
1379 };1234 };
1380 try dg.renderValue(writer, field_ty, Value.fromInterned(field_val), initializer_type);1235 try dg.renderValue(writer, Value.fromInterned(field_val), initializer_type);
13811236
1382 empty = false;1237 empty = false;
1383 }1238 }
1384 try writer.writeByte('}');1239 try writer.writeByte('}');
1385 },1240 },
1386 .@"packed" => {1241 .@"packed" => {
1387 const int_info = ty.intInfo(mod);1242 const int_info = ty.intInfo(zcu);
13881243
1389 const bits = Type.smallestUnsignedBits(int_info.bits - 1);1244 const bits = Type.smallestUnsignedBits(int_info.bits - 1);
1390 const bit_offset_ty = try mod.intType(.unsigned, bits);1245 const bit_offset_ty = try zcu.intType(.unsigned, bits);
13911246
1392 var bit_offset: u64 = 0;1247 var bit_offset: u64 = 0;
1393 var eff_num_fields: usize = 0;1248 var eff_num_fields: usize = 0;
13941249
1395 for (0..struct_type.field_types.len) |field_index| {1250 for (0..struct_type.field_types.len) |field_index| {
1396 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);1251 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1397 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1252 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1398 eff_num_fields += 1;1253 eff_num_fields += 1;
1399 }1254 }
14001255
1401 if (eff_num_fields == 0) {1256 if (eff_num_fields == 0) {
1402 try writer.writeByte('(');1257 try writer.writeByte('(');
1403 try dg.renderValue(writer, ty, Value.undef, initializer_type);1258 try dg.renderUndefValue(writer, ty, initializer_type);
1404 try writer.writeByte(')');1259 try writer.writeByte(')');
1405 } else if (ty.bitSize(mod) > 64) {1260 } else if (ty.bitSize(zcu) > 64) {
1406 // zig_or_u128(zig_or_u128(zig_shl_u128(a, a_off), zig_shl_u128(b, b_off)), zig_shl_u128(c, c_off))1261 // zig_or_u128(zig_or_u128(zig_shl_u128(a, a_off), zig_shl_u128(b, b_off)), zig_shl_u128(c, c_off))
1407 var num_or = eff_num_fields - 1;1262 var num_or = eff_num_fields - 1;
1408 while (num_or > 0) : (num_or -= 1) {1263 while (num_or > 0) : (num_or -= 1) {
...@@ -1415,10 +1270,10 @@ pub const DeclGen = struct {...@@ -1415,10 +1270,10 @@ pub const DeclGen = struct {
1415 var needs_closing_paren = false;1270 var needs_closing_paren = false;
1416 for (0..struct_type.field_types.len) |field_index| {1271 for (0..struct_type.field_types.len) |field_index| {
1417 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);1272 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1418 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1273 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
14191274
1420 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {1275 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1421 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{1276 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1422 .ty = field_ty.toIntern(),1277 .ty = field_ty.toIntern(),
1423 .storage = .{ .u64 = bytes[field_index] },1278 .storage = .{ .u64 = bytes[field_index] },
1424 } }),1279 } }),
...@@ -1432,8 +1287,7 @@ pub const DeclGen = struct {...@@ -1432,8 +1287,7 @@ pub const DeclGen = struct {
1432 try writer.writeByte('(');1287 try writer.writeByte('(');
1433 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);1288 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
1434 try writer.writeAll(", ");1289 try writer.writeAll(", ");
1435 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);1290 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1436 try dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);
1437 try writer.writeByte(')');1291 try writer.writeByte(')');
1438 } else {1292 } else {
1439 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);1293 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
...@@ -1442,7 +1296,7 @@ pub const DeclGen = struct {...@@ -1442,7 +1296,7 @@ pub const DeclGen = struct {
1442 if (needs_closing_paren) try writer.writeByte(')');1296 if (needs_closing_paren) try writer.writeByte(')');
1443 if (eff_index != eff_num_fields - 1) try writer.writeAll(", ");1297 if (eff_index != eff_num_fields - 1) try writer.writeAll(", ");
14441298
1445 bit_offset += field_ty.bitSize(mod);1299 bit_offset += field_ty.bitSize(zcu);
1446 needs_closing_paren = true;1300 needs_closing_paren = true;
1447 eff_index += 1;1301 eff_index += 1;
1448 }1302 }
...@@ -1452,15 +1306,15 @@ pub const DeclGen = struct {...@@ -1452,15 +1306,15 @@ pub const DeclGen = struct {
1452 var empty = true;1306 var empty = true;
1453 for (0..struct_type.field_types.len) |field_index| {1307 for (0..struct_type.field_types.len) |field_index| {
1454 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);1308 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1455 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1309 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
14561310
1457 if (!empty) try writer.writeAll(" | ");1311 if (!empty) try writer.writeAll(" | ");
1458 try writer.writeByte('(');1312 try writer.writeByte('(');
1459 try dg.renderType(writer, ty);1313 try dg.renderType(writer, ty);
1460 try writer.writeByte(')');1314 try writer.writeByte(')');
14611315
1462 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {1316 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1463 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{1317 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1464 .ty = field_ty.toIntern(),1318 .ty = field_ty.toIntern(),
1465 .storage = .{ .u64 = bytes[field_index] },1319 .storage = .{ .u64 = bytes[field_index] },
1466 } }),1320 } }),
...@@ -1469,15 +1323,14 @@ pub const DeclGen = struct {...@@ -1469,15 +1323,14 @@ pub const DeclGen = struct {
1469 };1323 };
14701324
1471 if (bit_offset != 0) {1325 if (bit_offset != 0) {
1472 try dg.renderValue(writer, field_ty, Value.fromInterned(field_val), .Other);1326 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
1473 try writer.writeAll(" << ");1327 try writer.writeAll(" << ");
1474 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);1328 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1475 try dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);
1476 } else {1329 } else {
1477 try dg.renderValue(writer, field_ty, Value.fromInterned(field_val), .Other);1330 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
1478 }1331 }
14791332
1480 bit_offset += field_ty.bitSize(mod);1333 bit_offset += field_ty.bitSize(zcu);
1481 empty = false;1334 empty = false;
1482 }1335 }
1483 try writer.writeByte(')');1336 try writer.writeByte(')');
...@@ -1488,9 +1341,9 @@ pub const DeclGen = struct {...@@ -1488,9 +1341,9 @@ pub const DeclGen = struct {
1488 else => unreachable,1341 else => unreachable,
1489 },1342 },
1490 .un => |un| {1343 .un => |un| {
1491 const union_obj = mod.typeToUnion(ty).?;1344 const union_obj = zcu.typeToUnion(ty).?;
1492 if (un.tag == .none) {1345 if (un.tag == .none) {
1493 const backing_ty = try ty.unionBackingType(mod);1346 const backing_ty = try ty.unionBackingType(zcu);
1494 switch (union_obj.getLayout(ip)) {1347 switch (union_obj.getLayout(ip)) {
1495 .@"packed" => {1348 .@"packed" => {
1496 if (!location.isInitializer()) {1349 if (!location.isInitializer()) {
...@@ -1498,20 +1351,20 @@ pub const DeclGen = struct {...@@ -1498,20 +1351,20 @@ pub const DeclGen = struct {
1498 try dg.renderType(writer, backing_ty);1351 try dg.renderType(writer, backing_ty);
1499 try writer.writeByte(')');1352 try writer.writeByte(')');
1500 }1353 }
1501 try dg.renderValue(writer, backing_ty, Value.fromInterned(un.val), initializer_type);1354 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
1502 },1355 },
1503 .@"extern" => {1356 .@"extern" => {
1504 if (location == .StaticInitializer) {1357 if (location == .StaticInitializer) {
1505 return dg.fail("TODO: C backend: implement extern union backing type rendering in static initializers", .{});1358 return dg.fail("TODO: C backend: implement extern union backing type rendering in static initializers", .{});
1506 }1359 }
15071360
1508 const ptr_ty = try mod.singleConstPtrType(ty);1361 const ptr_ty = try zcu.singleConstPtrType(ty);
1509 try writer.writeAll("*((");1362 try writer.writeAll("*((");
1510 try dg.renderType(writer, ptr_ty);1363 try dg.renderType(writer, ptr_ty);
1511 try writer.writeAll(")(");1364 try writer.writeAll(")(");
1512 try dg.renderType(writer, backing_ty);1365 try dg.renderType(writer, backing_ty);
1513 try writer.writeAll("){");1366 try writer.writeAll("){");
1514 try dg.renderValue(writer, backing_ty, Value.fromInterned(un.val), initializer_type);1367 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
1515 try writer.writeAll("})");1368 try writer.writeAll("})");
1516 },1369 },
1517 else => unreachable,1370 else => unreachable,
...@@ -1523,21 +1376,21 @@ pub const DeclGen = struct {...@@ -1523,21 +1376,21 @@ pub const DeclGen = struct {
1523 try writer.writeByte(')');1376 try writer.writeByte(')');
1524 }1377 }
15251378
1526 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;1379 const field_index = zcu.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
1527 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);1380 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
1528 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];1381 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];
1529 if (union_obj.getLayout(ip) == .@"packed") {1382 if (union_obj.getLayout(ip) == .@"packed") {
1530 if (field_ty.hasRuntimeBits(mod)) {1383 if (field_ty.hasRuntimeBits(zcu)) {
1531 if (field_ty.isPtrAtRuntime(mod)) {1384 if (field_ty.isPtrAtRuntime(zcu)) {
1532 try writer.writeByte('(');1385 try writer.writeByte('(');
1533 try dg.renderType(writer, ty);1386 try dg.renderType(writer, ty);
1534 try writer.writeByte(')');1387 try writer.writeByte(')');
1535 } else if (field_ty.zigTypeTag(mod) == .Float) {1388 } else if (field_ty.zigTypeTag(zcu) == .Float) {
1536 try writer.writeByte('(');1389 try writer.writeByte('(');
1537 try dg.renderType(writer, ty);1390 try dg.renderType(writer, ty);
1538 try writer.writeByte(')');1391 try writer.writeByte(')');
1539 }1392 }
1540 try dg.renderValue(writer, field_ty, Value.fromInterned(un.val), initializer_type);1393 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
1541 } else {1394 } else {
1542 try writer.writeAll("0");1395 try writer.writeAll("0");
1543 }1396 }
...@@ -1545,30 +1398,236 @@ pub const DeclGen = struct {...@@ -1545,30 +1398,236 @@ pub const DeclGen = struct {
1545 }1398 }
15461399
1547 try writer.writeByte('{');1400 try writer.writeByte('{');
1548 if (ty.unionTagTypeSafety(mod)) |tag_ty| {1401 if (ty.unionTagTypeSafety(zcu)) |_| {
1549 const layout = mod.getUnionLayout(union_obj);1402 const layout = zcu.getUnionLayout(union_obj);
1550 if (layout.tag_size != 0) {1403 if (layout.tag_size != 0) {
1551 try writer.writeAll(" .tag = ");1404 try writer.writeAll(" .tag = ");
1552 try dg.renderValue(writer, tag_ty, Value.fromInterned(un.tag), initializer_type);1405 try dg.renderValue(writer, Value.fromInterned(un.tag), initializer_type);
1553 }1406 }
1554 if (ty.unionHasAllZeroBitFieldTypes(mod)) return try writer.writeByte('}');1407 if (ty.unionHasAllZeroBitFieldTypes(zcu)) return try writer.writeByte('}');
1555 if (layout.tag_size != 0) try writer.writeByte(',');1408 if (layout.tag_size != 0) try writer.writeByte(',');
1556 try writer.writeAll(" .payload = {");1409 try writer.writeAll(" .payload = {");
1557 }1410 }
1558 if (field_ty.hasRuntimeBits(mod)) {1411 if (field_ty.hasRuntimeBits(zcu)) {
1559 try writer.print(" .{ } = ", .{fmtIdent(ip.stringToSlice(field_name))});1412 try writer.print(" .{ } = ", .{fmtIdent(ip.stringToSlice(field_name))});
1560 try dg.renderValue(writer, field_ty, Value.fromInterned(un.val), initializer_type);1413 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
1561 try writer.writeByte(' ');1414 try writer.writeByte(' ');
1562 } else for (0..union_obj.field_types.len) |this_field_index| {1415 } else for (0..union_obj.field_types.len) |this_field_index| {
1563 const this_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[this_field_index]);1416 const this_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[this_field_index]);
1564 if (!this_field_ty.hasRuntimeBits(mod)) continue;1417 if (!this_field_ty.hasRuntimeBits(zcu)) continue;
1565 try dg.renderValue(writer, this_field_ty, Value.undef, initializer_type);1418 try dg.renderUndefValue(writer, this_field_ty, initializer_type);
1566 break;1419 break;
1567 }1420 }
1568 if (ty.unionTagTypeSafety(mod)) |_| try writer.writeByte('}');1421 if (ty.unionTagTypeSafety(zcu)) |_| try writer.writeByte('}');
1422 try writer.writeByte('}');
1423 }
1424 },
1425 }
1426 }
1427
1428 fn renderUndefValue(
1429 dg: *DeclGen,
1430 writer: anytype,
1431 ty: Type,
1432 location: ValueRenderLocation,
1433 ) error{ OutOfMemory, AnalysisFail }!void {
1434 const zcu = dg.zcu;
1435 const ip = &zcu.intern_pool;
1436 const target = &dg.mod.resolved_target.result;
1437
1438 const initializer_type: ValueRenderLocation = switch (location) {
1439 .StaticInitializer => .StaticInitializer,
1440 else => .Initializer,
1441 };
1442
1443 const safety_on = switch (zcu.optimizeMode()) {
1444 .Debug, .ReleaseSafe => true,
1445 .ReleaseFast, .ReleaseSmall => false,
1446 };
1447
1448 switch (ty.zigTypeTag(zcu)) {
1449 .Bool => try writer.writeAll(if (safety_on) "0xaa" else "false"),
1450 .Int, .Enum, .ErrorSet => try writer.print("{x}", .{
1451 try dg.fmtIntLiteral(try zcu.undefValue(ty), location),
1452 }),
1453 .Float => {
1454 const bits = ty.floatBits(target.*);
1455 // All unsigned ints matching float types are pre-allocated.
1456 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
1457
1458 try writer.writeAll("zig_make_");
1459 try dg.renderTypeForBuiltinFnName(writer, ty);
1460 try writer.writeByte('(');
1461 switch (bits) {
1462 16 => try writer.print("{x}", .{@as(f16, @bitCast(undefPattern(i16)))}),
1463 32 => try writer.print("{x}", .{@as(f32, @bitCast(undefPattern(i32)))}),
1464 64 => try writer.print("{x}", .{@as(f64, @bitCast(undefPattern(i64)))}),
1465 80 => try writer.print("{x}", .{@as(f80, @bitCast(undefPattern(i80)))}),
1466 128 => try writer.print("{x}", .{@as(f128, @bitCast(undefPattern(i128)))}),
1467 else => unreachable,
1468 }
1469 try writer.writeAll(", ");
1470 try dg.renderUndefValue(writer, repr_ty, .FunctionArgument);
1471 try writer.writeByte(')');
1472 },
1473 .Pointer => if (ty.isSlice(zcu)) {
1474 if (!location.isInitializer()) {
1475 try writer.writeByte('(');
1476 try dg.renderType(writer, ty);
1477 try writer.writeByte(')');
1478 }
1479
1480 try writer.writeAll("{(");
1481 const ptr_ty = ty.slicePtrFieldType(zcu);
1482 try dg.renderType(writer, ptr_ty);
1483 try writer.print("){x}, {0x}}}", .{try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other)});
1484 } else {
1485 try writer.writeAll("((");
1486 try dg.renderType(writer, ty);
1487 try writer.print("){x})", .{try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other)});
1488 },
1489 .Optional => {
1490 const payload_ty = ty.optionalChild(zcu);
1491
1492 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1493 return dg.renderUndefValue(writer, Type.bool, location);
1494 }
1495
1496 if (ty.optionalReprIsPayload(zcu)) {
1497 return dg.renderUndefValue(writer, payload_ty, location);
1498 }
1499
1500 if (!location.isInitializer()) {
1501 try writer.writeByte('(');
1502 try dg.renderType(writer, ty);
1503 try writer.writeByte(')');
1504 }
1505
1506 try writer.writeAll("{ .payload = ");
1507 try dg.renderUndefValue(writer, payload_ty, initializer_type);
1508 try writer.writeAll(", .is_null = ");
1509 try dg.renderUndefValue(writer, Type.bool, initializer_type);
1510 try writer.writeAll(" }");
1511 },
1512 .Struct => switch (ty.containerLayout(zcu)) {
1513 .auto, .@"extern" => {
1514 if (!location.isInitializer()) {
1515 try writer.writeByte('(');
1516 try dg.renderType(writer, ty);
1517 try writer.writeByte(')');
1518 }
1519
1520 try writer.writeByte('{');
1521 var empty = true;
1522 for (0..ty.structFieldCount(zcu)) |field_index| {
1523 if (ty.structFieldIsComptime(field_index, zcu)) continue;
1524 const field_ty = ty.structFieldType(field_index, zcu);
1525 if (!field_ty.hasRuntimeBits(zcu)) continue;
1526
1527 if (!empty) try writer.writeByte(',');
1528 try dg.renderUndefValue(writer, field_ty, initializer_type);
1529
1530 empty = false;
1531 }
1532
1569 try writer.writeByte('}');1533 try writer.writeByte('}');
1534 },
1535 .@"packed" => try writer.print("{x}", .{
1536 try dg.fmtIntLiteral(try zcu.undefValue(ty), .Other),
1537 }),
1538 },
1539 .Union => {
1540 if (!location.isInitializer()) {
1541 try writer.writeByte('(');
1542 try dg.renderType(writer, ty);
1543 try writer.writeByte(')');
1570 }1544 }
1545
1546 try writer.writeByte('{');
1547 if (ty.unionTagTypeSafety(zcu)) |tag_ty| {
1548 const layout = ty.unionGetLayout(zcu);
1549 if (layout.tag_size != 0) {
1550 try writer.writeAll(" .tag = ");
1551 try dg.renderUndefValue(writer, tag_ty, initializer_type);
1552 }
1553 if (ty.unionHasAllZeroBitFieldTypes(zcu)) return try writer.writeByte('}');
1554 if (layout.tag_size != 0) try writer.writeByte(',');
1555 try writer.writeAll(" .payload = {");
1556 }
1557 const union_obj = zcu.typeToUnion(ty).?;
1558 for (0..union_obj.field_types.len) |field_index| {
1559 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
1560 if (!field_ty.hasRuntimeBits(zcu)) continue;
1561 try dg.renderUndefValue(writer, field_ty, initializer_type);
1562 break;
1563 }
1564 if (ty.unionTagTypeSafety(zcu)) |_| try writer.writeByte('}');
1565 try writer.writeByte('}');
1571 },1566 },
1567 .ErrorUnion => {
1568 const payload_ty = ty.errorUnionPayload(zcu);
1569 const error_ty = ty.errorUnionSet(zcu);
1570
1571 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1572 return dg.renderUndefValue(writer, error_ty, location);
1573 }
1574
1575 if (!location.isInitializer()) {
1576 try writer.writeByte('(');
1577 try dg.renderType(writer, ty);
1578 try writer.writeByte(')');
1579 }
1580
1581 try writer.writeAll("{ .payload = ");
1582 try dg.renderUndefValue(writer, payload_ty, initializer_type);
1583 try writer.writeAll(", .error = ");
1584 try dg.renderUndefValue(writer, error_ty, initializer_type);
1585 try writer.writeAll(" }");
1586 },
1587 .Array, .Vector => {
1588 const ai = ty.arrayInfo(zcu);
1589 if (ai.elem_type.eql(Type.u8, zcu)) {
1590 const c_len = ty.arrayLenIncludingSentinel(zcu);
1591 var literal = stringLiteral(writer, c_len);
1592 try literal.start();
1593 var index: u64 = 0;
1594 while (index < c_len) : (index += 1)
1595 try literal.writeChar(0xaa);
1596 try literal.end();
1597 } else {
1598 if (!location.isInitializer()) {
1599 try writer.writeByte('(');
1600 try dg.renderType(writer, ty);
1601 try writer.writeByte(')');
1602 }
1603
1604 try writer.writeByte('{');
1605 const c_len = ty.arrayLenIncludingSentinel(zcu);
1606 var index: u64 = 0;
1607 while (index < c_len) : (index += 1) {
1608 if (index > 0) try writer.writeAll(", ");
1609 try dg.renderUndefValue(writer, ty.childType(zcu), initializer_type);
1610 }
1611 try writer.writeByte('}');
1612 }
1613 },
1614 .ComptimeInt,
1615 .ComptimeFloat,
1616 .Type,
1617 .EnumLiteral,
1618 .Void,
1619 .NoReturn,
1620 .Undefined,
1621 .Null,
1622 .Opaque,
1623 => unreachable,
1624
1625 .Fn,
1626 .Frame,
1627 .AnyFrame,
1628 => |tag| return dg.fail("TODO: C backend: implement value of type {s}", .{
1629 @tagName(tag),
1630 }),
1572 }1631 }
1573 }1632 }
15741633
...@@ -1583,14 +1642,14 @@ pub const DeclGen = struct {...@@ -1583,14 +1642,14 @@ pub const DeclGen = struct {
1583 },1642 },
1584 ) !void {1643 ) !void {
1585 const store = &dg.ctypes.set;1644 const store = &dg.ctypes.set;
1586 const mod = dg.module;1645 const zcu = dg.zcu;
1587 const ip = &mod.intern_pool;1646 const ip = &zcu.intern_pool;
15881647
1589 const fn_decl = mod.declPtr(fn_decl_index);1648 const fn_decl = zcu.declPtr(fn_decl_index);
1590 const fn_ty = fn_decl.typeOf(mod);1649 const fn_ty = fn_decl.typeOf(zcu);
1591 const fn_cty_idx = try dg.typeToIndex(fn_ty, kind);1650 const fn_cty_idx = try dg.typeToIndex(fn_ty, kind);
15921651
1593 const fn_info = mod.typeToFunc(fn_ty).?;1652 const fn_info = zcu.typeToFunc(fn_ty).?;
1594 if (fn_info.cc == .Naked) {1653 if (fn_info.cc == .Naked) {
1595 switch (kind) {1654 switch (kind) {
1596 .forward => try w.writeAll("zig_naked_decl "),1655 .forward => try w.writeAll("zig_naked_decl "),
...@@ -1598,11 +1657,11 @@ pub const DeclGen = struct {...@@ -1598,11 +1657,11 @@ pub const DeclGen = struct {
1598 else => unreachable,1657 else => unreachable,
1599 }1658 }
1600 }1659 }
1601 if (fn_decl.val.getFunction(mod)) |func| if (func.analysis(ip).is_cold)1660 if (fn_decl.val.getFunction(zcu)) |func| if (func.analysis(ip).is_cold)
1602 try w.writeAll("zig_cold ");1661 try w.writeAll("zig_cold ");
1603 if (fn_info.return_type == .noreturn_type) try w.writeAll("zig_noreturn ");1662 if (fn_info.return_type == .noreturn_type) try w.writeAll("zig_noreturn ");
16041663
1605 var trailing = try renderTypePrefix(dg.pass, store.*, mod, w, fn_cty_idx, .suffix, .{});1664 var trailing = try renderTypePrefix(dg.pass, store.*, zcu, w, fn_cty_idx, .suffix, .{});
16061665
1607 if (toCallingConvention(fn_info.cc)) |call_conv| {1666 if (toCallingConvention(fn_info.cc)) |call_conv| {
1608 try w.print("{}zig_callconv({s})", .{ trailing, call_conv });1667 try w.print("{}zig_callconv({s})", .{ trailing, call_conv });
...@@ -1629,7 +1688,7 @@ pub const DeclGen = struct {...@@ -1629,7 +1688,7 @@ pub const DeclGen = struct {
1629 try renderTypeSuffix(1688 try renderTypeSuffix(
1630 dg.pass,1689 dg.pass,
1631 store.*,1690 store.*,
1632 mod,1691 zcu,
1633 w,1692 w,
1634 fn_cty_idx,1693 fn_cty_idx,
1635 .suffix,1694 .suffix,
...@@ -1647,11 +1706,11 @@ pub const DeclGen = struct {...@@ -1647,11 +1706,11 @@ pub const DeclGen = struct {
1647 }1706 }
1648 switch (name) {1707 switch (name) {
1649 .export_index => |export_index| mangled: {1708 .export_index => |export_index| mangled: {
1650 const maybe_exports = mod.decl_exports.get(fn_decl_index);1709 const maybe_exports = zcu.decl_exports.get(fn_decl_index);
1651 const external_name = ip.stringToSlice(1710 const external_name = ip.stringToSlice(
1652 if (maybe_exports) |exports|1711 if (maybe_exports) |exports|
1653 exports.items[export_index].opts.name1712 exports.items[export_index].opts.name
1654 else if (fn_decl.isExtern(mod))1713 else if (fn_decl.isExtern(zcu))
1655 fn_decl.name1714 fn_decl.name
1656 else1715 else
1657 break :mangled,1716 break :mangled,
...@@ -1694,15 +1753,15 @@ pub const DeclGen = struct {...@@ -1694,15 +1753,15 @@ pub const DeclGen = struct {
1694 }1753 }
16951754
1696 fn typeToIndex(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType.Index {1755 fn typeToIndex(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType.Index {
1697 return dg.ctypes.typeToIndex(dg.gpa, ty, dg.module, kind);1756 return dg.ctypes.typeToIndex(dg.gpa, ty, dg.zcu, dg.mod, kind);
1698 }1757 }
16991758
1700 fn typeToCType(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType {1759 fn typeToCType(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType {
1701 return dg.ctypes.typeToCType(dg.gpa, ty, dg.module, kind);1760 return dg.ctypes.typeToCType(dg.gpa, ty, dg.zcu, dg.mod, kind);
1702 }1761 }
17031762
1704 fn byteSize(dg: *DeclGen, cty: CType) u64 {1763 fn byteSize(dg: *DeclGen, cty: CType) u64 {
1705 return cty.byteSize(dg.ctypes.set, dg.module.getTarget());1764 return cty.byteSize(dg.ctypes.set, dg.mod);
1706 }1765 }
17071766
1708 /// Renders a type as a single identifier, generating intermediate typedefs1767 /// Renders a type as a single identifier, generating intermediate typedefs
...@@ -1722,9 +1781,9 @@ pub const DeclGen = struct {...@@ -1722,9 +1781,9 @@ pub const DeclGen = struct {
17221781
1723 fn renderCType(dg: *DeclGen, w: anytype, idx: CType.Index) error{ OutOfMemory, AnalysisFail }!void {1782 fn renderCType(dg: *DeclGen, w: anytype, idx: CType.Index) error{ OutOfMemory, AnalysisFail }!void {
1724 const store = &dg.ctypes.set;1783 const store = &dg.ctypes.set;
1725 const mod = dg.module;1784 const zcu = dg.zcu;
1726 _ = try renderTypePrefix(dg.pass, store.*, mod, w, idx, .suffix, .{});1785 _ = try renderTypePrefix(dg.pass, store.*, zcu, w, idx, .suffix, .{});
1727 try renderTypeSuffix(dg.pass, store.*, mod, w, idx, .suffix, .{});1786 try renderTypeSuffix(dg.pass, store.*, zcu, w, idx, .suffix, .{});
1728 }1787 }
17291788
1730 const IntCastContext = union(enum) {1789 const IntCastContext = union(enum) {
...@@ -1737,15 +1796,13 @@ pub const DeclGen = struct {...@@ -1737,15 +1796,13 @@ pub const DeclGen = struct {
1737 value: Value,1796 value: Value,
1738 },1797 },
17391798
1740 pub fn writeValue(self: *const IntCastContext, dg: *DeclGen, w: anytype, value_ty: Type, location: ValueRenderLocation) !void {1799 pub fn writeValue(self: *const IntCastContext, dg: *DeclGen, w: anytype, location: ValueRenderLocation) !void {
1741 switch (self.*) {1800 switch (self.*) {
1742 .c_value => |v| {1801 .c_value => |v| {
1743 try v.f.writeCValue(w, v.value, location);1802 try v.f.writeCValue(w, v.value, location);
1744 try v.v.elem(v.f, w);1803 try v.v.elem(v.f, w);
1745 },1804 },
1746 .value => |v| {1805 .value => |v| try dg.renderValue(w, v.value, location),
1747 try dg.renderValue(w, value_ty, v.value, location);
1748 },
1749 }1806 }
1750 }1807 }
1751 };1808 };
...@@ -1764,18 +1821,18 @@ pub const DeclGen = struct {...@@ -1764,18 +1821,18 @@ pub const DeclGen = struct {
1764 /// | > 64 bit integer | < 64 bit integer | zig_make_<dest_ty>(0, src)1821 /// | > 64 bit integer | < 64 bit integer | zig_make_<dest_ty>(0, src)
1765 /// | > 64 bit integer | > 64 bit integer | zig_make_<dest_ty>(zig_hi_<src_ty>(src), zig_lo_<src_ty>(src))1822 /// | > 64 bit integer | > 64 bit integer | zig_make_<dest_ty>(zig_hi_<src_ty>(src), zig_lo_<src_ty>(src))
1766 fn renderIntCast(dg: *DeclGen, w: anytype, dest_ty: Type, context: IntCastContext, src_ty: Type, location: ValueRenderLocation) !void {1823 fn renderIntCast(dg: *DeclGen, w: anytype, dest_ty: Type, context: IntCastContext, src_ty: Type, location: ValueRenderLocation) !void {
1767 const mod = dg.module;1824 const zcu = dg.zcu;
1768 const dest_bits = dest_ty.bitSize(mod);1825 const dest_bits = dest_ty.bitSize(zcu);
1769 const dest_int_info = dest_ty.intInfo(mod);1826 const dest_int_info = dest_ty.intInfo(zcu);
17701827
1771 const src_is_ptr = src_ty.isPtrAtRuntime(mod);1828 const src_is_ptr = src_ty.isPtrAtRuntime(zcu);
1772 const src_eff_ty: Type = if (src_is_ptr) switch (dest_int_info.signedness) {1829 const src_eff_ty: Type = if (src_is_ptr) switch (dest_int_info.signedness) {
1773 .unsigned => Type.usize,1830 .unsigned => Type.usize,
1774 .signed => Type.isize,1831 .signed => Type.isize,
1775 } else src_ty;1832 } else src_ty;
17761833
1777 const src_bits = src_eff_ty.bitSize(mod);1834 const src_bits = src_eff_ty.bitSize(zcu);
1778 const src_int_info = if (src_eff_ty.isAbiInt(mod)) src_eff_ty.intInfo(mod) else null;1835 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
1779 if (dest_bits <= 64 and src_bits <= 64) {1836 if (dest_bits <= 64 and src_bits <= 64) {
1780 const needs_cast = src_int_info == null or1837 const needs_cast = src_int_info == null or
1781 (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or1838 (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or
...@@ -1791,7 +1848,7 @@ pub const DeclGen = struct {...@@ -1791,7 +1848,7 @@ pub const DeclGen = struct {
1791 try dg.renderType(w, src_eff_ty);1848 try dg.renderType(w, src_eff_ty);
1792 try w.writeByte(')');1849 try w.writeByte(')');
1793 }1850 }
1794 try context.writeValue(dg, w, src_ty, location);1851 try context.writeValue(dg, w, location);
1795 } else if (dest_bits <= 64 and src_bits > 64) {1852 } else if (dest_bits <= 64 and src_bits > 64) {
1796 assert(!src_is_ptr);1853 assert(!src_is_ptr);
1797 if (dest_bits < 64) {1854 if (dest_bits < 64) {
...@@ -1802,7 +1859,7 @@ pub const DeclGen = struct {...@@ -1802,7 +1859,7 @@ pub const DeclGen = struct {
1802 try w.writeAll("zig_lo_");1859 try w.writeAll("zig_lo_");
1803 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);1860 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
1804 try w.writeByte('(');1861 try w.writeByte('(');
1805 try context.writeValue(dg, w, src_ty, .FunctionArgument);1862 try context.writeValue(dg, w, .FunctionArgument);
1806 try w.writeByte(')');1863 try w.writeByte(')');
1807 } else if (dest_bits > 64 and src_bits <= 64) {1864 } else if (dest_bits > 64 and src_bits <= 64) {
1808 try w.writeAll("zig_make_");1865 try w.writeAll("zig_make_");
...@@ -1813,7 +1870,7 @@ pub const DeclGen = struct {...@@ -1813,7 +1870,7 @@ pub const DeclGen = struct {
1813 try dg.renderType(w, src_eff_ty);1870 try dg.renderType(w, src_eff_ty);
1814 try w.writeByte(')');1871 try w.writeByte(')');
1815 }1872 }
1816 try context.writeValue(dg, w, src_ty, .FunctionArgument);1873 try context.writeValue(dg, w, .FunctionArgument);
1817 try w.writeByte(')');1874 try w.writeByte(')');
1818 } else {1875 } else {
1819 assert(!src_is_ptr);1876 assert(!src_is_ptr);
...@@ -1822,11 +1879,11 @@ pub const DeclGen = struct {...@@ -1822,11 +1879,11 @@ pub const DeclGen = struct {
1822 try w.writeAll("(zig_hi_");1879 try w.writeAll("(zig_hi_");
1823 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);1880 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
1824 try w.writeByte('(');1881 try w.writeByte('(');
1825 try context.writeValue(dg, w, src_ty, .FunctionArgument);1882 try context.writeValue(dg, w, .FunctionArgument);
1826 try w.writeAll("), zig_lo_");1883 try w.writeAll("), zig_lo_");
1827 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);1884 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
1828 try w.writeByte('(');1885 try w.writeByte('(');
1829 try context.writeValue(dg, w, src_ty, .FunctionArgument);1886 try context.writeValue(dg, w, .FunctionArgument);
1830 try w.writeAll("))");1887 try w.writeAll("))");
1831 }1888 }
1832 }1889 }
...@@ -1848,8 +1905,8 @@ pub const DeclGen = struct {...@@ -1848,8 +1905,8 @@ pub const DeclGen = struct {
1848 alignment: Alignment,1905 alignment: Alignment,
1849 kind: CType.Kind,1906 kind: CType.Kind,
1850 ) error{ OutOfMemory, AnalysisFail }!void {1907 ) error{ OutOfMemory, AnalysisFail }!void {
1851 const mod = dg.module;1908 const zcu = dg.zcu;
1852 const alignas = CType.AlignAs.init(alignment, ty.abiAlignment(mod));1909 const alignas = CType.AlignAs.init(alignment, ty.abiAlignment(zcu));
1853 try dg.renderCTypeAndName(w, try dg.typeToIndex(ty, kind), name, qualifiers, alignas);1910 try dg.renderCTypeAndName(w, try dg.typeToIndex(ty, kind), name, qualifiers, alignas);
1854 }1911 }
18551912
...@@ -1862,7 +1919,7 @@ pub const DeclGen = struct {...@@ -1862,7 +1919,7 @@ pub const DeclGen = struct {
1862 alignas: CType.AlignAs,1919 alignas: CType.AlignAs,
1863 ) error{ OutOfMemory, AnalysisFail }!void {1920 ) error{ OutOfMemory, AnalysisFail }!void {
1864 const store = &dg.ctypes.set;1921 const store = &dg.ctypes.set;
1865 const mod = dg.module;1922 const zcu = dg.zcu;
18661923
1867 switch (alignas.abiOrder()) {1924 switch (alignas.abiOrder()) {
1868 .lt => try w.print("zig_under_align({}) ", .{alignas.toByteUnits()}),1925 .lt => try w.print("zig_under_align({}) ", .{alignas.toByteUnits()}),
...@@ -1870,39 +1927,46 @@ pub const DeclGen = struct {...@@ -1870,39 +1927,46 @@ pub const DeclGen = struct {
1870 .gt => try w.print("zig_align({}) ", .{alignas.toByteUnits()}),1927 .gt => try w.print("zig_align({}) ", .{alignas.toByteUnits()}),
1871 }1928 }
18721929
1873 const trailing = try renderTypePrefix(dg.pass, store.*, mod, w, cty_idx, .suffix, qualifiers);1930 const trailing = try renderTypePrefix(dg.pass, store.*, zcu, w, cty_idx, .suffix, qualifiers);
1874 try w.print("{}", .{trailing});1931 try w.print("{}", .{trailing});
1875 try dg.writeCValue(w, name);1932 try dg.writeName(w, name);
1876 try renderTypeSuffix(dg.pass, store.*, mod, w, cty_idx, .suffix, .{});1933 try renderTypeSuffix(dg.pass, store.*, zcu, w, cty_idx, .suffix, .{});
1877 }1934 }
18781935
1879 fn declIsGlobal(dg: *DeclGen, val: Value) bool {1936 fn declIsGlobal(dg: *DeclGen, val: Value) bool {
1880 const mod = dg.module;1937 const zcu = dg.zcu;
1881 return switch (mod.intern_pool.indexToKey(val.ip_index)) {1938 return switch (zcu.intern_pool.indexToKey(val.toIntern())) {
1882 .variable => |variable| mod.decl_exports.contains(variable.decl),1939 .variable => |variable| zcu.decl_exports.contains(variable.decl),
1883 .extern_func => true,1940 .extern_func => true,
1884 .func => |func| mod.decl_exports.contains(func.owner_decl),1941 .func => |func| zcu.decl_exports.contains(func.owner_decl),
1885 else => unreachable,1942 else => unreachable,
1886 };1943 };
1887 }1944 }
18881945
1946 fn writeName(dg: *DeclGen, w: anytype, c_value: CValue) !void {
1947 switch (c_value) {
1948 .new_local, .local => |i| try w.print("t{d}", .{i}),
1949 .constant => |val| try renderAnonDeclName(w, val),
1950 .decl => |decl| try dg.renderDeclName(w, decl, 0),
1951 .identifier => |ident| try w.print("{ }", .{fmtIdent(ident)}),
1952 else => unreachable,
1953 }
1954 }
1955
1889 fn writeCValue(dg: *DeclGen, w: anytype, c_value: CValue) !void {1956 fn writeCValue(dg: *DeclGen, w: anytype, c_value: CValue) !void {
1890 switch (c_value) {1957 switch (c_value) {
1891 .none => unreachable,1958 .none, .new_local, .local, .local_ref => unreachable,
1892 .local, .new_local => |i| return w.print("t{d}", .{i}),1959 .constant => |val| try renderAnonDeclName(w, val),
1893 .local_ref => |i| return w.print("&t{d}", .{i}),1960 .arg, .arg_array => unreachable,
1894 .constant => |val| return renderAnonDeclName(w, val),1961 .field => |i| try w.print("f{d}", .{i}),
1895 .arg => |i| return w.print("a{d}", .{i}),1962 .decl => |decl| try dg.renderDeclName(w, decl, 0),
1896 .arg_array => |i| return dg.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" }),
1897 .field => |i| return w.print("f{d}", .{i}),
1898 .decl => |decl| return dg.renderDeclName(w, decl, 0),
1899 .decl_ref => |decl| {1963 .decl_ref => |decl| {
1900 try w.writeByte('&');1964 try w.writeByte('&');
1901 return dg.renderDeclName(w, decl, 0);1965 try dg.renderDeclName(w, decl, 0);
1902 },1966 },
1903 .undef => |ty| return dg.renderValue(w, ty, Value.undef, .Other),1967 .undef => |ty| try dg.renderUndefValue(w, ty, .Other),
1904 .identifier => |ident| return w.print("{ }", .{fmtIdent(ident)}),1968 .identifier => |ident| try w.print("{ }", .{fmtIdent(ident)}),
1905 .payload_identifier => |ident| return w.print("{ }.{ }", .{1969 .payload_identifier => |ident| try w.print("{ }.{ }", .{
1906 fmtIdent("payload"),1970 fmtIdent("payload"),
1907 fmtIdent(ident),1971 fmtIdent(ident),
1908 }),1972 }),
...@@ -1911,26 +1975,17 @@ pub const DeclGen = struct {...@@ -1911,26 +1975,17 @@ pub const DeclGen = struct {
19111975
1912 fn writeCValueDeref(dg: *DeclGen, w: anytype, c_value: CValue) !void {1976 fn writeCValueDeref(dg: *DeclGen, w: anytype, c_value: CValue) !void {
1913 switch (c_value) {1977 switch (c_value) {
1914 .none => unreachable,1978 .none, .new_local, .local, .local_ref, .constant, .arg, .arg_array => unreachable,
1915 .local, .new_local => |i| return w.print("(*t{d})", .{i}),1979 .field => |i| try w.print("f{d}", .{i}),
1916 .local_ref => |i| return w.print("t{d}", .{i}),
1917 .constant => unreachable,
1918 .arg => |i| return w.print("(*a{d})", .{i}),
1919 .arg_array => |i| {
1920 try w.writeAll("(*");
1921 try dg.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" });
1922 return w.writeByte(')');
1923 },
1924 .field => |i| return w.print("f{d}", .{i}),
1925 .decl => |decl| {1980 .decl => |decl| {
1926 try w.writeAll("(*");1981 try w.writeAll("(*");
1927 try dg.renderDeclName(w, decl, 0);1982 try dg.renderDeclName(w, decl, 0);
1928 return w.writeByte(')');1983 try w.writeByte(')');
1929 },1984 },
1930 .decl_ref => |decl| return dg.renderDeclName(w, decl, 0),1985 .decl_ref => |decl| try dg.renderDeclName(w, decl, 0),
1931 .undef => unreachable,1986 .undef => unreachable,
1932 .identifier => |ident| return w.print("(*{ })", .{fmtIdent(ident)}),1987 .identifier => |ident| try w.print("(*{ })", .{fmtIdent(ident)}),
1933 .payload_identifier => |ident| return w.print("(*{ }.{ })", .{1988 .payload_identifier => |ident| try w.print("(*{ }.{ })", .{
1934 fmtIdent("payload"),1989 fmtIdent("payload"),
1935 fmtIdent(ident),1990 fmtIdent(ident),
1936 }),1991 }),
...@@ -1950,12 +2005,12 @@ pub const DeclGen = struct {...@@ -1950,12 +2005,12 @@ pub const DeclGen = struct {
19502005
1951 fn writeCValueDerefMember(dg: *DeclGen, writer: anytype, c_value: CValue, member: CValue) !void {2006 fn writeCValueDerefMember(dg: *DeclGen, writer: anytype, c_value: CValue, member: CValue) !void {
1952 switch (c_value) {2007 switch (c_value) {
1953 .none, .constant, .field, .undef => unreachable,2008 .none, .new_local, .local, .local_ref, .constant, .field, .undef, .arg, .arg_array => unreachable,
1954 .new_local, .local, .arg, .arg_array, .decl, .identifier, .payload_identifier => {2009 .decl, .identifier, .payload_identifier => {
1955 try dg.writeCValue(writer, c_value);2010 try dg.writeCValue(writer, c_value);
1956 try writer.writeAll("->");2011 try writer.writeAll("->");
1957 },2012 },
1958 .local_ref, .decl_ref => {2013 .decl_ref => {
1959 try dg.writeCValueDeref(writer, c_value);2014 try dg.writeCValueDeref(writer, c_value);
1960 try writer.writeByte('.');2015 try writer.writeByte('.');
1961 },2016 },
...@@ -1969,11 +2024,12 @@ pub const DeclGen = struct {...@@ -1969,11 +2024,12 @@ pub const DeclGen = struct {
1969 variable: InternPool.Key.Variable,2024 variable: InternPool.Key.Variable,
1970 fwd_kind: enum { tentative, final },2025 fwd_kind: enum { tentative, final },
1971 ) !void {2026 ) !void {
1972 const decl = dg.module.declPtr(decl_index);2027 const zcu = dg.zcu;
2028 const decl = zcu.declPtr(decl_index);
1973 const fwd = dg.fwdDeclWriter();2029 const fwd = dg.fwdDeclWriter();
1974 const is_global = variable.is_extern or dg.declIsGlobal(decl.val);2030 const is_global = variable.is_extern or dg.declIsGlobal(decl.val);
1975 try fwd.writeAll(if (is_global) "zig_extern " else "static ");2031 try fwd.writeAll(if (is_global) "zig_extern " else "static ");
1976 const maybe_exports = dg.module.decl_exports.get(decl_index);2032 const maybe_exports = zcu.decl_exports.get(decl_index);
1977 const export_weak_linkage = if (maybe_exports) |exports|2033 const export_weak_linkage = if (maybe_exports) |exports|
1978 exports.items[0].opts.linkage == .weak2034 exports.items[0].opts.linkage == .weak
1979 else2035 else
...@@ -1982,14 +2038,14 @@ pub const DeclGen = struct {...@@ -1982,14 +2038,14 @@ pub const DeclGen = struct {
1982 if (variable.is_threadlocal) try fwd.writeAll("zig_threadlocal ");2038 if (variable.is_threadlocal) try fwd.writeAll("zig_threadlocal ");
1983 try dg.renderTypeAndName(2039 try dg.renderTypeAndName(
1984 fwd,2040 fwd,
1985 decl.typeOf(dg.module),2041 decl.typeOf(zcu),
1986 .{ .decl = decl_index },2042 .{ .decl = decl_index },
1987 CQualifiers.init(.{ .@"const" = variable.is_const }),2043 CQualifiers.init(.{ .@"const" = variable.is_const }),
1988 decl.alignment,2044 decl.alignment,
1989 .complete,2045 .complete,
1990 );2046 );
1991 mangled: {2047 mangled: {
1992 const external_name = dg.module.intern_pool.stringToSlice(if (maybe_exports) |exports|2048 const external_name = zcu.intern_pool.stringToSlice(if (maybe_exports) |exports|
1993 exports.items[0].opts.name2049 exports.items[0].opts.name
1994 else if (variable.is_extern)2050 else if (variable.is_extern)
1995 decl.name2051 decl.name
...@@ -2007,23 +2063,23 @@ pub const DeclGen = struct {...@@ -2007,23 +2063,23 @@ pub const DeclGen = struct {
2007 }2063 }
20082064
2009 fn renderDeclName(dg: *DeclGen, writer: anytype, decl_index: InternPool.DeclIndex, export_index: u32) !void {2065 fn renderDeclName(dg: *DeclGen, writer: anytype, decl_index: InternPool.DeclIndex, export_index: u32) !void {
2010 const mod = dg.module;2066 const zcu = dg.zcu;
2011 const decl = mod.declPtr(decl_index);2067 const decl = zcu.declPtr(decl_index);
20122068
2013 if (mod.decl_exports.get(decl_index)) |exports| {2069 if (zcu.decl_exports.get(decl_index)) |exports| {
2014 try writer.print("{ }", .{2070 try writer.print("{ }", .{
2015 fmtIdent(mod.intern_pool.stringToSlice(exports.items[export_index].opts.name)),2071 fmtIdent(zcu.intern_pool.stringToSlice(exports.items[export_index].opts.name)),
2016 });2072 });
2017 } else if (decl.getExternDecl(mod).unwrap()) |extern_decl_index| {2073 } else if (decl.getExternDecl(zcu).unwrap()) |extern_decl_index| {
2018 try writer.print("{ }", .{2074 try writer.print("{ }", .{
2019 fmtIdent(mod.intern_pool.stringToSlice(mod.declPtr(extern_decl_index).name)),2075 fmtIdent(zcu.intern_pool.stringToSlice(zcu.declPtr(extern_decl_index).name)),
2020 });2076 });
2021 } else {2077 } else {
2022 // MSVC has a limit of 4095 character token length limit, and fmtIdent can (worst case),2078 // MSVC has a limit of 4095 character token length limit, and fmtIdent can (worst case),
2023 // expand to 3x the length of its input, but let's cut it off at a much shorter limit.2079 // expand to 3x the length of its input, but let's cut it off at a much shorter limit.
2024 var name: [100]u8 = undefined;2080 var name: [100]u8 = undefined;
2025 var name_stream = std.io.fixedBufferStream(&name);2081 var name_stream = std.io.fixedBufferStream(&name);
2026 decl.renderFullyQualifiedName(mod, name_stream.writer()) catch |err| switch (err) {2082 decl.renderFullyQualifiedName(zcu, name_stream.writer()) catch |err| switch (err) {
2027 error.NoSpaceLeft => {},2083 error.NoSpaceLeft => {},
2028 };2084 };
2029 try writer.print("{}__{d}", .{2085 try writer.print("{}__{d}", .{
...@@ -2033,8 +2089,8 @@ pub const DeclGen = struct {...@@ -2033,8 +2089,8 @@ pub const DeclGen = struct {
2033 }2089 }
2034 }2090 }
20352091
2036 fn renderAnonDeclName(writer: anytype, anon_decl_val: InternPool.Index) !void {2092 fn renderAnonDeclName(writer: anytype, anon_decl_val: Value) !void {
2037 return writer.print("__anon_{d}", .{@intFromEnum(anon_decl_val)});2093 try writer.print("__anon_{d}", .{@intFromEnum(anon_decl_val.toIntern())});
2038 }2094 }
20392095
2040 fn renderTypeForBuiltinFnName(dg: *DeclGen, writer: anytype, ty: Type) !void {2096 fn renderTypeForBuiltinFnName(dg: *DeclGen, writer: anytype, ty: Type) !void {
...@@ -2047,7 +2103,7 @@ pub const DeclGen = struct {...@@ -2047,7 +2103,7 @@ pub const DeclGen = struct {
2047 if (cty.isBool())2103 if (cty.isBool())
2048 signAbbrev(.unsigned)2104 signAbbrev(.unsigned)
2049 else if (cty.isInteger())2105 else if (cty.isInteger())
2050 signAbbrev(cty.signedness(dg.module.getTarget()))2106 signAbbrev(cty.signedness(dg.mod))
2051 else if (cty.isFloat())2107 else if (cty.isFloat())
2052 @as(u8, 'f')2108 @as(u8, 'f')
2053 else if (cty.isPointer())2109 else if (cty.isPointer())
...@@ -2056,7 +2112,7 @@ pub const DeclGen = struct {...@@ -2056,7 +2112,7 @@ pub const DeclGen = struct {
2056 return dg.fail("TODO: CBE: implement renderTypeForBuiltinFnName for type {}", .{2112 return dg.fail("TODO: CBE: implement renderTypeForBuiltinFnName for type {}", .{
2057 cty.tag(),2113 cty.tag(),
2058 }),2114 }),
2059 if (cty.isFloat()) cty.floatActiveBits(dg.module.getTarget()) else dg.byteSize(cty) * 8,2115 if (cty.isFloat()) cty.floatActiveBits(dg.mod) else dg.byteSize(cty) * 8,
2060 }),2116 }),
2061 .array => try writer.writeAll("big"),2117 .array => try writer.writeAll("big"),
2062 }2118 }
...@@ -2065,43 +2121,39 @@ pub const DeclGen = struct {...@@ -2065,43 +2121,39 @@ pub const DeclGen = struct {
2065 fn renderBuiltinInfo(dg: *DeclGen, writer: anytype, ty: Type, info: BuiltinInfo) !void {2121 fn renderBuiltinInfo(dg: *DeclGen, writer: anytype, ty: Type, info: BuiltinInfo) !void {
2066 const cty = try dg.typeToCType(ty, .complete);2122 const cty = try dg.typeToCType(ty, .complete);
2067 const is_big = cty.tag() == .array;2123 const is_big = cty.tag() == .array;
2068
2069 switch (info) {2124 switch (info) {
2070 .none => if (!is_big) return,2125 .none => if (!is_big) return,
2071 .bits => {},2126 .bits => {},
2072 }2127 }
20732128
2074 const mod = dg.module;2129 const zcu = dg.zcu;
2075 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{2130 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
2076 .signedness = .unsigned,2131 .signedness = .unsigned,
2077 .bits = @as(u16, @intCast(ty.bitSize(mod))),2132 .bits = @as(u16, @intCast(ty.bitSize(zcu))),
2078 };2133 };
20792134
2080 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});2135 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});
2081
2082 const bits_ty = if (is_big) Type.u16 else Type.u8;
2083 try writer.print(", {}", .{try dg.fmtIntLiteral(2136 try writer.print(", {}", .{try dg.fmtIntLiteral(
2084 bits_ty,2137 try zcu.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
2085 try mod.intValue(bits_ty, int_info.bits),
2086 .FunctionArgument,2138 .FunctionArgument,
2087 )});2139 )});
2088 }2140 }
20892141
2090 fn fmtIntLiteral(2142 fn fmtIntLiteral(
2091 dg: *DeclGen,2143 dg: *DeclGen,
2092 ty: Type,
2093 val: Value,2144 val: Value,
2094 loc: ValueRenderLocation,2145 loc: ValueRenderLocation,
2095 ) !std.fmt.Formatter(formatIntLiteral) {2146 ) !std.fmt.Formatter(formatIntLiteral) {
2096 const mod = dg.module;2147 const zcu = dg.zcu;
2097 const kind: CType.Kind = switch (loc) {2148 const kind: CType.Kind = switch (loc) {
2098 .FunctionArgument => .parameter,2149 .FunctionArgument => .parameter,
2099 .Initializer, .Other => .complete,2150 .Initializer, .Other => .complete,
2100 .StaticInitializer => .global,2151 .StaticInitializer => .global,
2101 };2152 };
2153 const ty = val.typeOf(zcu);
2102 return std.fmt.Formatter(formatIntLiteral){ .data = .{2154 return std.fmt.Formatter(formatIntLiteral){ .data = .{
2103 .dg = dg,2155 .dg = dg,
2104 .int_info = ty.intInfo(mod),2156 .int_info = ty.intInfo(zcu),
2105 .kind = kind,2157 .kind = kind,
2106 .cty = try dg.typeToCType(ty, kind),2158 .cty = try dg.typeToCType(ty, kind),
2107 .val = val,2159 .val = val,
...@@ -2133,7 +2185,7 @@ const RenderCTypeTrailing = enum {...@@ -2133,7 +2185,7 @@ const RenderCTypeTrailing = enum {
2133 }2185 }
2134};2186};
2135fn renderTypeName(2187fn renderTypeName(
2136 mod: *Module,2188 zcu: *Zcu,
2137 w: anytype,2189 w: anytype,
2138 idx: CType.Index,2190 idx: CType.Index,
2139 cty: CType,2191 cty: CType,
...@@ -2157,7 +2209,7 @@ fn renderTypeName(...@@ -2157,7 +2209,7 @@ fn renderTypeName(
2157 try w.print("{s} {s}{}__{d}", .{2209 try w.print("{s} {s}{}__{d}", .{
2158 @tagName(tag)["fwd_".len..],2210 @tagName(tag)["fwd_".len..],
2159 attributes,2211 attributes,
2160 fmtIdent(mod.intern_pool.stringToSlice(mod.declPtr(owner_decl).name)),2212 fmtIdent(zcu.intern_pool.stringToSlice(zcu.declPtr(owner_decl).name)),
2161 @intFromEnum(owner_decl),2213 @intFromEnum(owner_decl),
2162 });2214 });
2163 },2215 },
...@@ -2166,7 +2218,7 @@ fn renderTypeName(...@@ -2166,7 +2218,7 @@ fn renderTypeName(
2166fn renderTypePrefix(2218fn renderTypePrefix(
2167 pass: DeclGen.Pass,2219 pass: DeclGen.Pass,
2168 store: CType.Store.Set,2220 store: CType.Store.Set,
2169 mod: *Module,2221 zcu: *Zcu,
2170 w: anytype,2222 w: anytype,
2171 idx: CType.Index,2223 idx: CType.Index,
2172 parent_fix: CTypeFix,2224 parent_fix: CTypeFix,
...@@ -2224,7 +2276,7 @@ fn renderTypePrefix(...@@ -2224,7 +2276,7 @@ fn renderTypePrefix(
2224 const child_trailing = try renderTypePrefix(2276 const child_trailing = try renderTypePrefix(
2225 pass,2277 pass,
2226 store,2278 store,
2227 mod,2279 zcu,
2228 w,2280 w,
2229 child_idx,2281 child_idx,
2230 .prefix,2282 .prefix,
...@@ -2247,7 +2299,7 @@ fn renderTypePrefix(...@@ -2247,7 +2299,7 @@ fn renderTypePrefix(
2247 => {2299 => {
2248 const child_idx = cty.cast(CType.Payload.Sequence).?.data.elem_type;2300 const child_idx = cty.cast(CType.Payload.Sequence).?.data.elem_type;
2249 const child_trailing =2301 const child_trailing =
2250 try renderTypePrefix(pass, store, mod, w, child_idx, .suffix, qualifiers);2302 try renderTypePrefix(pass, store, zcu, w, child_idx, .suffix, qualifiers);
2251 switch (parent_fix) {2303 switch (parent_fix) {
2252 .prefix => {2304 .prefix => {
2253 try w.print("{}(", .{child_trailing});2305 try w.print("{}(", .{child_trailing});
...@@ -2262,12 +2314,12 @@ fn renderTypePrefix(...@@ -2262,12 +2314,12 @@ fn renderTypePrefix(
2262 => switch (pass) {2314 => switch (pass) {
2263 .decl => |decl_index| try w.print("decl__{d}_{d}", .{ @intFromEnum(decl_index), idx }),2315 .decl => |decl_index| try w.print("decl__{d}_{d}", .{ @intFromEnum(decl_index), idx }),
2264 .anon => |anon_decl| try w.print("anon__{d}_{d}", .{ @intFromEnum(anon_decl), idx }),2316 .anon => |anon_decl| try w.print("anon__{d}_{d}", .{ @intFromEnum(anon_decl), idx }),
2265 .flush => try renderTypeName(mod, w, idx, cty, ""),2317 .flush => try renderTypeName(zcu, w, idx, cty, ""),
2266 },2318 },
22672319
2268 .fwd_struct,2320 .fwd_struct,
2269 .fwd_union,2321 .fwd_union,
2270 => try renderTypeName(mod, w, idx, cty, ""),2322 => try renderTypeName(zcu, w, idx, cty, ""),
22712323
2272 .unnamed_struct,2324 .unnamed_struct,
2273 .unnamed_union,2325 .unnamed_union,
...@@ -2278,7 +2330,7 @@ fn renderTypePrefix(...@@ -2278,7 +2330,7 @@ fn renderTypePrefix(
2278 @tagName(tag)["unnamed_".len..],2330 @tagName(tag)["unnamed_".len..],
2279 if (cty.isPacked()) "zig_packed(" else "",2331 if (cty.isPacked()) "zig_packed(" else "",
2280 });2332 });
2281 try renderAggregateFields(mod, w, store, cty, 1);2333 try renderAggregateFields(zcu, w, store, cty, 1);
2282 if (cty.isPacked()) try w.writeByte(')');2334 if (cty.isPacked()) try w.writeByte(')');
2283 },2335 },
22842336
...@@ -2291,7 +2343,7 @@ fn renderTypePrefix(...@@ -2291,7 +2343,7 @@ fn renderTypePrefix(
2291 => return renderTypePrefix(2343 => return renderTypePrefix(
2292 pass,2344 pass,
2293 store,2345 store,
2294 mod,2346 zcu,
2295 w,2347 w,
2296 cty.cast(CType.Payload.Aggregate).?.data.fwd_decl,2348 cty.cast(CType.Payload.Aggregate).?.data.fwd_decl,
2297 parent_fix,2349 parent_fix,
...@@ -2304,7 +2356,7 @@ fn renderTypePrefix(...@@ -2304,7 +2356,7 @@ fn renderTypePrefix(
2304 const child_trailing = try renderTypePrefix(2356 const child_trailing = try renderTypePrefix(
2305 pass,2357 pass,
2306 store,2358 store,
2307 mod,2359 zcu,
2308 w,2360 w,
2309 cty.cast(CType.Payload.Function).?.data.return_type,2361 cty.cast(CType.Payload.Function).?.data.return_type,
2310 .suffix,2362 .suffix,
...@@ -2331,7 +2383,7 @@ fn renderTypePrefix(...@@ -2331,7 +2383,7 @@ fn renderTypePrefix(
2331fn renderTypeSuffix(2383fn renderTypeSuffix(
2332 pass: DeclGen.Pass,2384 pass: DeclGen.Pass,
2333 store: CType.Store.Set,2385 store: CType.Store.Set,
2334 mod: *Module,2386 zcu: *Zcu,
2335 w: anytype,2387 w: anytype,
2336 idx: CType.Index,2388 idx: CType.Index,
2337 parent_fix: CTypeFix,2389 parent_fix: CTypeFix,
...@@ -2385,7 +2437,7 @@ fn renderTypeSuffix(...@@ -2385,7 +2437,7 @@ fn renderTypeSuffix(
2385 => try renderTypeSuffix(2437 => try renderTypeSuffix(
2386 pass,2438 pass,
2387 store,2439 store,
2388 mod,2440 zcu,
2389 w,2441 w,
2390 cty.cast(CType.Payload.Child).?.data,2442 cty.cast(CType.Payload.Child).?.data,
2391 .prefix,2443 .prefix,
...@@ -2404,7 +2456,7 @@ fn renderTypeSuffix(...@@ -2404,7 +2456,7 @@ fn renderTypeSuffix(
2404 try renderTypeSuffix(2456 try renderTypeSuffix(
2405 pass,2457 pass,
2406 store,2458 store,
2407 mod,2459 zcu,
2408 w,2460 w,
2409 cty.cast(CType.Payload.Sequence).?.data.elem_type,2461 cty.cast(CType.Payload.Sequence).?.data.elem_type,
2410 .suffix,2462 .suffix,
...@@ -2444,9 +2496,9 @@ fn renderTypeSuffix(...@@ -2444,9 +2496,9 @@ fn renderTypeSuffix(
2444 if (need_comma) try w.writeAll(", ");2496 if (need_comma) try w.writeAll(", ");
2445 need_comma = true;2497 need_comma = true;
2446 const trailing =2498 const trailing =
2447 try renderTypePrefix(pass, store, mod, w, param_type, .suffix, qualifiers);2499 try renderTypePrefix(pass, store, zcu, w, param_type, .suffix, qualifiers);
2448 if (qualifiers.contains(.@"const")) try w.print("{}a{d}", .{ trailing, param_i });2500 if (qualifiers.contains(.@"const")) try w.print("{}a{d}", .{ trailing, param_i });
2449 try renderTypeSuffix(pass, store, mod, w, param_type, .suffix, .{});2501 try renderTypeSuffix(pass, store, zcu, w, param_type, .suffix, .{});
2450 }2502 }
2451 switch (tag) {2503 switch (tag) {
2452 .function => {},2504 .function => {},
...@@ -2460,12 +2512,12 @@ fn renderTypeSuffix(...@@ -2460,12 +2512,12 @@ fn renderTypeSuffix(
2460 if (!need_comma) try w.writeAll("void");2512 if (!need_comma) try w.writeAll("void");
2461 try w.writeByte(')');2513 try w.writeByte(')');
24622514
2463 try renderTypeSuffix(pass, store, mod, w, data.return_type, .suffix, .{});2515 try renderTypeSuffix(pass, store, zcu, w, data.return_type, .suffix, .{});
2464 },2516 },
2465 }2517 }
2466}2518}
2467fn renderAggregateFields(2519fn renderAggregateFields(
2468 mod: *Module,2520 zcu: *Zcu,
2469 writer: anytype,2521 writer: anytype,
2470 store: CType.Store.Set,2522 store: CType.Store.Set,
2471 cty: CType,2523 cty: CType,
...@@ -2480,9 +2532,9 @@ fn renderAggregateFields(...@@ -2480,9 +2532,9 @@ fn renderAggregateFields(
2480 .eq => {},2532 .eq => {},
2481 .gt => try writer.print("zig_align({}) ", .{field.alignas.toByteUnits()}),2533 .gt => try writer.print("zig_align({}) ", .{field.alignas.toByteUnits()}),
2482 }2534 }
2483 const trailing = try renderTypePrefix(.flush, store, mod, writer, field.type, .suffix, .{});2535 const trailing = try renderTypePrefix(.flush, store, zcu, writer, field.type, .suffix, .{});
2484 try writer.print("{}{ }", .{ trailing, fmtIdent(mem.span(field.name)) });2536 try writer.print("{}{ }", .{ trailing, fmtIdent(mem.span(field.name)) });
2485 try renderTypeSuffix(.flush, store, mod, writer, field.type, .suffix, .{});2537 try renderTypeSuffix(.flush, store, zcu, writer, field.type, .suffix, .{});
2486 try writer.writeAll(";\n");2538 try writer.writeAll(";\n");
2487 }2539 }
2488 try writer.writeByteNTimes(' ', indent);2540 try writer.writeByteNTimes(' ', indent);
...@@ -2490,7 +2542,7 @@ fn renderAggregateFields(...@@ -2490,7 +2542,7 @@ fn renderAggregateFields(
2490}2542}
24912543
2492pub fn genTypeDecl(2544pub fn genTypeDecl(
2493 mod: *Module,2545 zcu: *Zcu,
2494 writer: anytype,2546 writer: anytype,
2495 global_store: CType.Store.Set,2547 global_store: CType.Store.Set,
2496 global_idx: CType.Index,2548 global_idx: CType.Index,
...@@ -2503,9 +2555,9 @@ pub fn genTypeDecl(...@@ -2503,9 +2555,9 @@ pub fn genTypeDecl(
2503 switch (global_cty.tag()) {2555 switch (global_cty.tag()) {
2504 .fwd_anon_struct => if (pass != .flush) {2556 .fwd_anon_struct => if (pass != .flush) {
2505 try writer.writeAll("typedef ");2557 try writer.writeAll("typedef ");
2506 _ = try renderTypePrefix(.flush, global_store, mod, writer, global_idx, .suffix, .{});2558 _ = try renderTypePrefix(.flush, global_store, zcu, writer, global_idx, .suffix, .{});
2507 try writer.writeByte(' ');2559 try writer.writeByte(' ');
2508 _ = try renderTypePrefix(pass, decl_store, mod, writer, decl_idx, .suffix, .{});2560 _ = try renderTypePrefix(pass, decl_store, zcu, writer, decl_idx, .suffix, .{});
2509 try writer.writeAll(";\n");2561 try writer.writeAll(";\n");
2510 },2562 },
25112563
...@@ -2526,14 +2578,14 @@ pub fn genTypeDecl(...@@ -2526,14 +2578,14 @@ pub fn genTypeDecl(
2526 _ = try renderTypePrefix(2578 _ = try renderTypePrefix(
2527 .flush,2579 .flush,
2528 global_store,2580 global_store,
2529 mod,2581 zcu,
2530 writer,2582 writer,
2531 global_idx,2583 global_idx,
2532 .suffix,2584 .suffix,
2533 .{},2585 .{},
2534 );2586 );
2535 try writer.writeAll("; /* ");2587 try writer.writeAll("; /* ");
2536 try mod.declPtr(owner_decl).renderFullyQualifiedName(mod, writer);2588 try zcu.declPtr(owner_decl).renderFullyQualifiedName(zcu, writer);
2537 try writer.writeAll(" */\n");2589 try writer.writeAll(" */\n");
2538 },2590 },
25392591
...@@ -2546,14 +2598,14 @@ pub fn genTypeDecl(...@@ -2546,14 +2598,14 @@ pub fn genTypeDecl(
2546 => {2598 => {
2547 const fwd_idx = global_cty.cast(CType.Payload.Aggregate).?.data.fwd_decl;2599 const fwd_idx = global_cty.cast(CType.Payload.Aggregate).?.data.fwd_decl;
2548 try renderTypeName(2600 try renderTypeName(
2549 mod,2601 zcu,
2550 writer,2602 writer,
2551 fwd_idx,2603 fwd_idx,
2552 global_store.indexToCType(fwd_idx),2604 global_store.indexToCType(fwd_idx),
2553 if (global_cty.isPacked()) "zig_packed(" else "",2605 if (global_cty.isPacked()) "zig_packed(" else "",
2554 );2606 );
2555 try writer.writeByte(' ');2607 try writer.writeByte(' ');
2556 try renderAggregateFields(mod, writer, global_store, global_cty, 0);2608 try renderAggregateFields(zcu, writer, global_store, global_cty, 0);
2557 if (global_cty.isPacked()) try writer.writeByte(')');2609 if (global_cty.isPacked()) try writer.writeByte(')');
2558 try writer.writeAll(";\n");2610 try writer.writeAll(";\n");
2559 },2611 },
...@@ -2566,30 +2618,30 @@ pub fn genTypeDecl(...@@ -2566,30 +2618,30 @@ pub fn genTypeDecl(
2566 }2618 }
2567}2619}
25682620
2569pub fn genGlobalAsm(mod: *Module, writer: anytype) !void {2621pub fn genGlobalAsm(zcu: *Zcu, writer: anytype) !void {
2570 for (mod.global_assembly.values()) |asm_source| {2622 for (zcu.global_assembly.values()) |asm_source| {
2571 try writer.print("__asm({s});\n", .{fmtStringLiteral(asm_source, null)});2623 try writer.print("__asm({s});\n", .{fmtStringLiteral(asm_source, null)});
2572 }2624 }
2573}2625}
25742626
2575pub fn genErrDecls(o: *Object) !void {2627pub fn genErrDecls(o: *Object) !void {
2576 const mod = o.dg.module;2628 const zcu = o.dg.zcu;
2577 const ip = &mod.intern_pool;2629 const ip = &zcu.intern_pool;
2578 const writer = o.writer();2630 const writer = o.writer();
25792631
2580 var max_name_len: usize = 0;2632 var max_name_len: usize = 0;
2581 // do not generate an invalid empty enum when the global error set is empty2633 // do not generate an invalid empty enum when the global error set is empty
2582 if (mod.global_error_set.keys().len > 1) {2634 if (zcu.global_error_set.keys().len > 1) {
2583 try writer.writeAll("enum {\n");2635 try writer.writeAll("enum {\n");
2584 o.indent_writer.pushIndent();2636 o.indent_writer.pushIndent();
2585 for (mod.global_error_set.keys()[1..], 1..) |name_nts, value| {2637 for (zcu.global_error_set.keys()[1..], 1..) |name_nts, value| {
2586 const name = ip.stringToSlice(name_nts);2638 const name = ip.stringToSlice(name_nts);
2587 max_name_len = @max(name.len, max_name_len);2639 max_name_len = @max(name.len, max_name_len);
2588 const err_val = try mod.intern(.{ .err = .{2640 const err_val = try zcu.intern(.{ .err = .{
2589 .ty = .anyerror_type,2641 .ty = .anyerror_type,
2590 .name = name_nts,2642 .name = name_nts,
2591 } });2643 } });
2592 try o.dg.renderValue(writer, Type.anyerror, Value.fromInterned(err_val), .Other);2644 try o.dg.renderValue(writer, Value.fromInterned(err_val), .Other);
2593 try writer.print(" = {d}u,\n", .{value});2645 try writer.print(" = {d}u,\n", .{value});
2594 }2646 }
2595 o.indent_writer.popIndent();2647 o.indent_writer.popIndent();
...@@ -2601,44 +2653,56 @@ pub fn genErrDecls(o: *Object) !void {...@@ -2601,44 +2653,56 @@ pub fn genErrDecls(o: *Object) !void {
2601 defer o.dg.gpa.free(name_buf);2653 defer o.dg.gpa.free(name_buf);
26022654
2603 @memcpy(name_buf[0..name_prefix.len], name_prefix);2655 @memcpy(name_buf[0..name_prefix.len], name_prefix);
2604 for (mod.global_error_set.keys()) |name_ip| {2656 for (zcu.global_error_set.keys()) |name_ip| {
2605 const name = ip.stringToSlice(name_ip);2657 const name = ip.stringToSlice(name_ip);
2606 @memcpy(name_buf[name_prefix.len..][0..name.len], name);2658 @memcpy(name_buf[name_prefix.len..][0..name.len], name);
2607 const identifier = name_buf[0 .. name_prefix.len + name.len];2659 const identifier = name_buf[0 .. name_prefix.len + name.len];
26082660
2609 const name_ty = try mod.arrayType(.{2661 const name_ty = try zcu.arrayType(.{
2610 .len = name.len,2662 .len = name.len,
2611 .child = .u8_type,2663 .child = .u8_type,
2612 .sentinel = .zero_u8,2664 .sentinel = .zero_u8,
2613 });2665 });
2614 const name_val = try mod.intern(.{ .aggregate = .{2666 const name_val = try zcu.intern(.{ .aggregate = .{
2615 .ty = name_ty.toIntern(),2667 .ty = name_ty.toIntern(),
2616 .storage = .{ .bytes = name },2668 .storage = .{ .bytes = name },
2617 } });2669 } });
26182670
2619 try writer.writeAll("static ");2671 try writer.writeAll("static ");
2620 try o.dg.renderTypeAndName(writer, name_ty, .{ .identifier = identifier }, Const, .none, .complete);2672 try o.dg.renderTypeAndName(
2673 writer,
2674 name_ty,
2675 .{ .identifier = identifier },
2676 Const,
2677 .none,
2678 .complete,
2679 );
2621 try writer.writeAll(" = ");2680 try writer.writeAll(" = ");
2622 try o.dg.renderValue(writer, name_ty, Value.fromInterned(name_val), .StaticInitializer);2681 try o.dg.renderValue(writer, Value.fromInterned(name_val), .StaticInitializer);
2623 try writer.writeAll(";\n");2682 try writer.writeAll(";\n");
2624 }2683 }
26252684
2626 const name_array_ty = try mod.arrayType(.{2685 const name_array_ty = try zcu.arrayType(.{
2627 .len = mod.global_error_set.count(),2686 .len = zcu.global_error_set.count(),
2628 .child = .slice_const_u8_sentinel_0_type,2687 .child = .slice_const_u8_sentinel_0_type,
2629 });2688 });
26302689
2631 try writer.writeAll("static ");2690 try writer.writeAll("static ");
2632 try o.dg.renderTypeAndName(writer, name_array_ty, .{ .identifier = array_identifier }, Const, .none, .complete);2691 try o.dg.renderTypeAndName(
2692 writer,
2693 name_array_ty,
2694 .{ .identifier = array_identifier },
2695 Const,
2696 .none,
2697 .complete,
2698 );
2633 try writer.writeAll(" = {");2699 try writer.writeAll(" = {");
2634 for (mod.global_error_set.keys(), 0..) |name_nts, value| {2700 for (zcu.global_error_set.keys(), 0..) |name_nts, value| {
2635 const name = ip.stringToSlice(name_nts);2701 const name = ip.stringToSlice(name_nts);
2636 if (value != 0) try writer.writeByte(',');2702 if (value != 0) try writer.writeByte(',');
2637
2638 const len_val = try mod.intValue(Type.usize, name.len);
2639
2640 try writer.print("{{" ++ name_prefix ++ "{}, {}}}", .{2703 try writer.print("{{" ++ name_prefix ++ "{}, {}}}", .{
2641 fmtIdent(name), try o.dg.fmtIntLiteral(Type.usize, len_val, .StaticInitializer),2704 fmtIdent(name),
2705 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, name.len), .StaticInitializer),
2642 });2706 });
2643 }2707 }
2644 try writer.writeAll("};\n");2708 try writer.writeAll("};\n");
...@@ -2648,16 +2712,16 @@ fn genExports(o: *Object) !void {...@@ -2648,16 +2712,16 @@ fn genExports(o: *Object) !void {
2648 const tracy = trace(@src());2712 const tracy = trace(@src());
2649 defer tracy.end();2713 defer tracy.end();
26502714
2651 const mod = o.dg.module;2715 const zcu = o.dg.zcu;
2652 const ip = &mod.intern_pool;2716 const ip = &zcu.intern_pool;
2653 const decl_index = switch (o.dg.pass) {2717 const decl_index = switch (o.dg.pass) {
2654 .decl => |decl| decl,2718 .decl => |decl| decl,
2655 .anon, .flush => return,2719 .anon, .flush => return,
2656 };2720 };
2657 const decl = mod.declPtr(decl_index);2721 const decl = zcu.declPtr(decl_index);
2658 const fwd = o.dg.fwdDeclWriter();2722 const fwd = o.dg.fwdDeclWriter();
26592723
2660 const exports = mod.decl_exports.get(decl_index) orelse return;2724 const exports = zcu.decl_exports.get(decl_index) orelse return;
2661 if (exports.items.len < 2) return;2725 if (exports.items.len < 2) return;
26622726
2663 const is_variable_const = switch (ip.indexToKey(decl.val.toIntern())) {2727 const is_variable_const = switch (ip.indexToKey(decl.val.toIntern())) {
...@@ -2685,7 +2749,7 @@ fn genExports(o: *Object) !void {...@@ -2685,7 +2749,7 @@ fn genExports(o: *Object) !void {
2685 const export_name = ip.stringToSlice(@"export".opts.name);2749 const export_name = ip.stringToSlice(@"export".opts.name);
2686 try o.dg.renderTypeAndName(2750 try o.dg.renderTypeAndName(
2687 fwd,2751 fwd,
2688 decl.typeOf(mod),2752 decl.typeOf(zcu),
2689 .{ .identifier = export_name },2753 .{ .identifier = export_name },
2690 CQualifiers.init(.{ .@"const" = is_variable_const }),2754 CQualifiers.init(.{ .@"const" = is_variable_const }),
2691 decl.alignment,2755 decl.alignment,
...@@ -2708,8 +2772,8 @@ fn genExports(o: *Object) !void {...@@ -2708,8 +2772,8 @@ fn genExports(o: *Object) !void {
2708}2772}
27092773
2710pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {2774pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {
2711 const mod = o.dg.module;2775 const zcu = o.dg.zcu;
2712 const ip = &mod.intern_pool;2776 const ip = &zcu.intern_pool;
2713 const w = o.writer();2777 const w = o.writer();
2714 const key = lazy_fn.key_ptr.*;2778 const key = lazy_fn.key_ptr.*;
2715 const val = lazy_fn.value_ptr;2779 const val = lazy_fn.value_ptr;
...@@ -2727,47 +2791,45 @@ pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {...@@ -2727,47 +2791,45 @@ pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {
2727 try w.writeByte('(');2791 try w.writeByte('(');
2728 try o.dg.renderTypeAndName(w, enum_ty, .{ .identifier = "tag" }, Const, .none, .complete);2792 try o.dg.renderTypeAndName(w, enum_ty, .{ .identifier = "tag" }, Const, .none, .complete);
2729 try w.writeAll(") {\n switch (tag) {\n");2793 try w.writeAll(") {\n switch (tag) {\n");
2730 const tag_names = enum_ty.enumFields(mod);2794 const tag_names = enum_ty.enumFields(zcu);
2731 for (0..tag_names.len) |tag_index| {2795 for (0..tag_names.len) |tag_index| {
2732 const tag_name = ip.stringToSlice(tag_names.get(ip)[tag_index]);2796 const tag_name = ip.stringToSlice(tag_names.get(ip)[tag_index]);
2733 const tag_val = try mod.enumValueFieldIndex(enum_ty, @intCast(tag_index));2797 const tag_val = try zcu.enumValueFieldIndex(enum_ty, @intCast(tag_index));
27342798
2735 const int_val = try tag_val.intFromEnum(enum_ty, mod);2799 const name_ty = try zcu.arrayType(.{
2736
2737 const name_ty = try mod.arrayType(.{
2738 .len = tag_name.len,2800 .len = tag_name.len,
2739 .child = .u8_type,2801 .child = .u8_type,
2740 .sentinel = .zero_u8,2802 .sentinel = .zero_u8,
2741 });2803 });
2742 const name_val = try mod.intern(.{ .aggregate = .{2804 const name_val = try zcu.intern(.{ .aggregate = .{
2743 .ty = name_ty.toIntern(),2805 .ty = name_ty.toIntern(),
2744 .storage = .{ .bytes = tag_name },2806 .storage = .{ .bytes = tag_name },
2745 } });2807 } });
2746 const len_val = try mod.intValue(Type.usize, tag_name.len);
27472808
2748 try w.print(" case {}: {{\n static ", .{2809 try w.print(" case {}: {{\n static ", .{
2749 try o.dg.fmtIntLiteral(enum_ty, int_val, .Other),2810 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, zcu), .Other),
2750 });2811 });
2751 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);2812 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);
2752 try w.writeAll(" = ");2813 try w.writeAll(" = ");
2753 try o.dg.renderValue(w, name_ty, Value.fromInterned(name_val), .Initializer);2814 try o.dg.renderValue(w, Value.fromInterned(name_val), .Initializer);
2754 try w.writeAll(";\n return (");2815 try w.writeAll(";\n return (");
2755 try o.dg.renderType(w, name_slice_ty);2816 try o.dg.renderType(w, name_slice_ty);
2756 try w.print("){{{}, {}}};\n", .{2817 try w.print("){{{}, {}}};\n", .{
2757 fmtIdent("name"), try o.dg.fmtIntLiteral(Type.usize, len_val, .Other),2818 fmtIdent("name"),
2819 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, tag_name.len), .Other),
2758 });2820 });
27592821
2760 try w.writeAll(" }\n");2822 try w.writeAll(" }\n");
2761 }2823 }
2762 try w.writeAll(" }\n while (");2824 try w.writeAll(" }\n while (");
2763 try o.dg.renderValue(w, Type.bool, Value.true, .Other);2825 try o.dg.renderValue(w, Value.true, .Other);
2764 try w.writeAll(") ");2826 try w.writeAll(") ");
2765 _ = try airBreakpoint(w);2827 _ = try airBreakpoint(w);
2766 try w.writeAll("}\n");2828 try w.writeAll("}\n");
2767 },2829 },
2768 .never_tail, .never_inline => |fn_decl_index| {2830 .never_tail, .never_inline => |fn_decl_index| {
2769 const fn_decl = mod.declPtr(fn_decl_index);2831 const fn_decl = zcu.declPtr(fn_decl_index);
2770 const fn_cty = try o.dg.typeToCType(fn_decl.typeOf(mod), .complete);2832 const fn_cty = try o.dg.typeToCType(fn_decl.typeOf(zcu), .complete);
2771 const fn_info = fn_cty.cast(CType.Payload.Function).?.data;2833 const fn_info = fn_cty.cast(CType.Payload.Function).?.data;
27722834
2773 const fwd_decl_writer = o.dg.fwdDeclWriter();2835 const fwd_decl_writer = o.dg.fwdDeclWriter();
...@@ -2799,10 +2861,10 @@ pub fn genFunc(f: *Function) !void {...@@ -2799,10 +2861,10 @@ pub fn genFunc(f: *Function) !void {
2799 defer tracy.end();2861 defer tracy.end();
28002862
2801 const o = &f.object;2863 const o = &f.object;
2802 const mod = o.dg.module;2864 const zcu = o.dg.zcu;
2803 const gpa = o.dg.gpa;2865 const gpa = o.dg.gpa;
2804 const decl_index = o.dg.pass.decl;2866 const decl_index = o.dg.pass.decl;
2805 const decl = mod.declPtr(decl_index);2867 const decl = zcu.declPtr(decl_index);
28062868
2807 o.code_header = std.ArrayList(u8).init(gpa);2869 o.code_header = std.ArrayList(u8).init(gpa);
2808 defer o.code_header.deinit();2870 defer o.code_header.deinit();
...@@ -2811,7 +2873,7 @@ pub fn genFunc(f: *Function) !void {...@@ -2811,7 +2873,7 @@ pub fn genFunc(f: *Function) !void {
2811 const fwd_decl_writer = o.dg.fwdDeclWriter();2873 const fwd_decl_writer = o.dg.fwdDeclWriter();
2812 try fwd_decl_writer.writeAll(if (is_global) "zig_extern " else "static ");2874 try fwd_decl_writer.writeAll(if (is_global) "zig_extern " else "static ");
28132875
2814 if (mod.decl_exports.get(decl_index)) |exports|2876 if (zcu.decl_exports.get(decl_index)) |exports|
2815 if (exports.items[0].opts.linkage == .weak) try fwd_decl_writer.writeAll("zig_weak_linkage_fn ");2877 if (exports.items[0].opts.linkage == .weak) try fwd_decl_writer.writeAll("zig_weak_linkage_fn ");
2816 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });2878 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });
2817 try fwd_decl_writer.writeAll(";\n");2879 try fwd_decl_writer.writeAll(";\n");
...@@ -2819,6 +2881,8 @@ pub fn genFunc(f: *Function) !void {...@@ -2819,6 +2881,8 @@ pub fn genFunc(f: *Function) !void {
28192881
2820 try o.indent_writer.insertNewline();2882 try o.indent_writer.insertNewline();
2821 if (!is_global) try o.writer().writeAll("static ");2883 if (!is_global) try o.writer().writeAll("static ");
2884 if (zcu.intern_pool.stringToSliceUnwrap(decl.@"linksection")) |s|
2885 try o.writer().print("zig_linksection_fn({s}) ", .{fmtStringLiteral(s, null)});
2822 try o.dg.renderFunctionSignature(o.writer(), decl_index, .complete, .{ .export_index = 0 });2886 try o.dg.renderFunctionSignature(o.writer(), decl_index, .complete, .{ .export_index = 0 });
2823 try o.writer().writeByte(' ');2887 try o.writer().writeByte(' ');
28242888
...@@ -2867,7 +2931,7 @@ pub fn genFunc(f: *Function) !void {...@@ -2867,7 +2931,7 @@ pub fn genFunc(f: *Function) !void {
2867 for (free_locals.values()) |list| {2931 for (free_locals.values()) |list| {
2868 for (list.keys()) |local_index| {2932 for (list.keys()) |local_index| {
2869 const local = f.locals.items[local_index];2933 const local = f.locals.items[local_index];
2870 try o.dg.renderCTypeAndName(w, local.cty_idx, .{ .local = local_index }, .{}, local.alignas);2934 try o.dg.renderCTypeAndName(w, local.cty_idx, .{ .local = local_index }, .{}, local.flags.alignas);
2871 try w.writeAll(";\n ");2935 try w.writeAll(";\n ");
2872 }2936 }
2873 }2937 }
...@@ -2884,43 +2948,41 @@ pub fn genDecl(o: *Object) !void {...@@ -2884,43 +2948,41 @@ pub fn genDecl(o: *Object) !void {
2884 const tracy = trace(@src());2948 const tracy = trace(@src());
2885 defer tracy.end();2949 defer tracy.end();
28862950
2887 const mod = o.dg.module;2951 const zcu = o.dg.zcu;
2888 const decl_index = o.dg.pass.decl;2952 const decl_index = o.dg.pass.decl;
2889 const decl = mod.declPtr(decl_index);2953 const decl = zcu.declPtr(decl_index);
2890 const decl_val = decl.val;2954 const decl_ty = decl.typeOf(zcu);
2891 const decl_ty = decl_val.typeOf(mod);
28922955
2893 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return;2956 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return;
2894 if (decl_val.getExternFunc(mod)) |_| {2957 if (decl.val.getExternFunc(zcu)) |_| {
2895 const fwd_decl_writer = o.dg.fwdDeclWriter();2958 const fwd_decl_writer = o.dg.fwdDeclWriter();
2896 try fwd_decl_writer.writeAll("zig_extern ");2959 try fwd_decl_writer.writeAll("zig_extern ");
2897 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });2960 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });
2898 try fwd_decl_writer.writeAll(";\n");2961 try fwd_decl_writer.writeAll(";\n");
2899 try genExports(o);2962 try genExports(o);
2900 } else if (decl_val.getVariable(mod)) |variable| {2963 } else if (decl.val.getVariable(zcu)) |variable| {
2901 try o.dg.renderFwdDecl(decl_index, variable, .final);2964 try o.dg.renderFwdDecl(decl_index, variable, .final);
2902 try genExports(o);2965 try genExports(o);
29032966
2904 if (variable.is_extern) return;2967 if (variable.is_extern) return;
29052968
2906 const is_global = variable.is_extern or o.dg.declIsGlobal(decl_val);2969 const is_global = variable.is_extern or o.dg.declIsGlobal(decl.val);
2907 const w = o.writer();2970 const w = o.writer();
2908 if (!is_global) try w.writeAll("static ");2971 if (!is_global) try w.writeAll("static ");
2909 if (variable.is_weak_linkage) try w.writeAll("zig_weak_linkage ");2972 if (variable.is_weak_linkage) try w.writeAll("zig_weak_linkage ");
2910 if (variable.is_threadlocal) try w.writeAll("zig_threadlocal ");2973 if (variable.is_threadlocal) try w.writeAll("zig_threadlocal ");
2911 if (mod.intern_pool.stringToSliceUnwrap(decl.@"linksection")) |s|2974 if (zcu.intern_pool.stringToSliceUnwrap(decl.@"linksection")) |s|
2912 try w.print("zig_linksection(\"{s}\", ", .{s});2975 try w.print("zig_linksection({s}) ", .{fmtStringLiteral(s, null)});
2913 const decl_c_value = .{ .decl = decl_index };2976 const decl_c_value = .{ .decl = decl_index };
2914 try o.dg.renderTypeAndName(w, decl_ty, decl_c_value, .{}, decl.alignment, .complete);2977 try o.dg.renderTypeAndName(w, decl_ty, decl_c_value, .{}, decl.alignment, .complete);
2915 if (decl.@"linksection" != .none) try w.writeAll(", read, write)");
2916 try w.writeAll(" = ");2978 try w.writeAll(" = ");
2917 try o.dg.renderValue(w, decl_ty, Value.fromInterned(variable.init), .StaticInitializer);2979 try o.dg.renderValue(w, Value.fromInterned(variable.init), .StaticInitializer);
2918 try w.writeByte(';');2980 try w.writeByte(';');
2919 try o.indent_writer.insertNewline();2981 try o.indent_writer.insertNewline();
2920 } else {2982 } else {
2921 const is_global = o.dg.module.decl_exports.contains(decl_index);2983 const is_global = o.dg.zcu.decl_exports.contains(decl_index);
2922 const decl_c_value = .{ .decl = decl_index };2984 const decl_c_value = .{ .decl = decl_index };
2923 try genDeclValue(o, decl_val, is_global, decl_c_value, decl.alignment, decl.@"linksection");2985 try genDeclValue(o, decl.val, is_global, decl_c_value, decl.alignment, decl.@"linksection");
2924 }2986 }
2925}2987}
29262988
...@@ -2930,19 +2992,19 @@ pub fn genDeclValue(...@@ -2930,19 +2992,19 @@ pub fn genDeclValue(
2930 is_global: bool,2992 is_global: bool,
2931 decl_c_value: CValue,2993 decl_c_value: CValue,
2932 alignment: Alignment,2994 alignment: Alignment,
2933 link_section: InternPool.OptionalNullTerminatedString,2995 @"linksection": InternPool.OptionalNullTerminatedString,
2934) !void {2996) !void {
2935 const mod = o.dg.module;2997 const zcu = o.dg.zcu;
2936 const fwd_decl_writer = o.dg.fwdDeclWriter();2998 const fwd_decl_writer = o.dg.fwdDeclWriter();
29372999
2938 const ty = val.typeOf(mod);3000 const ty = val.typeOf(zcu);
29393001
2940 try fwd_decl_writer.writeAll(if (is_global) "zig_extern " else "static ");3002 try fwd_decl_writer.writeAll(if (is_global) "zig_extern " else "static ");
2941 try o.dg.renderTypeAndName(fwd_decl_writer, ty, decl_c_value, Const, alignment, .complete);3003 try o.dg.renderTypeAndName(fwd_decl_writer, ty, decl_c_value, Const, alignment, .complete);
2942 switch (o.dg.pass) {3004 switch (o.dg.pass) {
2943 .decl => |decl_index| {3005 .decl => |decl_index| {
2944 if (mod.decl_exports.get(decl_index)) |exports| {3006 if (zcu.decl_exports.get(decl_index)) |exports| {
2945 const export_name = mod.intern_pool.stringToSlice(exports.items[0].opts.name);3007 const export_name = zcu.intern_pool.stringToSlice(exports.items[0].opts.name);
2946 if (isMangledIdent(export_name, true)) {3008 if (isMangledIdent(export_name, true)) {
2947 try fwd_decl_writer.print(" zig_mangled_final({ }, {s})", .{3009 try fwd_decl_writer.print(" zig_mangled_final({ }, {s})", .{
2948 fmtIdent(export_name), fmtStringLiteral(export_name, null),3010 fmtIdent(export_name), fmtStringLiteral(export_name, null),
...@@ -2958,13 +3020,11 @@ pub fn genDeclValue(...@@ -2958,13 +3020,11 @@ pub fn genDeclValue(
29583020
2959 const w = o.writer();3021 const w = o.writer();
2960 if (!is_global) try w.writeAll("static ");3022 if (!is_global) try w.writeAll("static ");
29613023 if (zcu.intern_pool.stringToSliceUnwrap(@"linksection")) |s|
2962 if (mod.intern_pool.stringToSliceUnwrap(link_section)) |s|3024 try w.print("zig_linksection({s}) ", .{fmtStringLiteral(s, null)});
2963 try w.print("zig_linksection(\"{s}\", ", .{s});
2964 try o.dg.renderTypeAndName(w, ty, decl_c_value, Const, alignment, .complete);3025 try o.dg.renderTypeAndName(w, ty, decl_c_value, Const, alignment, .complete);
2965 if (link_section != .none) try w.writeAll(", read)");
2966 try w.writeAll(" = ");3026 try w.writeAll(" = ");
2967 try o.dg.renderValue(w, ty, val, .StaticInitializer);3027 try o.dg.renderValue(w, val, .StaticInitializer);
2968 try w.writeAll(";\n");3028 try w.writeAll(";\n");
2969}3029}
29703030
...@@ -2972,12 +3032,12 @@ pub fn genHeader(dg: *DeclGen) error{ AnalysisFail, OutOfMemory }!void {...@@ -2972,12 +3032,12 @@ pub fn genHeader(dg: *DeclGen) error{ AnalysisFail, OutOfMemory }!void {
2972 const tracy = trace(@src());3032 const tracy = trace(@src());
2973 defer tracy.end();3033 defer tracy.end();
29743034
2975 const mod = dg.module;3035 const zcu = dg.zcu;
2976 const decl_index = dg.pass.decl;3036 const decl_index = dg.pass.decl;
2977 const decl = mod.declPtr(decl_index);3037 const decl = zcu.declPtr(decl_index);
2978 const writer = dg.fwdDeclWriter();3038 const writer = dg.fwdDeclWriter();
29793039
2980 switch (decl.val.typeOf(mod).zigTypeTag(mod)) {3040 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
2981 .Fn => if (dg.declIsGlobal(decl.val)) {3041 .Fn => if (dg.declIsGlobal(decl.val)) {
2982 try writer.writeAll("zig_extern ");3042 try writer.writeAll("zig_extern ");
2983 try dg.renderFunctionSignature(writer, dg.pass.decl, .complete, .{ .export_index = 0 });3043 try dg.renderFunctionSignature(writer, dg.pass.decl, .complete, .{ .export_index = 0 });
...@@ -3060,8 +3120,8 @@ fn genBodyResolveState(f: *Function, inst: Air.Inst.Index, leading_deaths: []con...@@ -3060,8 +3120,8 @@ fn genBodyResolveState(f: *Function, inst: Air.Inst.Index, leading_deaths: []con
3060}3120}
30613121
3062fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfMemory }!void {3122fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfMemory }!void {
3063 const mod = f.object.dg.module;3123 const zcu = f.object.dg.zcu;
3064 const ip = &mod.intern_pool;3124 const ip = &zcu.intern_pool;
3065 const air_tags = f.air.instructions.items(.tag);3125 const air_tags = f.air.instructions.items(.tag);
30663126
3067 for (body) |inst| {3127 for (body) |inst| {
...@@ -3096,10 +3156,10 @@ fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail,...@@ -3096,10 +3156,10 @@ fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail,
3096 .div_trunc, .div_exact => try airBinOp(f, inst, "/", "div_trunc", .none),3156 .div_trunc, .div_exact => try airBinOp(f, inst, "/", "div_trunc", .none),
3097 .rem => blk: {3157 .rem => blk: {
3098 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;3158 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3099 const lhs_scalar_ty = f.typeOf(bin_op.lhs).scalarType(mod);3159 const lhs_scalar_ty = f.typeOf(bin_op.lhs).scalarType(zcu);
3100 // For binary operations @TypeOf(lhs)==@TypeOf(rhs),3160 // For binary operations @TypeOf(lhs)==@TypeOf(rhs),
3101 // so we only check one.3161 // so we only check one.
3102 break :blk if (lhs_scalar_ty.isInt(mod))3162 break :blk if (lhs_scalar_ty.isInt(zcu))
3103 try airBinOp(f, inst, "%", "rem", .none)3163 try airBinOp(f, inst, "%", "rem", .none)
3104 else3164 else
3105 try airBinFloatOp(f, inst, "fmod");3165 try airBinFloatOp(f, inst, "fmod");
...@@ -3359,10 +3419,10 @@ fn airSliceField(f: *Function, inst: Air.Inst.Index, is_ptr: bool, field_name: [...@@ -3359,10 +3419,10 @@ fn airSliceField(f: *Function, inst: Air.Inst.Index, is_ptr: bool, field_name: [
3359}3419}
33603420
3361fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {3421fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3362 const mod = f.object.dg.module;3422 const zcu = f.object.dg.zcu;
3363 const inst_ty = f.typeOfIndex(inst);3423 const inst_ty = f.typeOfIndex(inst);
3364 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;3424 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3365 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {3425 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3366 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });3426 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
3367 return .none;3427 return .none;
3368 }3428 }
...@@ -3385,14 +3445,17 @@ fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3385,14 +3445,17 @@ fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3385}3445}
33863446
3387fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {3447fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3388 const mod = f.object.dg.module;3448 const zcu = f.object.dg.zcu;
3389 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;3449 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
3390 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;3450 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
33913451
3392 const inst_ty = f.typeOfIndex(inst);3452 const inst_ty = f.typeOfIndex(inst);
3393 const ptr_ty = f.typeOf(bin_op.lhs);3453 const ptr_ty = f.typeOf(bin_op.lhs);
3394 const elem_ty = ptr_ty.childType(mod);3454 const ptr_align = ptr_ty.ptrAlignment(zcu);
3395 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(mod);3455 const elem_ty = ptr_ty.elemType2(zcu);
3456 const elem_align = elem_ty.abiAlignment(zcu);
3457 const is_under_aligned = ptr_align.compareStrict(.lt, elem_align);
3458 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(zcu);
33963459
3397 const ptr = try f.resolveInst(bin_op.lhs);3460 const ptr = try f.resolveInst(bin_op.lhs);
3398 const index = try f.resolveInst(bin_op.rhs);3461 const index = try f.resolveInst(bin_op.rhs);
...@@ -3407,13 +3470,22 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3407,13 +3470,22 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3407 try f.renderType(writer, inst_ty);3470 try f.renderType(writer, inst_ty);
3408 try writer.writeByte(')');3471 try writer.writeByte(')');
3409 if (elem_has_bits) try writer.writeByte('&');3472 if (elem_has_bits) try writer.writeByte('&');
3410 if (elem_has_bits and ptr_ty.ptrSize(mod) == .One) {3473 if (elem_has_bits and ptr_ty.ptrSize(zcu) == .One and !is_under_aligned) {
3411 // It's a pointer to an array, so we need to de-reference.3474 // It's a pointer to an array, so we need to de-reference.
3412 try f.writeCValueDeref(writer, ptr);3475 try f.writeCValueDeref(writer, ptr);
3413 } else try f.writeCValue(writer, ptr, .Other);3476 } else try f.writeCValue(writer, ptr, .Other);
3414 if (elem_has_bits) {3477 if (elem_has_bits) {
3415 try writer.writeByte('[');3478 try writer.writeByte('[');
3416 try f.writeCValue(writer, index, .Other);3479 try f.writeCValue(writer, index, .Other);
3480 if (is_under_aligned) {
3481 const factor = @divExact(elem_align.toByteUnitsOptional().?, @min(
3482 ptr_align.toByteUnitsOptional().?,
3483 f.object.dg.mod.resolved_target.result.maxIntAlignment(),
3484 ));
3485 try writer.print(" * {}", .{
3486 try f.fmtIntLiteral(try zcu.intValue(Type.usize, factor)),
3487 });
3488 }
3417 try writer.writeByte(']');3489 try writer.writeByte(']');
3418 }3490 }
3419 try a.end(f, writer);3491 try a.end(f, writer);
...@@ -3421,10 +3493,10 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3421,10 +3493,10 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3421}3493}
34223494
3423fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {3495fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3424 const mod = f.object.dg.module;3496 const zcu = f.object.dg.zcu;
3425 const inst_ty = f.typeOfIndex(inst);3497 const inst_ty = f.typeOfIndex(inst);
3426 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;3498 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3427 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {3499 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3428 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });3500 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
3429 return .none;3501 return .none;
3430 }3502 }
...@@ -3447,14 +3519,14 @@ fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3447,14 +3519,14 @@ fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3447}3519}
34483520
3449fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {3521fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3450 const mod = f.object.dg.module;3522 const zcu = f.object.dg.zcu;
3451 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;3523 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
3452 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;3524 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34533525
3454 const inst_ty = f.typeOfIndex(inst);3526 const inst_ty = f.typeOfIndex(inst);
3455 const slice_ty = f.typeOf(bin_op.lhs);3527 const slice_ty = f.typeOf(bin_op.lhs);
3456 const elem_ty = slice_ty.elemType2(mod);3528 const elem_ty = slice_ty.elemType2(zcu);
3457 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(mod);3529 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(zcu);
34583530
3459 const slice = try f.resolveInst(bin_op.lhs);3531 const slice = try f.resolveInst(bin_op.lhs);
3460 const index = try f.resolveInst(bin_op.rhs);3532 const index = try f.resolveInst(bin_op.rhs);
...@@ -3477,10 +3549,10 @@ fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3477,10 +3549,10 @@ fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3477}3549}
34783550
3479fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {3551fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3480 const mod = f.object.dg.module;3552 const zcu = f.object.dg.zcu;
3481 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;3553 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3482 const inst_ty = f.typeOfIndex(inst);3554 const inst_ty = f.typeOfIndex(inst);
3483 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {3555 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3484 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });3556 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
3485 return .none;3557 return .none;
3486 }3558 }
...@@ -3503,33 +3575,33 @@ fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3503,33 +3575,33 @@ fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3503}3575}
35043576
3505fn airAlloc(f: *Function, inst: Air.Inst.Index) !CValue {3577fn airAlloc(f: *Function, inst: Air.Inst.Index) !CValue {
3506 const mod = f.object.dg.module;3578 const zcu = f.object.dg.zcu;
3507 const inst_ty = f.typeOfIndex(inst);3579 const inst_ty = f.typeOfIndex(inst);
3508 const elem_type = inst_ty.childType(mod);3580 const elem_type = inst_ty.childType(zcu);
3509 if (!elem_type.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .{ .undef = inst_ty };3581 if (!elem_type.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
35103582
3511 const local = try f.allocLocalValue(3583 const local = try f.allocLocalValue(
3512 elem_type,3584 elem_type,
3513 inst_ty.ptrAlignment(mod),3585 inst_ty.ptrAlignment(zcu),
3514 );3586 );
3515 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });3587 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3516 const gpa = f.object.dg.module.gpa;3588 const gpa = f.object.dg.zcu.gpa;
3517 try f.allocs.put(gpa, local.new_local, true);3589 try f.allocs.put(gpa, local.new_local, true);
3518 return .{ .local_ref = local.new_local };3590 return .{ .local_ref = local.new_local };
3519}3591}
35203592
3521fn airRetPtr(f: *Function, inst: Air.Inst.Index) !CValue {3593fn airRetPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3522 const mod = f.object.dg.module;3594 const zcu = f.object.dg.zcu;
3523 const inst_ty = f.typeOfIndex(inst);3595 const inst_ty = f.typeOfIndex(inst);
3524 const elem_ty = inst_ty.childType(mod);3596 const elem_ty = inst_ty.childType(zcu);
3525 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .{ .undef = inst_ty };3597 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
35263598
3527 const local = try f.allocLocalValue(3599 const local = try f.allocLocalValue(
3528 elem_ty,3600 elem_ty,
3529 inst_ty.ptrAlignment(mod),3601 inst_ty.ptrAlignment(zcu),
3530 );3602 );
3531 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });3603 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3532 const gpa = f.object.dg.module.gpa;3604 const gpa = f.object.dg.zcu.gpa;
3533 try f.allocs.put(gpa, local.new_local, true);3605 try f.allocs.put(gpa, local.new_local, true);
3534 return .{ .local_ref = local.new_local };3606 return .{ .local_ref = local.new_local };
3535}3607}
...@@ -3559,15 +3631,15 @@ fn airArg(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3559,15 +3631,15 @@ fn airArg(f: *Function, inst: Air.Inst.Index) !CValue {
3559}3631}
35603632
3561fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {3633fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3562 const mod = f.object.dg.module;3634 const zcu = f.object.dg.zcu;
3563 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;3635 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35643636
3565 const ptr_ty = f.typeOf(ty_op.operand);3637 const ptr_ty = f.typeOf(ty_op.operand);
3566 const ptr_scalar_ty = ptr_ty.scalarType(mod);3638 const ptr_scalar_ty = ptr_ty.scalarType(zcu);
3567 const ptr_info = ptr_scalar_ty.ptrInfo(mod);3639 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
3568 const src_ty = Type.fromInterned(ptr_info.child);3640 const src_ty = Type.fromInterned(ptr_info.child);
35693641
3570 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) {3642 if (!src_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3571 try reap(f, inst, &.{ty_op.operand});3643 try reap(f, inst, &.{ty_op.operand});
3572 return .none;3644 return .none;
3573 }3645 }
...@@ -3577,10 +3649,10 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3577,10 +3649,10 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3577 try reap(f, inst, &.{ty_op.operand});3649 try reap(f, inst, &.{ty_op.operand});
35783650
3579 const is_aligned = if (ptr_info.flags.alignment != .none)3651 const is_aligned = if (ptr_info.flags.alignment != .none)
3580 ptr_info.flags.alignment.compare(.gte, src_ty.abiAlignment(mod))3652 ptr_info.flags.alignment.compare(.gte, src_ty.abiAlignment(zcu))
3581 else3653 else
3582 true;3654 true;
3583 const is_array = lowersToArray(src_ty, mod);3655 const is_array = lowersToArray(src_ty, zcu);
3584 const need_memcpy = !is_aligned or is_array;3656 const need_memcpy = !is_aligned or is_array;
35853657
3586 const writer = f.object.writer();3658 const writer = f.object.writer();
...@@ -3600,12 +3672,12 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3600,12 +3672,12 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3600 try writer.writeAll("))");3672 try writer.writeAll("))");
3601 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {3673 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
3602 const host_bits: u16 = ptr_info.packed_offset.host_size * 8;3674 const host_bits: u16 = ptr_info.packed_offset.host_size * 8;
3603 const host_ty = try mod.intType(.unsigned, host_bits);3675 const host_ty = try zcu.intType(.unsigned, host_bits);
36043676
3605 const bit_offset_ty = try mod.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));3677 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3606 const bit_offset_val = try mod.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);3678 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
36073679
3608 const field_ty = try mod.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(mod))));3680 const field_ty = try zcu.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(zcu))));
36093681
3610 try f.writeCValue(writer, local, .Other);3682 try f.writeCValue(writer, local, .Other);
3611 try v.elem(f, writer);3683 try v.elem(f, writer);
...@@ -3616,9 +3688,9 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3616,9 +3688,9 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3616 try writer.writeAll("((");3688 try writer.writeAll("((");
3617 try f.renderType(writer, field_ty);3689 try f.renderType(writer, field_ty);
3618 try writer.writeByte(')');3690 try writer.writeByte(')');
3619 const cant_cast = host_ty.isInt(mod) and host_ty.bitSize(mod) > 64;3691 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3620 if (cant_cast) {3692 if (cant_cast) {
3621 if (field_ty.bitSize(mod) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});3693 if (field_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3622 try writer.writeAll("zig_lo_");3694 try writer.writeAll("zig_lo_");
3623 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);3695 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
3624 try writer.writeByte('(');3696 try writer.writeByte('(');
...@@ -3628,7 +3700,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3628,7 +3700,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3628 try writer.writeByte('(');3700 try writer.writeByte('(');
3629 try f.writeCValueDeref(writer, operand);3701 try f.writeCValueDeref(writer, operand);
3630 try v.elem(f, writer);3702 try v.elem(f, writer);
3631 try writer.print(", {})", .{try f.fmtIntLiteral(bit_offset_ty, bit_offset_val)});3703 try writer.print(", {})", .{try f.fmtIntLiteral(bit_offset_val)});
3632 if (cant_cast) try writer.writeByte(')');3704 if (cant_cast) try writer.writeByte(')');
3633 try f.object.dg.renderBuiltinInfo(writer, field_ty, .bits);3705 try f.object.dg.renderBuiltinInfo(writer, field_ty, .bits);
3634 try writer.writeByte(')');3706 try writer.writeByte(')');
...@@ -3646,22 +3718,22 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3646,22 +3718,22 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3646}3718}
36473719
3648fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {3720fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
3649 const mod = f.object.dg.module;3721 const zcu = f.object.dg.zcu;
3650 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;3722 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
3651 const writer = f.object.writer();3723 const writer = f.object.writer();
3652 const op_inst = un_op.toIndex();3724 const op_inst = un_op.toIndex();
3653 const op_ty = f.typeOf(un_op);3725 const op_ty = f.typeOf(un_op);
3654 const ret_ty = if (is_ptr) op_ty.childType(mod) else op_ty;3726 const ret_ty = if (is_ptr) op_ty.childType(zcu) else op_ty;
3655 const lowered_ret_ty = try lowerFnRetTy(ret_ty, mod);3727 const lowered_ret_ty = try lowerFnRetTy(ret_ty, zcu);
36563728
3657 if (op_inst != null and f.air.instructions.items(.tag)[@intFromEnum(op_inst.?)] == .call_always_tail) {3729 if (op_inst != null and f.air.instructions.items(.tag)[@intFromEnum(op_inst.?)] == .call_always_tail) {
3658 try reap(f, inst, &.{un_op});3730 try reap(f, inst, &.{un_op});
3659 _ = try airCall(f, op_inst.?, .always_tail);3731 _ = try airCall(f, op_inst.?, .always_tail);
3660 } else if (lowered_ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {3732 } else if (lowered_ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3661 const operand = try f.resolveInst(un_op);3733 const operand = try f.resolveInst(un_op);
3662 try reap(f, inst, &.{un_op});3734 try reap(f, inst, &.{un_op});
3663 var deref = is_ptr;3735 var deref = is_ptr;
3664 const is_array = lowersToArray(ret_ty, mod);3736 const is_array = lowersToArray(ret_ty, zcu);
3665 const ret_val = if (is_array) ret_val: {3737 const ret_val = if (is_array) ret_val: {
3666 const array_local = try f.allocLocal(inst, lowered_ret_ty);3738 const array_local = try f.allocLocal(inst, lowered_ret_ty);
3667 try writer.writeAll("memcpy(");3739 try writer.writeAll("memcpy(");
...@@ -3696,16 +3768,16 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {...@@ -3696,16 +3768,16 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
3696}3768}
36973769
3698fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {3770fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
3699 const mod = f.object.dg.module;3771 const zcu = f.object.dg.zcu;
3700 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;3772 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37013773
3702 const operand = try f.resolveInst(ty_op.operand);3774 const operand = try f.resolveInst(ty_op.operand);
3703 try reap(f, inst, &.{ty_op.operand});3775 try reap(f, inst, &.{ty_op.operand});
37043776
3705 const inst_ty = f.typeOfIndex(inst);3777 const inst_ty = f.typeOfIndex(inst);
3706 const inst_scalar_ty = inst_ty.scalarType(mod);3778 const inst_scalar_ty = inst_ty.scalarType(zcu);
3707 const operand_ty = f.typeOf(ty_op.operand);3779 const operand_ty = f.typeOf(ty_op.operand);
3708 const scalar_ty = operand_ty.scalarType(mod);3780 const scalar_ty = operand_ty.scalarType(zcu);
37093781
3710 const writer = f.object.writer();3782 const writer = f.object.writer();
3711 const local = try f.allocLocal(inst, inst_ty);3783 const local = try f.allocLocal(inst, inst_ty);
...@@ -3722,20 +3794,20 @@ fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3722,20 +3794,20 @@ fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
3722}3794}
37233795
3724fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {3796fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3725 const mod = f.object.dg.module;3797 const zcu = f.object.dg.zcu;
3726 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;3798 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37273799
3728 const operand = try f.resolveInst(ty_op.operand);3800 const operand = try f.resolveInst(ty_op.operand);
3729 try reap(f, inst, &.{ty_op.operand});3801 try reap(f, inst, &.{ty_op.operand});
3730 const inst_ty = f.typeOfIndex(inst);3802 const inst_ty = f.typeOfIndex(inst);
3731 const inst_scalar_ty = inst_ty.scalarType(mod);3803 const inst_scalar_ty = inst_ty.scalarType(zcu);
3732 const dest_int_info = inst_scalar_ty.intInfo(mod);3804 const dest_int_info = inst_scalar_ty.intInfo(zcu);
3733 const dest_bits = dest_int_info.bits;3805 const dest_bits = dest_int_info.bits;
3734 const dest_c_bits = toCIntBits(dest_int_info.bits) orelse3806 const dest_c_bits = toCIntBits(dest_int_info.bits) orelse
3735 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});3807 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
3736 const operand_ty = f.typeOf(ty_op.operand);3808 const operand_ty = f.typeOf(ty_op.operand);
3737 const scalar_ty = operand_ty.scalarType(mod);3809 const scalar_ty = operand_ty.scalarType(zcu);
3738 const scalar_int_info = scalar_ty.intInfo(mod);3810 const scalar_int_info = scalar_ty.intInfo(zcu);
37393811
3740 const writer = f.object.writer();3812 const writer = f.object.writer();
3741 const local = try f.allocLocal(inst, inst_ty);3813 const local = try f.allocLocal(inst, inst_ty);
...@@ -3763,18 +3835,19 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3763,18 +3835,19 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3763 try v.elem(f, writer);3835 try v.elem(f, writer);
3764 } else switch (dest_int_info.signedness) {3836 } else switch (dest_int_info.signedness) {
3765 .unsigned => {3837 .unsigned => {
3766 const mask_val = try inst_scalar_ty.maxIntScalar(mod, scalar_ty);
3767 try writer.writeAll("zig_and_");3838 try writer.writeAll("zig_and_");
3768 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);3839 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
3769 try writer.writeByte('(');3840 try writer.writeByte('(');
3770 try f.writeCValue(writer, operand, .FunctionArgument);3841 try f.writeCValue(writer, operand, .FunctionArgument);
3771 try v.elem(f, writer);3842 try v.elem(f, writer);
3772 try writer.print(", {x})", .{try f.fmtIntLiteral(scalar_ty, mask_val)});3843 try writer.print(", {x})", .{
3844 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(zcu, scalar_ty)),
3845 });
3773 },3846 },
3774 .signed => {3847 .signed => {
3775 const c_bits = toCIntBits(scalar_int_info.bits) orelse3848 const c_bits = toCIntBits(scalar_int_info.bits) orelse
3776 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});3849 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
3777 const shift_val = try mod.intValue(Type.u8, c_bits - dest_bits);3850 const shift_val = try zcu.intValue(Type.u8, c_bits - dest_bits);
37783851
3779 try writer.writeAll("zig_shr_");3852 try writer.writeAll("zig_shr_");
3780 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);3853 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
...@@ -3792,9 +3865,9 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3792,9 +3865,9 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3792 try f.writeCValue(writer, operand, .FunctionArgument);3865 try f.writeCValue(writer, operand, .FunctionArgument);
3793 try v.elem(f, writer);3866 try v.elem(f, writer);
3794 if (c_bits == 128) try writer.writeByte(')');3867 if (c_bits == 128) try writer.writeByte(')');
3795 try writer.print(", {})", .{try f.fmtIntLiteral(Type.u8, shift_val)});3868 try writer.print(", {})", .{try f.fmtIntLiteral(shift_val)});
3796 if (c_bits == 128) try writer.writeByte(')');3869 if (c_bits == 128) try writer.writeByte(')');
3797 try writer.print(", {})", .{try f.fmtIntLiteral(Type.u8, shift_val)});3870 try writer.print(", {})", .{try f.fmtIntLiteral(shift_val)});
3798 },3871 },
3799 }3872 }
38003873
...@@ -3821,18 +3894,18 @@ fn airIntFromBool(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -3821,18 +3894,18 @@ fn airIntFromBool(f: *Function, inst: Air.Inst.Index) !CValue {
3821}3894}
38223895
3823fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {3896fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3824 const mod = f.object.dg.module;3897 const zcu = f.object.dg.zcu;
3825 // *a = b;3898 // *a = b;
3826 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;3899 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38273900
3828 const ptr_ty = f.typeOf(bin_op.lhs);3901 const ptr_ty = f.typeOf(bin_op.lhs);
3829 const ptr_scalar_ty = ptr_ty.scalarType(mod);3902 const ptr_scalar_ty = ptr_ty.scalarType(zcu);
3830 const ptr_info = ptr_scalar_ty.ptrInfo(mod);3903 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
38313904
3832 const ptr_val = try f.resolveInst(bin_op.lhs);3905 const ptr_val = try f.resolveInst(bin_op.lhs);
3833 const src_ty = f.typeOf(bin_op.rhs);3906 const src_ty = f.typeOf(bin_op.rhs);
38343907
3835 const val_is_undef = if (try f.air.value(bin_op.rhs, mod)) |v| v.isUndefDeep(mod) else false;3908 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |v| v.isUndefDeep(zcu) else false;
38363909
3837 if (val_is_undef) {3910 if (val_is_undef) {
3838 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });3911 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
...@@ -3848,10 +3921,10 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3848,10 +3921,10 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3848 }3921 }
38493922
3850 const is_aligned = if (ptr_info.flags.alignment != .none)3923 const is_aligned = if (ptr_info.flags.alignment != .none)
3851 ptr_info.flags.alignment.compare(.gte, src_ty.abiAlignment(mod))3924 ptr_info.flags.alignment.compare(.gte, src_ty.abiAlignment(zcu))
3852 else3925 else
3853 true;3926 true;
3854 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), mod);3927 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), zcu);
3855 const need_memcpy = !is_aligned or is_array;3928 const need_memcpy = !is_aligned or is_array;
38563929
3857 const src_val = try f.resolveInst(bin_op.rhs);3930 const src_val = try f.resolveInst(bin_op.rhs);
...@@ -3863,7 +3936,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3863,7 +3936,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3863 if (need_memcpy) {3936 if (need_memcpy) {
3864 // For this memcpy to safely work we need the rhs to have the same3937 // For this memcpy to safely work we need the rhs to have the same
3865 // underlying type as the lhs (i.e. they must both be arrays of the same underlying type).3938 // underlying type as the lhs (i.e. they must both be arrays of the same underlying type).
3866 assert(src_ty.eql(Type.fromInterned(ptr_info.child), f.object.dg.module));3939 assert(src_ty.eql(Type.fromInterned(ptr_info.child), f.object.dg.zcu));
38673940
3868 // If the source is a constant, writeCValue will emit a brace initialization3941 // If the source is a constant, writeCValue will emit a brace initialization
3869 // so work around this by initializing into new local.3942 // so work around this by initializing into new local.
...@@ -3893,12 +3966,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3893,12 +3966,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3893 }3966 }
3894 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {3967 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
3895 const host_bits = ptr_info.packed_offset.host_size * 8;3968 const host_bits = ptr_info.packed_offset.host_size * 8;
3896 const host_ty = try mod.intType(.unsigned, host_bits);3969 const host_ty = try zcu.intType(.unsigned, host_bits);
38973970
3898 const bit_offset_ty = try mod.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));3971 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3899 const bit_offset_val = try mod.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);3972 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
39003973
3901 const src_bits = src_ty.bitSize(mod);3974 const src_bits = src_ty.bitSize(zcu);
39023975
3903 const ExpectedContents = [BigInt.Managed.default_capacity]BigIntLimb;3976 const ExpectedContents = [BigInt.Managed.default_capacity]BigIntLimb;
3904 var stack align(@alignOf(ExpectedContents)) =3977 var stack align(@alignOf(ExpectedContents)) =
...@@ -3911,7 +3984,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3911,7 +3984,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3911 try mask.shiftLeft(&mask, ptr_info.packed_offset.bit_offset);3984 try mask.shiftLeft(&mask, ptr_info.packed_offset.bit_offset);
3912 try mask.bitNotWrap(&mask, .unsigned, host_bits);3985 try mask.bitNotWrap(&mask, .unsigned, host_bits);
39133986
3914 const mask_val = try mod.intValue_big(host_ty, mask.toConst());3987 const mask_val = try zcu.intValue_big(host_ty, mask.toConst());
39153988
3916 try f.writeCValueDeref(writer, ptr_val);3989 try f.writeCValueDeref(writer, ptr_val);
3917 try v.elem(f, writer);3990 try v.elem(f, writer);
...@@ -3922,12 +3995,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3922,12 +3995,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3922 try writer.writeByte('(');3995 try writer.writeByte('(');
3923 try f.writeCValueDeref(writer, ptr_val);3996 try f.writeCValueDeref(writer, ptr_val);
3924 try v.elem(f, writer);3997 try v.elem(f, writer);
3925 try writer.print(", {x}), zig_shl_", .{try f.fmtIntLiteral(host_ty, mask_val)});3998 try writer.print(", {x}), zig_shl_", .{try f.fmtIntLiteral(mask_val)});
3926 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);3999 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
3927 try writer.writeByte('(');4000 try writer.writeByte('(');
3928 const cant_cast = host_ty.isInt(mod) and host_ty.bitSize(mod) > 64;4001 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3929 if (cant_cast) {4002 if (cant_cast) {
3930 if (src_ty.bitSize(mod) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});4003 if (src_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3931 try writer.writeAll("zig_make_");4004 try writer.writeAll("zig_make_");
3932 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);4005 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
3933 try writer.writeAll("(0, ");4006 try writer.writeAll("(0, ");
...@@ -3937,7 +4010,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3937,7 +4010,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3937 try writer.writeByte(')');4010 try writer.writeByte(')');
3938 }4011 }
39394012
3940 if (src_ty.isPtrAtRuntime(mod)) {4013 if (src_ty.isPtrAtRuntime(zcu)) {
3941 try writer.writeByte('(');4014 try writer.writeByte('(');
3942 try f.renderType(writer, Type.usize);4015 try f.renderType(writer, Type.usize);
3943 try writer.writeByte(')');4016 try writer.writeByte(')');
...@@ -3945,7 +4018,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3945,7 +4018,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3945 try f.writeCValue(writer, src_val, .Other);4018 try f.writeCValue(writer, src_val, .Other);
3946 try v.elem(f, writer);4019 try v.elem(f, writer);
3947 if (cant_cast) try writer.writeByte(')');4020 if (cant_cast) try writer.writeByte(')');
3948 try writer.print(", {}))", .{try f.fmtIntLiteral(bit_offset_ty, bit_offset_val)});4021 try writer.print(", {}))", .{try f.fmtIntLiteral(bit_offset_val)});
3949 } else {4022 } else {
3950 try f.writeCValueDeref(writer, ptr_val);4023 try f.writeCValueDeref(writer, ptr_val);
3951 try v.elem(f, writer);4024 try v.elem(f, writer);
...@@ -3960,7 +4033,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -3960,7 +4033,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3960}4033}
39614034
3962fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info: BuiltinInfo) !CValue {4035fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info: BuiltinInfo) !CValue {
3963 const mod = f.object.dg.module;4036 const zcu = f.object.dg.zcu;
3964 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;4037 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
3965 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;4038 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
39664039
...@@ -3970,7 +4043,7 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:...@@ -3970,7 +4043,7 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:
39704043
3971 const inst_ty = f.typeOfIndex(inst);4044 const inst_ty = f.typeOfIndex(inst);
3972 const operand_ty = f.typeOf(bin_op.lhs);4045 const operand_ty = f.typeOf(bin_op.lhs);
3973 const scalar_ty = operand_ty.scalarType(mod);4046 const scalar_ty = operand_ty.scalarType(zcu);
39744047
3975 const w = f.object.writer();4048 const w = f.object.writer();
3976 const local = try f.allocLocal(inst, inst_ty);4049 const local = try f.allocLocal(inst, inst_ty);
...@@ -3998,11 +4071,11 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:...@@ -3998,11 +4071,11 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:
3998}4071}
39994072
4000fn airNot(f: *Function, inst: Air.Inst.Index) !CValue {4073fn airNot(f: *Function, inst: Air.Inst.Index) !CValue {
4001 const mod = f.object.dg.module;4074 const zcu = f.object.dg.zcu;
4002 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;4075 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
4003 const operand_ty = f.typeOf(ty_op.operand);4076 const operand_ty = f.typeOf(ty_op.operand);
4004 const scalar_ty = operand_ty.scalarType(mod);4077 const scalar_ty = operand_ty.scalarType(zcu);
4005 if (scalar_ty.ip_index != .bool_type) return try airUnBuiltinCall(f, inst, "not", .bits);4078 if (scalar_ty.toIntern() != .bool_type) return try airUnBuiltinCall(f, inst, "not", .bits);
40064079
4007 const op = try f.resolveInst(ty_op.operand);4080 const op = try f.resolveInst(ty_op.operand);
4008 try reap(f, inst, &.{ty_op.operand});4081 try reap(f, inst, &.{ty_op.operand});
...@@ -4031,11 +4104,11 @@ fn airBinOp(...@@ -4031,11 +4104,11 @@ fn airBinOp(
4031 operation: []const u8,4104 operation: []const u8,
4032 info: BuiltinInfo,4105 info: BuiltinInfo,
4033) !CValue {4106) !CValue {
4034 const mod = f.object.dg.module;4107 const zcu = f.object.dg.zcu;
4035 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;4108 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
4036 const operand_ty = f.typeOf(bin_op.lhs);4109 const operand_ty = f.typeOf(bin_op.lhs);
4037 const scalar_ty = operand_ty.scalarType(mod);4110 const scalar_ty = operand_ty.scalarType(zcu);
4038 if ((scalar_ty.isInt(mod) and scalar_ty.bitSize(mod) > 64) or scalar_ty.isRuntimeFloat())4111 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(zcu) > 64) or scalar_ty.isRuntimeFloat())
4039 return try airBinBuiltinCall(f, inst, operation, info);4112 return try airBinBuiltinCall(f, inst, operation, info);
40404113
4041 const lhs = try f.resolveInst(bin_op.lhs);4114 const lhs = try f.resolveInst(bin_op.lhs);
...@@ -4069,12 +4142,12 @@ fn airCmpOp(...@@ -4069,12 +4142,12 @@ fn airCmpOp(
4069 data: anytype,4142 data: anytype,
4070 operator: std.math.CompareOperator,4143 operator: std.math.CompareOperator,
4071) !CValue {4144) !CValue {
4072 const mod = f.object.dg.module;4145 const zcu = f.object.dg.zcu;
4073 const lhs_ty = f.typeOf(data.lhs);4146 const lhs_ty = f.typeOf(data.lhs);
4074 const scalar_ty = lhs_ty.scalarType(mod);4147 const scalar_ty = lhs_ty.scalarType(zcu);
40754148
4076 const scalar_bits = scalar_ty.bitSize(mod);4149 const scalar_bits = scalar_ty.bitSize(zcu);
4077 if (scalar_ty.isInt(mod) and scalar_bits > 64)4150 if (scalar_ty.isInt(zcu) and scalar_bits > 64)
4078 return airCmpBuiltinCall(4151 return airCmpBuiltinCall(
4079 f,4152 f,
4080 inst,4153 inst,
...@@ -4092,7 +4165,7 @@ fn airCmpOp(...@@ -4092,7 +4165,7 @@ fn airCmpOp(
4092 try reap(f, inst, &.{ data.lhs, data.rhs });4165 try reap(f, inst, &.{ data.lhs, data.rhs });
40934166
4094 const rhs_ty = f.typeOf(data.rhs);4167 const rhs_ty = f.typeOf(data.rhs);
4095 const need_cast = lhs_ty.isSinglePointer(mod) or rhs_ty.isSinglePointer(mod);4168 const need_cast = lhs_ty.isSinglePointer(zcu) or rhs_ty.isSinglePointer(zcu);
4096 const writer = f.object.writer();4169 const writer = f.object.writer();
4097 const local = try f.allocLocal(inst, inst_ty);4170 const local = try f.allocLocal(inst, inst_ty);
4098 const v = try Vectorize.start(f, inst, writer, lhs_ty);4171 const v = try Vectorize.start(f, inst, writer, lhs_ty);
...@@ -4117,12 +4190,12 @@ fn airEquality(...@@ -4117,12 +4190,12 @@ fn airEquality(
4117 inst: Air.Inst.Index,4190 inst: Air.Inst.Index,
4118 operator: std.math.CompareOperator,4191 operator: std.math.CompareOperator,
4119) !CValue {4192) !CValue {
4120 const mod = f.object.dg.module;4193 const zcu = f.object.dg.zcu;
4121 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;4194 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
41224195
4123 const operand_ty = f.typeOf(bin_op.lhs);4196 const operand_ty = f.typeOf(bin_op.lhs);
4124 const operand_bits = operand_ty.bitSize(mod);4197 const operand_bits = operand_ty.bitSize(zcu);
4125 if (operand_ty.isInt(mod) and operand_bits > 64)4198 if (operand_ty.isInt(zcu) and operand_bits > 64)
4126 return airCmpBuiltinCall(4199 return airCmpBuiltinCall(
4127 f,4200 f,
4128 inst,4201 inst,
...@@ -4145,7 +4218,7 @@ fn airEquality(...@@ -4145,7 +4218,7 @@ fn airEquality(
4145 try f.writeCValue(writer, local, .Other);4218 try f.writeCValue(writer, local, .Other);
4146 try a.assign(f, writer);4219 try a.assign(f, writer);
41474220
4148 if (operand_ty.zigTypeTag(mod) == .Optional and !operand_ty.optionalReprIsPayload(mod)) {4221 if (operand_ty.zigTypeTag(zcu) == .Optional and !operand_ty.optionalReprIsPayload(zcu)) {
4149 try f.writeCValueMember(writer, lhs, .{ .identifier = "is_null" });4222 try f.writeCValueMember(writer, lhs, .{ .identifier = "is_null" });
4150 try writer.writeAll(" || ");4223 try writer.writeAll(" || ");
4151 try f.writeCValueMember(writer, rhs, .{ .identifier = "is_null" });4224 try f.writeCValueMember(writer, rhs, .{ .identifier = "is_null" });
...@@ -4184,7 +4257,7 @@ fn airCmpLtErrorsLen(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4184,7 +4257,7 @@ fn airCmpLtErrorsLen(f: *Function, inst: Air.Inst.Index) !CValue {
4184}4257}
41854258
4186fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {4259fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4187 const mod = f.object.dg.module;4260 const zcu = f.object.dg.zcu;
4188 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;4261 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
4189 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;4262 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
41904263
...@@ -4193,8 +4266,8 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {...@@ -4193,8 +4266,8 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4193 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });4266 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
41944267
4195 const inst_ty = f.typeOfIndex(inst);4268 const inst_ty = f.typeOfIndex(inst);
4196 const inst_scalar_ty = inst_ty.scalarType(mod);4269 const inst_scalar_ty = inst_ty.scalarType(zcu);
4197 const elem_ty = inst_scalar_ty.elemType2(mod);4270 const elem_ty = inst_scalar_ty.elemType2(zcu);
41984271
4199 const local = try f.allocLocal(inst, inst_ty);4272 const local = try f.allocLocal(inst, inst_ty);
4200 const writer = f.object.writer();4273 const writer = f.object.writer();
...@@ -4203,7 +4276,7 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {...@@ -4203,7 +4276,7 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4203 try v.elem(f, writer);4276 try v.elem(f, writer);
4204 try writer.writeAll(" = ");4277 try writer.writeAll(" = ");
42054278
4206 if (elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {4279 if (elem_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
4207 // We must convert to and from integer types to prevent UB if the operation4280 // We must convert to and from integer types to prevent UB if the operation
4208 // results in a NULL pointer, or if LHS is NULL. The operation is only UB4281 // results in a NULL pointer, or if LHS is NULL. The operation is only UB
4209 // if the result is NULL and then dereferenced.4282 // if the result is NULL and then dereferenced.
...@@ -4232,13 +4305,13 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {...@@ -4232,13 +4305,13 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4232}4305}
42334306
4234fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []const u8) !CValue {4307fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []const u8) !CValue {
4235 const mod = f.object.dg.module;4308 const zcu = f.object.dg.zcu;
4236 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;4309 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
42374310
4238 const inst_ty = f.typeOfIndex(inst);4311 const inst_ty = f.typeOfIndex(inst);
4239 const inst_scalar_ty = inst_ty.scalarType(mod);4312 const inst_scalar_ty = inst_ty.scalarType(zcu);
42404313
4241 if (inst_scalar_ty.isInt(mod) and inst_scalar_ty.bitSize(mod) > 64)4314 if (inst_scalar_ty.isInt(zcu) and inst_scalar_ty.bitSize(zcu) > 64)
4242 return try airBinBuiltinCall(f, inst, operation[1..], .none);4315 return try airBinBuiltinCall(f, inst, operation[1..], .none);
4243 if (inst_scalar_ty.isRuntimeFloat())4316 if (inst_scalar_ty.isRuntimeFloat())
4244 return try airBinFloatOp(f, inst, operation);4317 return try airBinFloatOp(f, inst, operation);
...@@ -4274,7 +4347,7 @@ fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []cons...@@ -4274,7 +4347,7 @@ fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []cons
4274}4347}
42754348
4276fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {4349fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4277 const mod = f.object.dg.module;4350 const zcu = f.object.dg.zcu;
4278 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;4351 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
4279 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;4352 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
42804353
...@@ -4283,7 +4356,7 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4283,7 +4356,7 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4283 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });4356 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
42844357
4285 const inst_ty = f.typeOfIndex(inst);4358 const inst_ty = f.typeOfIndex(inst);
4286 const ptr_ty = inst_ty.slicePtrFieldType(mod);4359 const ptr_ty = inst_ty.slicePtrFieldType(zcu);
42874360
4288 const writer = f.object.writer();4361 const writer = f.object.writer();
4289 const local = try f.allocLocal(inst, inst_ty);4362 const local = try f.allocLocal(inst, inst_ty);
...@@ -4291,9 +4364,6 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4291,9 +4364,6 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4291 const a = try Assignment.start(f, writer, ptr_ty);4364 const a = try Assignment.start(f, writer, ptr_ty);
4292 try f.writeCValueMember(writer, local, .{ .identifier = "ptr" });4365 try f.writeCValueMember(writer, local, .{ .identifier = "ptr" });
4293 try a.assign(f, writer);4366 try a.assign(f, writer);
4294 try writer.writeByte('(');
4295 try f.renderType(writer, ptr_ty);
4296 try writer.writeByte(')');
4297 try f.writeCValue(writer, ptr, .Other);4367 try f.writeCValue(writer, ptr, .Other);
4298 try a.end(f, writer);4368 try a.end(f, writer);
4299 }4369 }
...@@ -4301,7 +4371,7 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4301,7 +4371,7 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4301 const a = try Assignment.start(f, writer, Type.usize);4371 const a = try Assignment.start(f, writer, Type.usize);
4302 try f.writeCValueMember(writer, local, .{ .identifier = "len" });4372 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
4303 try a.assign(f, writer);4373 try a.assign(f, writer);
4304 try f.writeCValue(writer, len, .Other);4374 try f.writeCValue(writer, len, .Initializer);
4305 try a.end(f, writer);4375 try a.end(f, writer);
4306 }4376 }
4307 return local;4377 return local;
...@@ -4312,7 +4382,7 @@ fn airCall(...@@ -4312,7 +4382,7 @@ fn airCall(
4312 inst: Air.Inst.Index,4382 inst: Air.Inst.Index,
4313 modifier: std.builtin.CallModifier,4383 modifier: std.builtin.CallModifier,
4314) !CValue {4384) !CValue {
4315 const mod = f.object.dg.module;4385 const zcu = f.object.dg.zcu;
4316 // Not even allowed to call panic in a naked function.4386 // Not even allowed to call panic in a naked function.
4317 if (f.object.dg.is_naked_fn) return .none;4387 if (f.object.dg.is_naked_fn) return .none;
43184388
...@@ -4334,7 +4404,7 @@ fn airCall(...@@ -4334,7 +4404,7 @@ fn airCall(
4334 }4404 }
4335 resolved_arg.* = try f.resolveInst(arg);4405 resolved_arg.* = try f.resolveInst(arg);
4336 if (arg_cty != try f.typeToIndex(arg_ty, .complete)) {4406 if (arg_cty != try f.typeToIndex(arg_ty, .complete)) {
4337 const lowered_arg_ty = try lowerFnRetTy(arg_ty, mod);4407 const lowered_arg_ty = try lowerFnRetTy(arg_ty, zcu);
43384408
4339 const array_local = try f.allocLocal(inst, lowered_arg_ty);4409 const array_local = try f.allocLocal(inst, lowered_arg_ty);
4340 try writer.writeAll("memcpy(");4410 try writer.writeAll("memcpy(");
...@@ -4357,20 +4427,19 @@ fn airCall(...@@ -4357,20 +4427,19 @@ fn airCall(
4357 }4427 }
43584428
4359 const callee_ty = f.typeOf(pl_op.operand);4429 const callee_ty = f.typeOf(pl_op.operand);
4360 const fn_ty = switch (callee_ty.zigTypeTag(mod)) {4430 const fn_info = zcu.typeToFunc(switch (callee_ty.zigTypeTag(zcu)) {
4361 .Fn => callee_ty,4431 .Fn => callee_ty,
4362 .Pointer => callee_ty.childType(mod),4432 .Pointer => callee_ty.childType(zcu),
4363 else => unreachable,4433 else => unreachable,
4364 };4434 }).?;
43654435 const ret_ty = Type.fromInterned(fn_info.return_type);
4366 const ret_ty = fn_ty.fnReturnType(mod);4436 const lowered_ret_ty = try lowerFnRetTy(ret_ty, zcu);
4367 const lowered_ret_ty = try lowerFnRetTy(ret_ty, mod);
43684437
4369 const result_local = result: {4438 const result_local = result: {
4370 if (modifier == .always_tail) {4439 if (modifier == .always_tail) {
4371 try writer.writeAll("zig_always_tail return ");4440 try writer.writeAll("zig_always_tail return ");
4372 break :result .none;4441 break :result .none;
4373 } else if (!lowered_ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {4442 } else if (!lowered_ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
4374 break :result .none;4443 break :result .none;
4375 } else if (f.liveness.isUnused(inst)) {4444 } else if (f.liveness.isUnused(inst)) {
4376 try writer.writeByte('(');4445 try writer.writeByte('(');
...@@ -4388,8 +4457,8 @@ fn airCall(...@@ -4388,8 +4457,8 @@ fn airCall(
4388 callee: {4457 callee: {
4389 known: {4458 known: {
4390 const fn_decl = fn_decl: {4459 const fn_decl = fn_decl: {
4391 const callee_val = (try f.air.value(pl_op.operand, mod)) orelse break :known;4460 const callee_val = (try f.air.value(pl_op.operand, zcu)) orelse break :known;
4392 break :fn_decl switch (mod.intern_pool.indexToKey(callee_val.ip_index)) {4461 break :fn_decl switch (zcu.intern_pool.indexToKey(callee_val.toIntern())) {
4393 .extern_func => |extern_func| extern_func.decl,4462 .extern_func => |extern_func| extern_func.decl,
4394 .func => |func| func.owner_decl,4463 .func => |func| func.owner_decl,
4395 .ptr => |ptr| switch (ptr.addr) {4464 .ptr => |ptr| switch (ptr.addr) {
...@@ -4420,18 +4489,21 @@ fn airCall(...@@ -4420,18 +4489,21 @@ fn airCall(
4420 }4489 }
44214490
4422 try writer.writeByte('(');4491 try writer.writeByte('(');
4423 var args_written: usize = 0;4492 var need_comma = false;
4424 for (resolved_args) |resolved_arg| {4493 for (resolved_args) |resolved_arg| {
4425 if (resolved_arg == .none) continue;4494 if (resolved_arg == .none) continue;
4426 if (args_written != 0) try writer.writeAll(", ");4495 if (need_comma) try writer.writeAll(", ");
4496 need_comma = true;
4427 try f.writeCValue(writer, resolved_arg, .FunctionArgument);4497 try f.writeCValue(writer, resolved_arg, .FunctionArgument);
4428 if (resolved_arg == .new_local) try freeLocal(f, inst, resolved_arg.new_local, null);4498 switch (resolved_arg) {
4429 args_written += 1;4499 .new_local => |local| try freeLocal(f, inst, local, null),
4500 else => {},
4501 }
4430 }4502 }
4431 try writer.writeAll(");\n");4503 try writer.writeAll(");\n");
44324504
4433 const result = result: {4505 const result = result: {
4434 if (result_local == .none or !lowersToArray(ret_ty, mod))4506 if (result_local == .none or !lowersToArray(ret_ty, zcu))
4435 break :result result_local;4507 break :result result_local;
44364508
4437 const array_local = try f.allocLocal(inst, ret_ty);4509 const array_local = try f.allocLocal(inst, ret_ty);
...@@ -4465,22 +4537,22 @@ fn airDbgStmt(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4465,22 +4537,22 @@ fn airDbgStmt(f: *Function, inst: Air.Inst.Index) !CValue {
4465}4537}
44664538
4467fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {4539fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
4468 const mod = f.object.dg.module;4540 const zcu = f.object.dg.zcu;
4469 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;4541 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
4470 const extra = f.air.extraData(Air.DbgInlineBlock, ty_pl.payload);4542 const extra = f.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
4471 const owner_decl = mod.funcOwnerDeclPtr(extra.data.func);4543 const owner_decl = zcu.funcOwnerDeclPtr(extra.data.func);
4472 const writer = f.object.writer();4544 const writer = f.object.writer();
4473 try writer.writeAll("/* ");4545 try writer.writeAll("/* ");
4474 try owner_decl.renderFullyQualifiedName(mod, writer);4546 try owner_decl.renderFullyQualifiedName(zcu, writer);
4475 try writer.writeAll(" */ ");4547 try writer.writeAll(" */ ");
4476 return lowerBlock(f, inst, @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]));4548 return lowerBlock(f, inst, @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]));
4477}4549}
44784550
4479fn airDbgVar(f: *Function, inst: Air.Inst.Index) !CValue {4551fn airDbgVar(f: *Function, inst: Air.Inst.Index) !CValue {
4480 const mod = f.object.dg.module;4552 const zcu = f.object.dg.zcu;
4481 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;4553 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
4482 const name = f.air.nullTerminatedString(pl_op.payload);4554 const name = f.air.nullTerminatedString(pl_op.payload);
4483 const operand_is_undef = if (try f.air.value(pl_op.operand, mod)) |v| v.isUndefDeep(mod) else false;4555 const operand_is_undef = if (try f.air.value(pl_op.operand, zcu)) |v| v.isUndefDeep(zcu) else false;
4484 if (!operand_is_undef) _ = try f.resolveInst(pl_op.operand);4556 if (!operand_is_undef) _ = try f.resolveInst(pl_op.operand);
44854557
4486 try reap(f, inst, &.{pl_op.operand});4558 try reap(f, inst, &.{pl_op.operand});
...@@ -4496,7 +4568,7 @@ fn airBlock(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4496,7 +4568,7 @@ fn airBlock(f: *Function, inst: Air.Inst.Index) !CValue {
4496}4568}
44974569
4498fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index) !CValue {4570fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index) !CValue {
4499 const mod = f.object.dg.module;4571 const zcu = f.object.dg.zcu;
4500 const liveness_block = f.liveness.getBlock(inst);4572 const liveness_block = f.liveness.getBlock(inst);
45014573
4502 const block_id: usize = f.next_block_index;4574 const block_id: usize = f.next_block_index;
...@@ -4504,7 +4576,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)...@@ -4504,7 +4576,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)
4504 const writer = f.object.writer();4576 const writer = f.object.writer();
45054577
4506 const inst_ty = f.typeOfIndex(inst);4578 const inst_ty = f.typeOfIndex(inst);
4507 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(mod) and !f.liveness.isUnused(inst))4579 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu) and !f.liveness.isUnused(inst))
4508 try f.allocLocal(inst, inst_ty)4580 try f.allocLocal(inst, inst_ty)
4509 else4581 else
4510 .none;4582 .none;
...@@ -4526,7 +4598,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)...@@ -4526,7 +4598,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)
4526 try f.object.indent_writer.insertNewline();4598 try f.object.indent_writer.insertNewline();
45274599
4528 // noreturn blocks have no `br` instructions reaching them, so we don't want a label4600 // noreturn blocks have no `br` instructions reaching them, so we don't want a label
4529 if (!f.typeOfIndex(inst).isNoReturn(mod)) {4601 if (!f.typeOfIndex(inst).isNoReturn(zcu)) {
4530 // label must be followed by an expression, include an empty one.4602 // label must be followed by an expression, include an empty one.
4531 try writer.print("zig_block_{d}:;\n", .{block_id});4603 try writer.print("zig_block_{d}:;\n", .{block_id});
4532 }4604 }
...@@ -4543,11 +4615,11 @@ fn airTry(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4543,11 +4615,11 @@ fn airTry(f: *Function, inst: Air.Inst.Index) !CValue {
4543}4615}
45444616
4545fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {4617fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {
4546 const mod = f.object.dg.module;4618 const zcu = f.object.dg.zcu;
4547 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;4619 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
4548 const extra = f.air.extraData(Air.TryPtr, ty_pl.payload);4620 const extra = f.air.extraData(Air.TryPtr, ty_pl.payload);
4549 const body: []const Air.Inst.Index = @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]);4621 const body: []const Air.Inst.Index = @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]);
4550 const err_union_ty = f.typeOf(extra.data.ptr).childType(mod);4622 const err_union_ty = f.typeOf(extra.data.ptr).childType(zcu);
4551 return lowerTry(f, inst, extra.data.ptr, body, err_union_ty, true);4623 return lowerTry(f, inst, extra.data.ptr, body, err_union_ty, true);
4552}4624}
45534625
...@@ -4559,15 +4631,15 @@ fn lowerTry(...@@ -4559,15 +4631,15 @@ fn lowerTry(
4559 err_union_ty: Type,4631 err_union_ty: Type,
4560 is_ptr: bool,4632 is_ptr: bool,
4561) !CValue {4633) !CValue {
4562 const mod = f.object.dg.module;4634 const zcu = f.object.dg.zcu;
4563 const err_union = try f.resolveInst(operand);4635 const err_union = try f.resolveInst(operand);
4564 const inst_ty = f.typeOfIndex(inst);4636 const inst_ty = f.typeOfIndex(inst);
4565 const liveness_condbr = f.liveness.getCondBr(inst);4637 const liveness_condbr = f.liveness.getCondBr(inst);
4566 const writer = f.object.writer();4638 const writer = f.object.writer();
4567 const payload_ty = err_union_ty.errorUnionPayload(mod);4639 const payload_ty = err_union_ty.errorUnionPayload(zcu);
4568 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod);4640 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
45694641
4570 if (!err_union_ty.errorUnionSet(mod).errorSetIsEmpty(mod)) {4642 if (!err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu)) {
4571 try writer.writeAll("if (");4643 try writer.writeAll("if (");
4572 if (!payload_has_bits) {4644 if (!payload_has_bits) {
4573 if (is_ptr)4645 if (is_ptr)
...@@ -4661,7 +4733,7 @@ const LocalResult = struct {...@@ -4661,7 +4733,7 @@ const LocalResult = struct {
4661 need_free: bool,4733 need_free: bool,
46624734
4663 fn move(lr: LocalResult, f: *Function, inst: Air.Inst.Index, dest_ty: Type) !CValue {4735 fn move(lr: LocalResult, f: *Function, inst: Air.Inst.Index, dest_ty: Type) !CValue {
4664 const mod = f.object.dg.module;4736 const zcu = f.object.dg.zcu;
46654737
4666 if (lr.need_free) {4738 if (lr.need_free) {
4667 // Move the freshly allocated local to be owned by this instruction,4739 // Move the freshly allocated local to be owned by this instruction,
...@@ -4673,7 +4745,7 @@ const LocalResult = struct {...@@ -4673,7 +4745,7 @@ const LocalResult = struct {
4673 try lr.free(f);4745 try lr.free(f);
4674 const writer = f.object.writer();4746 const writer = f.object.writer();
4675 try f.writeCValue(writer, local, .Other);4747 try f.writeCValue(writer, local, .Other);
4676 if (dest_ty.isAbiInt(mod)) {4748 if (dest_ty.isAbiInt(zcu)) {
4677 try writer.writeAll(" = ");4749 try writer.writeAll(" = ");
4678 } else {4750 } else {
4679 try writer.writeAll(" = (");4751 try writer.writeAll(" = (");
...@@ -4693,13 +4765,13 @@ const LocalResult = struct {...@@ -4693,13 +4765,13 @@ const LocalResult = struct {
4693};4765};
46944766
4695fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !LocalResult {4767fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !LocalResult {
4696 const mod = f.object.dg.module;4768 const zcu = f.object.dg.zcu;
4697 const target = mod.getTarget();4769 const target = &f.object.dg.mod.resolved_target.result;
4698 const writer = f.object.writer();4770 const writer = f.object.writer();
46994771
4700 if (operand_ty.isAbiInt(mod) and dest_ty.isAbiInt(mod)) {4772 if (operand_ty.isAbiInt(zcu) and dest_ty.isAbiInt(zcu)) {
4701 const src_info = dest_ty.intInfo(mod);4773 const src_info = dest_ty.intInfo(zcu);
4702 const dest_info = operand_ty.intInfo(mod);4774 const dest_info = operand_ty.intInfo(zcu);
4703 if (src_info.signedness == dest_info.signedness and4775 if (src_info.signedness == dest_info.signedness and
4704 src_info.bits == dest_info.bits)4776 src_info.bits == dest_info.bits)
4705 {4777 {
...@@ -4710,7 +4782,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca...@@ -4710,7 +4782,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
4710 }4782 }
4711 }4783 }
47124784
4713 if (dest_ty.isPtrAtRuntime(mod) and operand_ty.isPtrAtRuntime(mod)) {4785 if (dest_ty.isPtrAtRuntime(zcu) and operand_ty.isPtrAtRuntime(zcu)) {
4714 const local = try f.allocLocal(null, dest_ty);4786 const local = try f.allocLocal(null, dest_ty);
4715 try f.writeCValue(writer, local, .Other);4787 try f.writeCValue(writer, local, .Other);
4716 try writer.writeAll(" = (");4788 try writer.writeAll(" = (");
...@@ -4727,7 +4799,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca...@@ -4727,7 +4799,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
4727 const operand_lval = if (operand == .constant) blk: {4799 const operand_lval = if (operand == .constant) blk: {
4728 const operand_local = try f.allocLocal(null, operand_ty);4800 const operand_local = try f.allocLocal(null, operand_ty);
4729 try f.writeCValue(writer, operand_local, .Other);4801 try f.writeCValue(writer, operand_local, .Other);
4730 if (operand_ty.isAbiInt(mod)) {4802 if (operand_ty.isAbiInt(zcu)) {
4731 try writer.writeAll(" = ");4803 try writer.writeAll(" = ");
4732 } else {4804 } else {
4733 try writer.writeAll(" = (");4805 try writer.writeAll(" = (");
...@@ -4747,14 +4819,14 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca...@@ -4747,14 +4819,14 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
4747 try writer.writeAll(", sizeof(");4819 try writer.writeAll(", sizeof(");
4748 try f.renderType(4820 try f.renderType(
4749 writer,4821 writer,
4750 if (dest_ty.abiSize(mod) <= operand_ty.abiSize(mod)) dest_ty else operand_ty,4822 if (dest_ty.abiSize(zcu) <= operand_ty.abiSize(zcu)) dest_ty else operand_ty,
4751 );4823 );
4752 try writer.writeAll("));\n");4824 try writer.writeAll("));\n");
47534825
4754 // Ensure padding bits have the expected value.4826 // Ensure padding bits have the expected value.
4755 if (dest_ty.isAbiInt(mod)) {4827 if (dest_ty.isAbiInt(zcu)) {
4756 const dest_cty = try f.typeToCType(dest_ty, .complete);4828 const dest_cty = try f.typeToCType(dest_ty, .complete);
4757 const dest_info = dest_ty.intInfo(mod);4829 const dest_info = dest_ty.intInfo(zcu);
4758 var bits: u16 = dest_info.bits;4830 var bits: u16 = dest_info.bits;
4759 var wrap_cty: ?CType = null;4831 var wrap_cty: ?CType = null;
4760 var need_bitcasts = false;4832 var need_bitcasts = false;
...@@ -4779,7 +4851,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca...@@ -4779,7 +4851,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
4779 try writer.writeByte('(');4851 try writer.writeByte('(');
4780 }4852 }
4781 try writer.writeAll("zig_wrap_");4853 try writer.writeAll("zig_wrap_");
4782 const info_ty = try mod.intType(dest_info.signedness, bits);4854 const info_ty = try zcu.intType(dest_info.signedness, bits);
4783 if (wrap_cty) |cty|4855 if (wrap_cty) |cty|
4784 try f.object.dg.renderCTypeForBuiltinFnName(writer, cty)4856 try f.object.dg.renderCTypeForBuiltinFnName(writer, cty)
4785 else4857 else
...@@ -4912,7 +4984,7 @@ fn airCondBr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4912,7 +4984,7 @@ fn airCondBr(f: *Function, inst: Air.Inst.Index) !CValue {
4912}4984}
49134985
4914fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {4986fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4915 const mod = f.object.dg.module;4987 const zcu = f.object.dg.zcu;
4916 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;4988 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
4917 const condition = try f.resolveInst(pl_op.operand);4989 const condition = try f.resolveInst(pl_op.operand);
4918 try reap(f, inst, &.{pl_op.operand});4990 try reap(f, inst, &.{pl_op.operand});
...@@ -4921,11 +4993,11 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4921,11 +4993,11 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4921 const writer = f.object.writer();4993 const writer = f.object.writer();
49224994
4923 try writer.writeAll("switch (");4995 try writer.writeAll("switch (");
4924 if (condition_ty.zigTypeTag(mod) == .Bool) {4996 if (condition_ty.zigTypeTag(zcu) == .Bool) {
4925 try writer.writeByte('(');4997 try writer.writeByte('(');
4926 try f.renderType(writer, Type.u1);4998 try f.renderType(writer, Type.u1);
4927 try writer.writeByte(')');4999 try writer.writeByte(')');
4928 } else if (condition_ty.isPtrAtRuntime(mod)) {5000 } else if (condition_ty.isPtrAtRuntime(zcu)) {
4929 try writer.writeByte('(');5001 try writer.writeByte('(');
4930 try f.renderType(writer, Type.usize);5002 try f.renderType(writer, Type.usize);
4931 try writer.writeByte(')');5003 try writer.writeByte(')');
...@@ -4952,12 +5024,12 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4952,12 +5024,12 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4952 for (items) |item| {5024 for (items) |item| {
4953 try f.object.indent_writer.insertNewline();5025 try f.object.indent_writer.insertNewline();
4954 try writer.writeAll("case ");5026 try writer.writeAll("case ");
4955 if (condition_ty.isPtrAtRuntime(mod)) {5027 if (condition_ty.isPtrAtRuntime(zcu)) {
4956 try writer.writeByte('(');5028 try writer.writeByte('(');
4957 try f.renderType(writer, Type.usize);5029 try f.renderType(writer, Type.usize);
4958 try writer.writeByte(')');5030 try writer.writeByte(')');
4959 }5031 }
4960 try f.object.dg.renderValue(writer, condition_ty, (try f.air.value(item, mod)).?, .Other);5032 try f.object.dg.renderValue(writer, (try f.air.value(item, zcu)).?, .Other);
4961 try writer.writeByte(':');5033 try writer.writeByte(':');
4962 }5034 }
4963 try writer.writeByte(' ');5035 try writer.writeByte(' ');
...@@ -4994,13 +5066,13 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -4994,13 +5066,13 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4994}5066}
49955067
4996fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool {5068fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool {
4997 const target = f.object.dg.module.getTarget();5069 const target = &f.object.dg.mod.resolved_target.result;
4998 return switch (constraint[0]) {5070 return switch (constraint[0]) {
4999 '{' => true,5071 '{' => true,
5000 'i', 'r' => false,5072 'i', 'r' => false,
5001 'I' => !target.cpu.arch.isArmOrThumb(),5073 'I' => !target.cpu.arch.isArmOrThumb(),
5002 else => switch (value) {5074 else => switch (value) {
5003 .constant => |val| switch (f.object.dg.module.intern_pool.indexToKey(val)) {5075 .constant => |val| switch (f.object.dg.zcu.intern_pool.indexToKey(val.toIntern())) {
5004 .ptr => |ptr| switch (ptr.addr) {5076 .ptr => |ptr| switch (ptr.addr) {
5005 .decl => false,5077 .decl => false,
5006 else => true,5078 else => true,
...@@ -5013,7 +5085,7 @@ fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool...@@ -5013,7 +5085,7 @@ fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool
5013}5085}
50145086
5015fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {5087fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
5016 const mod = f.object.dg.module;5088 const zcu = f.object.dg.zcu;
5017 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;5089 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
5018 const extra = f.air.extraData(Air.Asm, ty_pl.payload);5090 const extra = f.air.extraData(Air.Asm, ty_pl.payload);
5019 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;5091 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;
...@@ -5028,7 +5100,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5028,7 +5100,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
5028 const result = result: {5100 const result = result: {
5029 const writer = f.object.writer();5101 const writer = f.object.writer();
5030 const inst_ty = f.typeOfIndex(inst);5102 const inst_ty = f.typeOfIndex(inst);
5031 const local = if (inst_ty.hasRuntimeBitsIgnoreComptime(mod)) local: {5103 const local = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) local: {
5032 const local = try f.allocLocal(inst, inst_ty);5104 const local = try f.allocLocal(inst, inst_ty);
5033 if (f.wantSafety()) {5105 if (f.wantSafety()) {
5034 try f.writeCValue(writer, local, .Other);5106 try f.writeCValue(writer, local, .Other);
...@@ -5057,7 +5129,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5057,7 +5129,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50575129
5058 const is_reg = constraint[1] == '{';5130 const is_reg = constraint[1] == '{';
5059 if (is_reg) {5131 if (is_reg) {
5060 const output_ty = if (output == .none) inst_ty else f.typeOf(output).childType(mod);5132 const output_ty = if (output == .none) inst_ty else f.typeOf(output).childType(zcu);
5061 try writer.writeAll("register ");5133 try writer.writeAll("register ");
5062 const alignment: Alignment = .none;5134 const alignment: Alignment = .none;
5063 const local_value = try f.allocLocalValue(output_ty, alignment);5135 const local_value = try f.allocLocalValue(output_ty, alignment);
...@@ -5275,7 +5347,7 @@ fn airIsNull(...@@ -5275,7 +5347,7 @@ fn airIsNull(
5275 operator: []const u8,5347 operator: []const u8,
5276 is_ptr: bool,5348 is_ptr: bool,
5277) !CValue {5349) !CValue {
5278 const mod = f.object.dg.module;5350 const zcu = f.object.dg.zcu;
5279 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;5351 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
52805352
5281 const writer = f.object.writer();5353 const writer = f.object.writer();
...@@ -5292,22 +5364,22 @@ fn airIsNull(...@@ -5292,22 +5364,22 @@ fn airIsNull(
5292 }5364 }
52935365
5294 const operand_ty = f.typeOf(un_op);5366 const operand_ty = f.typeOf(un_op);
5295 const optional_ty = if (is_ptr) operand_ty.childType(mod) else operand_ty;5367 const optional_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
5296 const payload_ty = optional_ty.optionalChild(mod);5368 const payload_ty = optional_ty.optionalChild(zcu);
5297 const err_int_ty = try mod.errorIntType();5369 const err_int_ty = try zcu.errorIntType();
52985370
5299 const rhs = if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod))5371 const rhs = if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu))
5300 Value.true5372 Value.true
5301 else if (optional_ty.isPtrLikeOptional(mod))5373 else if (optional_ty.isPtrLikeOptional(zcu))
5302 // operand is a regular pointer, test `operand !=/== NULL`5374 // operand is a regular pointer, test `operand !=/== NULL`
5303 try mod.getCoerced(Value.null, optional_ty)5375 try zcu.getCoerced(Value.null, optional_ty)
5304 else if (payload_ty.zigTypeTag(mod) == .ErrorSet)5376 else if (payload_ty.zigTypeTag(zcu) == .ErrorSet)
5305 try mod.intValue(err_int_ty, 0)5377 try zcu.intValue(err_int_ty, 0)
5306 else if (payload_ty.isSlice(mod) and optional_ty.optionalReprIsPayload(mod)) rhs: {5378 else if (payload_ty.isSlice(zcu) and optional_ty.optionalReprIsPayload(zcu)) rhs: {
5307 try writer.writeAll(".ptr");5379 try writer.writeAll(".ptr");
5308 const slice_ptr_ty = payload_ty.slicePtrFieldType(mod);5380 const slice_ptr_ty = payload_ty.slicePtrFieldType(zcu);
5309 const opt_slice_ptr_ty = try mod.optionalType(slice_ptr_ty.toIntern());5381 const opt_slice_ptr_ty = try zcu.optionalType(slice_ptr_ty.toIntern());
5310 break :rhs try mod.nullValue(opt_slice_ptr_ty);5382 break :rhs try zcu.nullValue(opt_slice_ptr_ty);
5311 } else rhs: {5383 } else rhs: {
5312 try writer.writeAll(".is_null");5384 try writer.writeAll(".is_null");
5313 break :rhs Value.true;5385 break :rhs Value.true;
...@@ -5315,22 +5387,22 @@ fn airIsNull(...@@ -5315,22 +5387,22 @@ fn airIsNull(
5315 try writer.writeByte(' ');5387 try writer.writeByte(' ');
5316 try writer.writeAll(operator);5388 try writer.writeAll(operator);
5317 try writer.writeByte(' ');5389 try writer.writeByte(' ');
5318 try f.object.dg.renderValue(writer, rhs.typeOf(mod), rhs, .Other);5390 try f.object.dg.renderValue(writer, rhs, .Other);
5319 try writer.writeAll(";\n");5391 try writer.writeAll(";\n");
5320 return local;5392 return local;
5321}5393}
53225394
5323fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {5395fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
5324 const mod = f.object.dg.module;5396 const zcu = f.object.dg.zcu;
5325 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5397 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53265398
5327 const operand = try f.resolveInst(ty_op.operand);5399 const operand = try f.resolveInst(ty_op.operand);
5328 try reap(f, inst, &.{ty_op.operand});5400 try reap(f, inst, &.{ty_op.operand});
5329 const opt_ty = f.typeOf(ty_op.operand);5401 const opt_ty = f.typeOf(ty_op.operand);
53305402
5331 const payload_ty = opt_ty.optionalChild(mod);5403 const payload_ty = opt_ty.optionalChild(zcu);
53325404
5333 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {5405 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5334 return .none;5406 return .none;
5335 }5407 }
53365408
...@@ -5338,7 +5410,7 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5338,7 +5410,7 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
5338 const writer = f.object.writer();5410 const writer = f.object.writer();
5339 const local = try f.allocLocal(inst, inst_ty);5411 const local = try f.allocLocal(inst, inst_ty);
53405412
5341 if (opt_ty.optionalReprIsPayload(mod)) {5413 if (opt_ty.optionalReprIsPayload(zcu)) {
5342 try f.writeCValue(writer, local, .Other);5414 try f.writeCValue(writer, local, .Other);
5343 try writer.writeAll(" = ");5415 try writer.writeAll(" = ");
5344 try f.writeCValue(writer, operand, .Other);5416 try f.writeCValue(writer, operand, .Other);
...@@ -5355,24 +5427,24 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5355,24 +5427,24 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
5355}5427}
53565428
5357fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {5429fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5358 const mod = f.object.dg.module;5430 const zcu = f.object.dg.zcu;
5359 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5431 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53605432
5361 const writer = f.object.writer();5433 const writer = f.object.writer();
5362 const operand = try f.resolveInst(ty_op.operand);5434 const operand = try f.resolveInst(ty_op.operand);
5363 try reap(f, inst, &.{ty_op.operand});5435 try reap(f, inst, &.{ty_op.operand});
5364 const ptr_ty = f.typeOf(ty_op.operand);5436 const ptr_ty = f.typeOf(ty_op.operand);
5365 const opt_ty = ptr_ty.childType(mod);5437 const opt_ty = ptr_ty.childType(zcu);
5366 const inst_ty = f.typeOfIndex(inst);5438 const inst_ty = f.typeOfIndex(inst);
53675439
5368 if (!inst_ty.childType(mod).hasRuntimeBitsIgnoreComptime(mod)) {5440 if (!inst_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu)) {
5369 return .{ .undef = inst_ty };5441 return .{ .undef = inst_ty };
5370 }5442 }
53715443
5372 const local = try f.allocLocal(inst, inst_ty);5444 const local = try f.allocLocal(inst, inst_ty);
5373 try f.writeCValue(writer, local, .Other);5445 try f.writeCValue(writer, local, .Other);
53745446
5375 if (opt_ty.optionalReprIsPayload(mod)) {5447 if (opt_ty.optionalReprIsPayload(zcu)) {
5376 // the operand is just a regular pointer, no need to do anything special.5448 // the operand is just a regular pointer, no need to do anything special.
5377 // *?*T -> **T and ?*T -> *T are **T -> **T and *T -> *T in C5449 // *?*T -> **T and ?*T -> *T are **T -> **T and *T -> *T in C
5378 try writer.writeAll(" = ");5450 try writer.writeAll(" = ");
...@@ -5386,18 +5458,18 @@ fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5386,18 +5458,18 @@ fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5386}5458}
53875459
5388fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {5460fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5389 const mod = f.object.dg.module;5461 const zcu = f.object.dg.zcu;
5390 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5462 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
5391 const writer = f.object.writer();5463 const writer = f.object.writer();
5392 const operand = try f.resolveInst(ty_op.operand);5464 const operand = try f.resolveInst(ty_op.operand);
5393 try reap(f, inst, &.{ty_op.operand});5465 try reap(f, inst, &.{ty_op.operand});
5394 const operand_ty = f.typeOf(ty_op.operand);5466 const operand_ty = f.typeOf(ty_op.operand);
53955467
5396 const opt_ty = operand_ty.childType(mod);5468 const opt_ty = operand_ty.childType(zcu);
53975469
5398 const inst_ty = f.typeOfIndex(inst);5470 const inst_ty = f.typeOfIndex(inst);
53995471
5400 if (opt_ty.optionalReprIsPayload(mod)) {5472 if (opt_ty.optionalReprIsPayload(zcu)) {
5401 if (f.liveness.isUnused(inst)) {5473 if (f.liveness.isUnused(inst)) {
5402 return .none;5474 return .none;
5403 }5475 }
...@@ -5412,7 +5484,7 @@ fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5412,7 +5484,7 @@ fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5412 } else {5484 } else {
5413 try f.writeCValueDeref(writer, operand);5485 try f.writeCValueDeref(writer, operand);
5414 try writer.writeAll(".is_null = ");5486 try writer.writeAll(".is_null = ");
5415 try f.object.dg.renderValue(writer, Type.bool, Value.false, .Initializer);5487 try f.object.dg.renderValue(writer, Value.false, .Initializer);
5416 try writer.writeAll(";\n");5488 try writer.writeAll(";\n");
54175489
5418 if (f.liveness.isUnused(inst)) {5490 if (f.liveness.isUnused(inst)) {
...@@ -5432,50 +5504,50 @@ fn fieldLocation(...@@ -5432,50 +5504,50 @@ fn fieldLocation(
5432 container_ptr_ty: Type,5504 container_ptr_ty: Type,
5433 field_ptr_ty: Type,5505 field_ptr_ty: Type,
5434 field_index: u32,5506 field_index: u32,
5435 mod: *Module,5507 zcu: *Zcu,
5436) union(enum) {5508) union(enum) {
5437 begin: void,5509 begin: void,
5438 field: CValue,5510 field: CValue,
5439 byte_offset: u32,5511 byte_offset: u32,
5440 end: void,5512 end: void,
5441} {5513} {
5442 const ip = &mod.intern_pool;5514 const ip = &zcu.intern_pool;
5443 const container_ty = container_ptr_ty.childType(mod);5515 const container_ty = container_ptr_ty.childType(zcu);
5444 return switch (container_ty.zigTypeTag(mod)) {5516 return switch (container_ty.zigTypeTag(zcu)) {
5445 .Struct => blk: {5517 .Struct => blk: {
5446 if (mod.typeToPackedStruct(container_ty)) |struct_type| {5518 if (zcu.typeToPackedStruct(container_ty)) |struct_type| {
5447 if (field_ptr_ty.ptrInfo(mod).packed_offset.host_size == 0)5519 if (field_ptr_ty.ptrInfo(zcu).packed_offset.host_size == 0)
5448 break :blk .{ .byte_offset = @divExact(mod.structPackedFieldBitOffset(struct_type, field_index) + container_ptr_ty.ptrInfo(mod).packed_offset.bit_offset, 8) }5520 break :blk .{ .byte_offset = @divExact(zcu.structPackedFieldBitOffset(struct_type, field_index) + container_ptr_ty.ptrInfo(zcu).packed_offset.bit_offset, 8) }
5449 else5521 else
5450 break :blk .begin;5522 break :blk .begin;
5451 }5523 }
54525524
5453 for (field_index..container_ty.structFieldCount(mod)) |next_field_index_usize| {5525 for (field_index..container_ty.structFieldCount(zcu)) |next_field_index_usize| {
5454 const next_field_index: u32 = @intCast(next_field_index_usize);5526 const next_field_index: u32 = @intCast(next_field_index_usize);
5455 if (container_ty.structFieldIsComptime(next_field_index, mod)) continue;5527 if (container_ty.structFieldIsComptime(next_field_index, zcu)) continue;
5456 const field_ty = container_ty.structFieldType(next_field_index, mod);5528 const field_ty = container_ty.structFieldType(next_field_index, zcu);
5457 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;5529 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
54585530
5459 break :blk .{ .field = if (container_ty.isSimpleTuple(mod))5531 break :blk .{ .field = if (container_ty.isSimpleTuple(zcu))
5460 .{ .field = next_field_index }5532 .{ .field = next_field_index }
5461 else5533 else
5462 .{ .identifier = ip.stringToSlice(container_ty.legacyStructFieldName(next_field_index, mod)) } };5534 .{ .identifier = ip.stringToSlice(container_ty.legacyStructFieldName(next_field_index, zcu)) } };
5463 }5535 }
5464 break :blk if (container_ty.hasRuntimeBitsIgnoreComptime(mod)) .end else .begin;5536 break :blk if (container_ty.hasRuntimeBitsIgnoreComptime(zcu)) .end else .begin;
5465 },5537 },
5466 .Union => {5538 .Union => {
5467 const union_obj = mod.typeToUnion(container_ty).?;5539 const union_obj = zcu.typeToUnion(container_ty).?;
5468 return switch (union_obj.getLayout(ip)) {5540 return switch (union_obj.getLayout(ip)) {
5469 .auto, .@"extern" => {5541 .auto, .@"extern" => {
5470 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);5542 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
5471 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod))5543 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu))
5472 return if (container_ty.unionTagTypeSafety(mod) != null and5544 return if (container_ty.unionTagTypeSafety(zcu) != null and
5473 !container_ty.unionHasAllZeroBitFieldTypes(mod))5545 !container_ty.unionHasAllZeroBitFieldTypes(zcu))
5474 .{ .field = .{ .identifier = "payload" } }5546 .{ .field = .{ .identifier = "payload" } }
5475 else5547 else
5476 .begin;5548 .begin;
5477 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];5549 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];
5478 return .{ .field = if (container_ty.unionTagTypeSafety(mod)) |_|5550 return .{ .field = if (container_ty.unionTagTypeSafety(zcu)) |_|
5479 .{ .payload_identifier = ip.stringToSlice(field_name) }5551 .{ .payload_identifier = ip.stringToSlice(field_name) }
5480 else5552 else
5481 .{ .identifier = ip.stringToSlice(field_name) } };5553 .{ .identifier = ip.stringToSlice(field_name) } };
...@@ -5483,7 +5555,7 @@ fn fieldLocation(...@@ -5483,7 +5555,7 @@ fn fieldLocation(
5483 .@"packed" => .begin,5555 .@"packed" => .begin,
5484 };5556 };
5485 },5557 },
5486 .Pointer => switch (container_ty.ptrSize(mod)) {5558 .Pointer => switch (container_ty.ptrSize(zcu)) {
5487 .Slice => switch (field_index) {5559 .Slice => switch (field_index) {
5488 0 => .{ .field = .{ .identifier = "ptr" } },5560 0 => .{ .field = .{ .identifier = "ptr" } },
5489 1 => .{ .field = .{ .identifier = "len" } },5561 1 => .{ .field = .{ .identifier = "len" } },
...@@ -5515,12 +5587,12 @@ fn airStructFieldPtrIndex(f: *Function, inst: Air.Inst.Index, index: u8) !CValue...@@ -5515,12 +5587,12 @@ fn airStructFieldPtrIndex(f: *Function, inst: Air.Inst.Index, index: u8) !CValue
5515}5587}
55165588
5517fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {5589fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5518 const mod = f.object.dg.module;5590 const zcu = f.object.dg.zcu;
5519 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;5591 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
5520 const extra = f.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;5592 const extra = f.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
55215593
5522 const container_ptr_ty = f.typeOfIndex(inst);5594 const container_ptr_ty = f.typeOfIndex(inst);
5523 const container_ty = container_ptr_ty.childType(mod);5595 const container_ty = container_ptr_ty.childType(zcu);
55245596
5525 const field_ptr_ty = f.typeOf(extra.field_ptr);5597 const field_ptr_ty = f.typeOf(extra.field_ptr);
5526 const field_ptr_val = try f.resolveInst(extra.field_ptr);5598 const field_ptr_val = try f.resolveInst(extra.field_ptr);
...@@ -5533,10 +5605,10 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5533,10 +5605,10 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5533 try f.renderType(writer, container_ptr_ty);5605 try f.renderType(writer, container_ptr_ty);
5534 try writer.writeByte(')');5606 try writer.writeByte(')');
55355607
5536 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, mod)) {5608 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, zcu)) {
5537 .begin => try f.writeCValue(writer, field_ptr_val, .Initializer),5609 .begin => try f.writeCValue(writer, field_ptr_val, .Initializer),
5538 .field => |field| {5610 .field => |field| {
5539 const u8_ptr_ty = try mod.adjustPtrTypeChild(field_ptr_ty, Type.u8);5611 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55405612
5541 try writer.writeAll("((");5613 try writer.writeAll("((");
5542 try f.renderType(writer, u8_ptr_ty);5614 try f.renderType(writer, u8_ptr_ty);
...@@ -5549,19 +5621,19 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5549,19 +5621,19 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5549 try writer.writeAll("))");5621 try writer.writeAll("))");
5550 },5622 },
5551 .byte_offset => |byte_offset| {5623 .byte_offset => |byte_offset| {
5552 const u8_ptr_ty = try mod.adjustPtrTypeChild(field_ptr_ty, Type.u8);5624 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5553
5554 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);
55555625
5556 try writer.writeAll("((");5626 try writer.writeAll("((");
5557 try f.renderType(writer, u8_ptr_ty);5627 try f.renderType(writer, u8_ptr_ty);
5558 try writer.writeByte(')');5628 try writer.writeByte(')');
5559 try f.writeCValue(writer, field_ptr_val, .Other);5629 try f.writeCValue(writer, field_ptr_val, .Other);
5560 try writer.print(" - {})", .{try f.fmtIntLiteral(Type.usize, byte_offset_val)});5630 try writer.print(" - {})", .{
5631 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5632 });
5561 },5633 },
5562 .end => {5634 .end => {
5563 try f.writeCValue(writer, field_ptr_val, .Other);5635 try f.writeCValue(writer, field_ptr_val, .Other);
5564 try writer.print(" - {}", .{try f.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 1))});5636 try writer.print(" - {}", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 1))});
5565 },5637 },
5566 }5638 }
55675639
...@@ -5576,8 +5648,8 @@ fn fieldPtr(...@@ -5576,8 +5648,8 @@ fn fieldPtr(
5576 container_ptr_val: CValue,5648 container_ptr_val: CValue,
5577 field_index: u32,5649 field_index: u32,
5578) !CValue {5650) !CValue {
5579 const mod = f.object.dg.module;5651 const zcu = f.object.dg.zcu;
5580 const container_ty = container_ptr_ty.childType(mod);5652 const container_ty = container_ptr_ty.childType(zcu);
5581 const field_ptr_ty = f.typeOfIndex(inst);5653 const field_ptr_ty = f.typeOfIndex(inst);
55825654
5583 // Ensure complete type definition is visible before accessing fields.5655 // Ensure complete type definition is visible before accessing fields.
...@@ -5590,27 +5662,27 @@ fn fieldPtr(...@@ -5590,27 +5662,27 @@ fn fieldPtr(
5590 try f.renderType(writer, field_ptr_ty);5662 try f.renderType(writer, field_ptr_ty);
5591 try writer.writeByte(')');5663 try writer.writeByte(')');
55925664
5593 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, mod)) {5665 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, zcu)) {
5594 .begin => try f.writeCValue(writer, container_ptr_val, .Initializer),5666 .begin => try f.writeCValue(writer, container_ptr_val, .Initializer),
5595 .field => |field| {5667 .field => |field| {
5596 try writer.writeByte('&');5668 try writer.writeByte('&');
5597 try f.writeCValueDerefMember(writer, container_ptr_val, field);5669 try f.writeCValueDerefMember(writer, container_ptr_val, field);
5598 },5670 },
5599 .byte_offset => |byte_offset| {5671 .byte_offset => |byte_offset| {
5600 const u8_ptr_ty = try mod.adjustPtrTypeChild(field_ptr_ty, Type.u8);5672 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5601
5602 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);
56035673
5604 try writer.writeAll("((");5674 try writer.writeAll("((");
5605 try f.renderType(writer, u8_ptr_ty);5675 try f.renderType(writer, u8_ptr_ty);
5606 try writer.writeByte(')');5676 try writer.writeByte(')');
5607 try f.writeCValue(writer, container_ptr_val, .Other);5677 try f.writeCValue(writer, container_ptr_val, .Other);
5608 try writer.print(" + {})", .{try f.fmtIntLiteral(Type.usize, byte_offset_val)});5678 try writer.print(" + {})", .{
5679 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5680 });
5609 },5681 },
5610 .end => {5682 .end => {
5611 try writer.writeByte('(');5683 try writer.writeByte('(');
5612 try f.writeCValue(writer, container_ptr_val, .Other);5684 try f.writeCValue(writer, container_ptr_val, .Other);
5613 try writer.print(" + {})", .{try f.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 1))});5685 try writer.print(" + {})", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 1))});
5614 },5686 },
5615 }5687 }
56165688
...@@ -5619,13 +5691,13 @@ fn fieldPtr(...@@ -5619,13 +5691,13 @@ fn fieldPtr(
5619}5691}
56205692
5621fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {5693fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5622 const mod = f.object.dg.module;5694 const zcu = f.object.dg.zcu;
5623 const ip = &mod.intern_pool;5695 const ip = &zcu.intern_pool;
5624 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;5696 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
5625 const extra = f.air.extraData(Air.StructField, ty_pl.payload).data;5697 const extra = f.air.extraData(Air.StructField, ty_pl.payload).data;
56265698
5627 const inst_ty = f.typeOfIndex(inst);5699 const inst_ty = f.typeOfIndex(inst);
5628 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {5700 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5629 try reap(f, inst, &.{extra.struct_operand});5701 try reap(f, inst, &.{extra.struct_operand});
5630 return .none;5702 return .none;
5631 }5703 }
...@@ -5638,26 +5710,25 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5638,26 +5710,25 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5638 // Ensure complete type definition is visible before accessing fields.5710 // Ensure complete type definition is visible before accessing fields.
5639 _ = try f.typeToIndex(struct_ty, .complete);5711 _ = try f.typeToIndex(struct_ty, .complete);
56405712
5641 const field_name: CValue = switch (mod.intern_pool.indexToKey(struct_ty.ip_index)) {5713 const field_name: CValue = switch (zcu.intern_pool.indexToKey(struct_ty.toIntern())) {
5642 .struct_type => switch (struct_ty.containerLayout(mod)) {5714 .struct_type => switch (struct_ty.containerLayout(zcu)) {
5643 .auto, .@"extern" => if (struct_ty.isSimpleTuple(mod))5715 .auto, .@"extern" => if (struct_ty.isSimpleTuple(zcu))
5644 .{ .field = extra.field_index }5716 .{ .field = extra.field_index }
5645 else5717 else
5646 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, mod)) },5718 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, zcu)) },
5647 .@"packed" => {5719 .@"packed" => {
5648 const struct_type = mod.typeToStruct(struct_ty).?;5720 const struct_type = zcu.typeToStruct(struct_ty).?;
5649 const int_info = struct_ty.intInfo(mod);5721 const int_info = struct_ty.intInfo(zcu);
56505722
5651 const bit_offset_ty = try mod.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));5723 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
56525724
5653 const bit_offset = mod.structPackedFieldBitOffset(struct_type, extra.field_index);5725 const bit_offset = zcu.structPackedFieldBitOffset(struct_type, extra.field_index);
5654 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);
56555726
5656 const field_int_signedness = if (inst_ty.isAbiInt(mod))5727 const field_int_signedness = if (inst_ty.isAbiInt(zcu))
5657 inst_ty.intInfo(mod).signedness5728 inst_ty.intInfo(zcu).signedness
5658 else5729 else
5659 .unsigned;5730 .unsigned;
5660 const field_int_ty = try mod.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(mod))));5731 const field_int_ty = try zcu.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(zcu))));
56615732
5662 const temp_local = try f.allocLocal(inst, field_int_ty);5733 const temp_local = try f.allocLocal(inst, field_int_ty);
5663 try f.writeCValue(writer, temp_local, .Other);5734 try f.writeCValue(writer, temp_local, .Other);
...@@ -5668,7 +5739,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5668,7 +5739,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5668 try writer.writeByte(')');5739 try writer.writeByte(')');
5669 const cant_cast = int_info.bits > 64;5740 const cant_cast = int_info.bits > 64;
5670 if (cant_cast) {5741 if (cant_cast) {
5671 if (field_int_ty.bitSize(mod) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});5742 if (field_int_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
5672 try writer.writeAll("zig_lo_");5743 try writer.writeAll("zig_lo_");
5673 try f.object.dg.renderTypeForBuiltinFnName(writer, struct_ty);5744 try f.object.dg.renderTypeForBuiltinFnName(writer, struct_ty);
5674 try writer.writeByte('(');5745 try writer.writeByte('(');
...@@ -5681,13 +5752,13 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5681,13 +5752,13 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5681 try f.writeCValue(writer, struct_byval, .Other);5752 try f.writeCValue(writer, struct_byval, .Other);
5682 if (bit_offset > 0) {5753 if (bit_offset > 0) {
5683 try writer.writeAll(", ");5754 try writer.writeAll(", ");
5684 try f.object.dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);5755 try f.object.dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
5685 try writer.writeByte(')');5756 try writer.writeByte(')');
5686 }5757 }
5687 if (cant_cast) try writer.writeByte(')');5758 if (cant_cast) try writer.writeByte(')');
5688 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);5759 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);
5689 try writer.writeAll(");\n");5760 try writer.writeAll(");\n");
5690 if (inst_ty.eql(field_int_ty, f.object.dg.module)) return temp_local;5761 if (inst_ty.eql(field_int_ty, f.object.dg.zcu)) return temp_local;
56915762
5692 const local = try f.allocLocal(inst, inst_ty);5763 const local = try f.allocLocal(inst, inst_ty);
5693 try writer.writeAll("memcpy(");5764 try writer.writeAll("memcpy(");
...@@ -5705,7 +5776,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5705,7 +5776,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5705 .anon_struct_type => |anon_struct_type| if (anon_struct_type.names.len == 0)5776 .anon_struct_type => |anon_struct_type| if (anon_struct_type.names.len == 0)
5706 .{ .field = extra.field_index }5777 .{ .field = extra.field_index }
5707 else5778 else
5708 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, mod)) },5779 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, zcu)) },
57095780
5710 .union_type => field_name: {5781 .union_type => field_name: {
5711 const union_obj = ip.loadUnionType(struct_ty.toIntern());5782 const union_obj = ip.loadUnionType(struct_ty.toIntern());
...@@ -5757,7 +5828,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5757,7 +5828,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5757/// *(E!T) -> E5828/// *(E!T) -> E
5758/// Note that the result is never a pointer.5829/// Note that the result is never a pointer.
5759fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {5830fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5760 const mod = f.object.dg.module;5831 const zcu = f.object.dg.zcu;
5761 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5832 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57625833
5763 const inst_ty = f.typeOfIndex(inst);5834 const inst_ty = f.typeOfIndex(inst);
...@@ -5765,13 +5836,13 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5765,13 +5836,13 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5765 const operand_ty = f.typeOf(ty_op.operand);5836 const operand_ty = f.typeOf(ty_op.operand);
5766 try reap(f, inst, &.{ty_op.operand});5837 try reap(f, inst, &.{ty_op.operand});
57675838
5768 const operand_is_ptr = operand_ty.zigTypeTag(mod) == .Pointer;5839 const operand_is_ptr = operand_ty.zigTypeTag(zcu) == .Pointer;
5769 const error_union_ty = if (operand_is_ptr) operand_ty.childType(mod) else operand_ty;5840 const error_union_ty = if (operand_is_ptr) operand_ty.childType(zcu) else operand_ty;
5770 const error_ty = error_union_ty.errorUnionSet(mod);5841 const error_ty = error_union_ty.errorUnionSet(zcu);
5771 const payload_ty = error_union_ty.errorUnionPayload(mod);5842 const payload_ty = error_union_ty.errorUnionPayload(zcu);
5772 const local = try f.allocLocal(inst, inst_ty);5843 const local = try f.allocLocal(inst, inst_ty);
57735844
5774 if (!payload_ty.hasRuntimeBits(mod) and operand == .local and operand.local == local.new_local) {5845 if (!payload_ty.hasRuntimeBits(zcu) and operand == .local and operand.local == local.new_local) {
5775 // The store will be 'x = x'; elide it.5846 // The store will be 'x = x'; elide it.
5776 return local;5847 return local;
5777 }5848 }
...@@ -5780,35 +5851,32 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5780,35 +5851,32 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5780 try f.writeCValue(writer, local, .Other);5851 try f.writeCValue(writer, local, .Other);
5781 try writer.writeAll(" = ");5852 try writer.writeAll(" = ");
57825853
5783 if (!payload_ty.hasRuntimeBits(mod)) {5854 if (!payload_ty.hasRuntimeBits(zcu))
5784 try f.writeCValue(writer, operand, .Other);5855 try f.writeCValue(writer, operand, .Other)
5785 } else {5856 else if (error_ty.errorSetIsEmpty(zcu))
5786 if (!error_ty.errorSetIsEmpty(mod))5857 try writer.print("{}", .{
5787 if (operand_is_ptr)5858 try f.fmtIntLiteral(try zcu.intValue(try zcu.errorIntType(), 0)),
5788 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })5859 })
5789 else5860 else if (operand_is_ptr)
5790 try f.writeCValueMember(writer, operand, .{ .identifier = "error" })5861 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
5791 else {5862 else
5792 const err_int_ty = try mod.errorIntType();5863 try f.writeCValueMember(writer, operand, .{ .identifier = "error" });
5793 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Initializer);
5794 }
5795 }
5796 try writer.writeAll(";\n");5864 try writer.writeAll(";\n");
5797 return local;5865 return local;
5798}5866}
57995867
5800fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {5868fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
5801 const mod = f.object.dg.module;5869 const zcu = f.object.dg.zcu;
5802 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5870 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58035871
5804 const inst_ty = f.typeOfIndex(inst);5872 const inst_ty = f.typeOfIndex(inst);
5805 const operand = try f.resolveInst(ty_op.operand);5873 const operand = try f.resolveInst(ty_op.operand);
5806 try reap(f, inst, &.{ty_op.operand});5874 try reap(f, inst, &.{ty_op.operand});
5807 const operand_ty = f.typeOf(ty_op.operand);5875 const operand_ty = f.typeOf(ty_op.operand);
5808 const error_union_ty = if (is_ptr) operand_ty.childType(mod) else operand_ty;5876 const error_union_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
58095877
5810 const writer = f.object.writer();5878 const writer = f.object.writer();
5811 if (!error_union_ty.errorUnionPayload(mod).hasRuntimeBits(mod)) {5879 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(zcu)) {
5812 if (!is_ptr) return .none;5880 if (!is_ptr) return .none;
58135881
5814 const local = try f.allocLocal(inst, inst_ty);5882 const local = try f.allocLocal(inst, inst_ty);
...@@ -5834,11 +5902,11 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValu...@@ -5834,11 +5902,11 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValu
5834}5902}
58355903
5836fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {5904fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
5837 const mod = f.object.dg.module;5905 const zcu = f.object.dg.zcu;
5838 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5906 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58395907
5840 const inst_ty = f.typeOfIndex(inst);5908 const inst_ty = f.typeOfIndex(inst);
5841 const repr_is_payload = inst_ty.optionalReprIsPayload(mod);5909 const repr_is_payload = inst_ty.optionalReprIsPayload(zcu);
5842 const payload_ty = f.typeOf(ty_op.operand);5910 const payload_ty = f.typeOf(ty_op.operand);
5843 const payload = try f.resolveInst(ty_op.operand);5911 const payload = try f.resolveInst(ty_op.operand);
5844 try reap(f, inst, &.{ty_op.operand});5912 try reap(f, inst, &.{ty_op.operand});
...@@ -5859,20 +5927,20 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5859,20 +5927,20 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
5859 const a = try Assignment.start(f, writer, Type.bool);5927 const a = try Assignment.start(f, writer, Type.bool);
5860 try f.writeCValueMember(writer, local, .{ .identifier = "is_null" });5928 try f.writeCValueMember(writer, local, .{ .identifier = "is_null" });
5861 try a.assign(f, writer);5929 try a.assign(f, writer);
5862 try f.object.dg.renderValue(writer, Type.bool, Value.false, .Other);5930 try f.object.dg.renderValue(writer, Value.false, .Other);
5863 try a.end(f, writer);5931 try a.end(f, writer);
5864 }5932 }
5865 return local;5933 return local;
5866}5934}
58675935
5868fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {5936fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5869 const mod = f.object.dg.module;5937 const zcu = f.object.dg.zcu;
5870 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5938 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58715939
5872 const inst_ty = f.typeOfIndex(inst);5940 const inst_ty = f.typeOfIndex(inst);
5873 const payload_ty = inst_ty.errorUnionPayload(mod);5941 const payload_ty = inst_ty.errorUnionPayload(zcu);
5874 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(mod);5942 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
5875 const err_ty = inst_ty.errorUnionSet(mod);5943 const err_ty = inst_ty.errorUnionSet(zcu);
5876 const err = try f.resolveInst(ty_op.operand);5944 const err = try f.resolveInst(ty_op.operand);
5877 try reap(f, inst, &.{ty_op.operand});5945 try reap(f, inst, &.{ty_op.operand});
58785946
...@@ -5888,7 +5956,7 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5888,7 +5956,7 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5888 const a = try Assignment.start(f, writer, payload_ty);5956 const a = try Assignment.start(f, writer, payload_ty);
5889 try f.writeCValueMember(writer, local, .{ .identifier = "payload" });5957 try f.writeCValueMember(writer, local, .{ .identifier = "payload" });
5890 try a.assign(f, writer);5958 try a.assign(f, writer);
5891 try f.object.dg.renderValue(writer, payload_ty, Value.undef, .Other);5959 try f.object.dg.renderUndefValue(writer, payload_ty, .Other);
5892 try a.end(f, writer);5960 try a.end(f, writer);
5893 }5961 }
5894 {5962 {
...@@ -5905,29 +5973,25 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5905,29 +5973,25 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5905}5973}
59065974
5907fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {5975fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5908 const mod = f.object.dg.module;5976 const zcu = f.object.dg.zcu;
5909 const writer = f.object.writer();5977 const writer = f.object.writer();
5910 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;5978 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
5911 const operand = try f.resolveInst(ty_op.operand);5979 const operand = try f.resolveInst(ty_op.operand);
5912 const error_union_ty = f.typeOf(ty_op.operand).childType(mod);5980 const error_union_ty = f.typeOf(ty_op.operand).childType(zcu);
59135981
5914 const payload_ty = error_union_ty.errorUnionPayload(mod);5982 const payload_ty = error_union_ty.errorUnionPayload(zcu);
5915 const err_int_ty = try mod.errorIntType();5983 const err_int_ty = try zcu.errorIntType();
5984 const no_err = try zcu.intValue(err_int_ty, 0);
59165985
5917 // First, set the non-error value.5986 // First, set the non-error value.
5918 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {5987 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5919 try f.writeCValueDeref(writer, operand);5988 try f.writeCValueDeref(writer, operand);
5920 try writer.writeAll(" = ");5989 try writer.print(" = {};\n", .{try f.fmtIntLiteral(no_err)});
5921 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
5922 try writer.writeAll(";\n ");
5923
5924 return operand;5990 return operand;
5925 }5991 }
5926 try reap(f, inst, &.{ty_op.operand});5992 try reap(f, inst, &.{ty_op.operand});
5927 try f.writeCValueDeref(writer, operand);5993 try f.writeCValueDeref(writer, operand);
5928 try writer.writeAll(".error = ");5994 try writer.print(".error = {};\n", .{try f.fmtIntLiteral(no_err)});
5929 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
5930 try writer.writeAll(";\n");
59315995
5932 // Then return the payload pointer (only if it is used)5996 // Then return the payload pointer (only if it is used)
5933 if (f.liveness.isUnused(inst)) return .none;5997 if (f.liveness.isUnused(inst)) return .none;
...@@ -5956,14 +6020,14 @@ fn airSaveErrReturnTraceIndex(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5956,14 +6020,14 @@ fn airSaveErrReturnTraceIndex(f: *Function, inst: Air.Inst.Index) !CValue {
5956}6020}
59576021
5958fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {6022fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
5959 const mod = f.object.dg.module;6023 const zcu = f.object.dg.zcu;
5960 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6024 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59616025
5962 const inst_ty = f.typeOfIndex(inst);6026 const inst_ty = f.typeOfIndex(inst);
5963 const payload_ty = inst_ty.errorUnionPayload(mod);6027 const payload_ty = inst_ty.errorUnionPayload(zcu);
5964 const payload = try f.resolveInst(ty_op.operand);6028 const payload = try f.resolveInst(ty_op.operand);
5965 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(mod);6029 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
5966 const err_ty = inst_ty.errorUnionSet(mod);6030 const err_ty = inst_ty.errorUnionSet(zcu);
5967 try reap(f, inst, &.{ty_op.operand});6031 try reap(f, inst, &.{ty_op.operand});
59686032
5969 const writer = f.object.writer();6033 const writer = f.object.writer();
...@@ -5982,15 +6046,14 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -5982,15 +6046,14 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
5982 else6046 else
5983 try f.writeCValueMember(writer, local, .{ .identifier = "error" });6047 try f.writeCValueMember(writer, local, .{ .identifier = "error" });
5984 try a.assign(f, writer);6048 try a.assign(f, writer);
5985 const err_int_ty = try mod.errorIntType();6049 try f.object.dg.renderValue(writer, try zcu.intValue(try zcu.errorIntType(), 0), .Other);
5986 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
5987 try a.end(f, writer);6050 try a.end(f, writer);
5988 }6051 }
5989 return local;6052 return local;
5990}6053}
59916054
5992fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const u8) !CValue {6055fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const u8) !CValue {
5993 const mod = f.object.dg.module;6056 const zcu = f.object.dg.zcu;
5994 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;6057 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
59956058
5996 const writer = f.object.writer();6059 const writer = f.object.writer();
...@@ -5998,16 +6061,16 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const...@@ -5998,16 +6061,16 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
5998 try reap(f, inst, &.{un_op});6061 try reap(f, inst, &.{un_op});
5999 const operand_ty = f.typeOf(un_op);6062 const operand_ty = f.typeOf(un_op);
6000 const local = try f.allocLocal(inst, Type.bool);6063 const local = try f.allocLocal(inst, Type.bool);
6001 const err_union_ty = if (is_ptr) operand_ty.childType(mod) else operand_ty;6064 const err_union_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
6002 const payload_ty = err_union_ty.errorUnionPayload(mod);6065 const payload_ty = err_union_ty.errorUnionPayload(zcu);
6003 const error_ty = err_union_ty.errorUnionSet(mod);6066 const error_ty = err_union_ty.errorUnionSet(zcu);
60046067
6068 const a = try Assignment.start(f, writer, Type.bool);
6005 try f.writeCValue(writer, local, .Other);6069 try f.writeCValue(writer, local, .Other);
6006 try writer.writeAll(" = ");6070 try a.assign(f, writer);
60076071 const err_int_ty = try zcu.errorIntType();
6008 const err_int_ty = try mod.errorIntType();6072 if (!error_ty.errorSetIsEmpty(zcu))
6009 if (!error_ty.errorSetIsEmpty(mod))6073 if (payload_ty.hasRuntimeBits(zcu))
6010 if (payload_ty.hasRuntimeBits(mod))
6011 if (is_ptr)6074 if (is_ptr)
6012 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })6075 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
6013 else6076 else
...@@ -6015,63 +6078,84 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const...@@ -6015,63 +6078,84 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
6015 else6078 else
6016 try f.writeCValue(writer, operand, .Other)6079 try f.writeCValue(writer, operand, .Other)
6017 else6080 else
6018 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);6081 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6019 try writer.writeByte(' ');6082 try writer.writeByte(' ');
6020 try writer.writeAll(operator);6083 try writer.writeAll(operator);
6021 try writer.writeByte(' ');6084 try writer.writeByte(' ');
6022 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);6085 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6023 try writer.writeAll(";\n");6086 try a.end(f, writer);
6024 return local;6087 return local;
6025}6088}
60266089
6027fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {6090fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
6028 const mod = f.object.dg.module;6091 const zcu = f.object.dg.zcu;
6029 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6092 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60306093
6031 const operand = try f.resolveInst(ty_op.operand);6094 const operand = try f.resolveInst(ty_op.operand);
6032 try reap(f, inst, &.{ty_op.operand});6095 try reap(f, inst, &.{ty_op.operand});
6033 const inst_ty = f.typeOfIndex(inst);6096 const inst_ty = f.typeOfIndex(inst);
6097 const ptr_ty = inst_ty.slicePtrFieldType(zcu);
6034 const writer = f.object.writer();6098 const writer = f.object.writer();
6035 const local = try f.allocLocal(inst, inst_ty);6099 const local = try f.allocLocal(inst, inst_ty);
6036 const array_ty = f.typeOf(ty_op.operand).childType(mod);6100 const operand_ty = f.typeOf(ty_op.operand);
60376101 const array_ty = operand_ty.childType(zcu);
6038 try f.writeCValueMember(writer, local, .{ .identifier = "ptr" });
6039 try writer.writeAll(" = ");
6040 // Unfortunately, C does not support any equivalent to
6041 // &(*(void *)p)[0], although LLVM does via GetElementPtr
6042 if (operand == .undef) {
6043 try f.writeCValue(writer, .{ .undef = inst_ty.slicePtrFieldType(mod) }, .Initializer);
6044 } else if (array_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6045 try writer.writeAll("&(");
6046 try f.writeCValueDeref(writer, operand);
6047 try writer.print(")[{}]", .{try f.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 0))});
6048 } else try f.writeCValue(writer, operand, .Initializer);
6049 try writer.writeAll("; ");
60506102
6051 const len_val = try mod.intValue(Type.usize, array_ty.arrayLen(mod));6103 {
6052 try f.writeCValueMember(writer, local, .{ .identifier = "len" });6104 const a = try Assignment.start(f, writer, ptr_ty);
6053 try writer.print(" = {};\n", .{try f.fmtIntLiteral(Type.usize, len_val)});6105 try f.writeCValueMember(writer, local, .{ .identifier = "ptr" });
6106 try a.assign(f, writer);
6107 if (operand == .undef) {
6108 try f.writeCValue(writer, .{ .undef = inst_ty.slicePtrFieldType(zcu) }, .Initializer);
6109 } else {
6110 const ptr_cty = try f.typeToIndex(ptr_ty, .complete);
6111 const ptr_child_cty = f.indexToCType(ptr_cty).cast(CType.Payload.Child).?.data;
6112 const elem_ty = array_ty.childType(zcu);
6113 const elem_cty = try f.typeToIndex(elem_ty, .complete);
6114 if (ptr_child_cty != elem_cty) {
6115 try writer.writeByte('(');
6116 try f.renderCType(writer, ptr_cty);
6117 try writer.writeByte(')');
6118 }
6119 const operand_cty = try f.typeToCType(operand_ty, .complete);
6120 const operand_child_cty = operand_cty.cast(CType.Payload.Child).?.data;
6121 if (f.indexToCType(operand_child_cty).tag() == .array) {
6122 try writer.writeByte('&');
6123 try f.writeCValueDeref(writer, operand);
6124 try writer.print("[{}]", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
6125 } else try f.writeCValue(writer, operand, .Initializer);
6126 }
6127 try a.end(f, writer);
6128 }
6129 {
6130 const a = try Assignment.start(f, writer, Type.usize);
6131 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
6132 try a.assign(f, writer);
6133 try writer.print("{}", .{
6134 try f.fmtIntLiteral(try zcu.intValue(Type.usize, array_ty.arrayLen(zcu))),
6135 });
6136 try a.end(f, writer);
6137 }
60546138
6055 return local;6139 return local;
6056}6140}
60576141
6058fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {6142fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6059 const mod = f.object.dg.module;6143 const zcu = f.object.dg.zcu;
6060 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6144 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60616145
6062 const inst_ty = f.typeOfIndex(inst);6146 const inst_ty = f.typeOfIndex(inst);
6063 const inst_scalar_ty = inst_ty.scalarType(mod);6147 const inst_scalar_ty = inst_ty.scalarType(zcu);
6064 const operand = try f.resolveInst(ty_op.operand);6148 const operand = try f.resolveInst(ty_op.operand);
6065 try reap(f, inst, &.{ty_op.operand});6149 try reap(f, inst, &.{ty_op.operand});
6066 const operand_ty = f.typeOf(ty_op.operand);6150 const operand_ty = f.typeOf(ty_op.operand);
6067 const scalar_ty = operand_ty.scalarType(mod);6151 const scalar_ty = operand_ty.scalarType(zcu);
6068 const target = f.object.dg.module.getTarget();6152 const target = &f.object.dg.mod.resolved_target.result;
6069 const operation = if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isRuntimeFloat())6153 const operation = if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isRuntimeFloat())
6070 if (inst_scalar_ty.floatBits(target) < scalar_ty.floatBits(target)) "trunc" else "extend"6154 if (inst_scalar_ty.floatBits(target.*) < scalar_ty.floatBits(target.*)) "trunc" else "extend"
6071 else if (inst_scalar_ty.isInt(mod) and scalar_ty.isRuntimeFloat())6155 else if (inst_scalar_ty.isInt(zcu) and scalar_ty.isRuntimeFloat())
6072 if (inst_scalar_ty.isSignedInt(mod)) "fix" else "fixuns"6156 if (inst_scalar_ty.isSignedInt(zcu)) "fix" else "fixuns"
6073 else if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isInt(mod))6157 else if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isInt(zcu))
6074 if (scalar_ty.isSignedInt(mod)) "float" else "floatun"6158 if (scalar_ty.isSignedInt(zcu)) "float" else "floatun"
6075 else6159 else
6076 unreachable;6160 unreachable;
60776161
...@@ -6082,20 +6166,20 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6082,20 +6166,20 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6082 try f.writeCValue(writer, local, .Other);6166 try f.writeCValue(writer, local, .Other);
6083 try v.elem(f, writer);6167 try v.elem(f, writer);
6084 try a.assign(f, writer);6168 try a.assign(f, writer);
6085 if (inst_scalar_ty.isInt(mod) and scalar_ty.isRuntimeFloat()) {6169 if (inst_scalar_ty.isInt(zcu) and scalar_ty.isRuntimeFloat()) {
6086 try writer.writeAll("zig_wrap_");6170 try writer.writeAll("zig_wrap_");
6087 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_scalar_ty);6171 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_scalar_ty);
6088 try writer.writeByte('(');6172 try writer.writeByte('(');
6089 }6173 }
6090 try writer.writeAll("zig_");6174 try writer.writeAll("zig_");
6091 try writer.writeAll(operation);6175 try writer.writeAll(operation);
6092 try writer.writeAll(compilerRtAbbrev(scalar_ty, mod));6176 try writer.writeAll(compilerRtAbbrev(scalar_ty, zcu, target.*));
6093 try writer.writeAll(compilerRtAbbrev(inst_scalar_ty, mod));6177 try writer.writeAll(compilerRtAbbrev(inst_scalar_ty, zcu, target.*));
6094 try writer.writeByte('(');6178 try writer.writeByte('(');
6095 try f.writeCValue(writer, operand, .FunctionArgument);6179 try f.writeCValue(writer, operand, .FunctionArgument);
6096 try v.elem(f, writer);6180 try v.elem(f, writer);
6097 try writer.writeByte(')');6181 try writer.writeByte(')');
6098 if (inst_scalar_ty.isInt(mod) and scalar_ty.isRuntimeFloat()) {6182 if (inst_scalar_ty.isInt(zcu) and scalar_ty.isRuntimeFloat()) {
6099 try f.object.dg.renderBuiltinInfo(writer, inst_scalar_ty, .bits);6183 try f.object.dg.renderBuiltinInfo(writer, inst_scalar_ty, .bits);
6100 try writer.writeByte(')');6184 try writer.writeByte(')');
6101 }6185 }
...@@ -6106,7 +6190,7 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6106,7 +6190,7 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6106}6190}
61076191
6108fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {6192fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
6109 const mod = f.object.dg.module;6193 const zcu = f.object.dg.zcu;
6110 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;6194 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61116195
6112 const operand = try f.resolveInst(un_op);6196 const operand = try f.resolveInst(un_op);
...@@ -6120,7 +6204,7 @@ fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6120,7 +6204,7 @@ fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
6120 try writer.writeAll(" = (");6204 try writer.writeAll(" = (");
6121 try f.renderType(writer, inst_ty);6205 try f.renderType(writer, inst_ty);
6122 try writer.writeByte(')');6206 try writer.writeByte(')');
6123 if (operand_ty.isSlice(mod)) {6207 if (operand_ty.isSlice(zcu)) {
6124 try f.writeCValueMember(writer, operand, .{ .identifier = "ptr" });6208 try f.writeCValueMember(writer, operand, .{ .identifier = "ptr" });
6125 } else {6209 } else {
6126 try f.writeCValue(writer, operand, .Other);6210 try f.writeCValue(writer, operand, .Other);
...@@ -6135,15 +6219,15 @@ fn airUnBuiltinCall(...@@ -6135,15 +6219,15 @@ fn airUnBuiltinCall(
6135 operation: []const u8,6219 operation: []const u8,
6136 info: BuiltinInfo,6220 info: BuiltinInfo,
6137) !CValue {6221) !CValue {
6138 const mod = f.object.dg.module;6222 const zcu = f.object.dg.zcu;
6139 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6223 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61406224
6141 const operand = try f.resolveInst(ty_op.operand);6225 const operand = try f.resolveInst(ty_op.operand);
6142 try reap(f, inst, &.{ty_op.operand});6226 try reap(f, inst, &.{ty_op.operand});
6143 const inst_ty = f.typeOfIndex(inst);6227 const inst_ty = f.typeOfIndex(inst);
6144 const inst_scalar_ty = inst_ty.scalarType(mod);6228 const inst_scalar_ty = inst_ty.scalarType(zcu);
6145 const operand_ty = f.typeOf(ty_op.operand);6229 const operand_ty = f.typeOf(ty_op.operand);
6146 const scalar_ty = operand_ty.scalarType(mod);6230 const scalar_ty = operand_ty.scalarType(zcu);
61476231
6148 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);6232 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
6149 const ref_ret = inst_scalar_cty.tag() == .array;6233 const ref_ret = inst_scalar_cty.tag() == .array;
...@@ -6179,7 +6263,7 @@ fn airBinBuiltinCall(...@@ -6179,7 +6263,7 @@ fn airBinBuiltinCall(
6179 operation: []const u8,6263 operation: []const u8,
6180 info: BuiltinInfo,6264 info: BuiltinInfo,
6181) !CValue {6265) !CValue {
6182 const mod = f.object.dg.module;6266 const zcu = f.object.dg.zcu;
6183 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;6267 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
61846268
6185 const operand_ty = f.typeOf(bin_op.lhs);6269 const operand_ty = f.typeOf(bin_op.lhs);
...@@ -6191,8 +6275,8 @@ fn airBinBuiltinCall(...@@ -6191,8 +6275,8 @@ fn airBinBuiltinCall(
6191 if (!is_big) try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });6275 if (!is_big) try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
61926276
6193 const inst_ty = f.typeOfIndex(inst);6277 const inst_ty = f.typeOfIndex(inst);
6194 const inst_scalar_ty = inst_ty.scalarType(mod);6278 const inst_scalar_ty = inst_ty.scalarType(zcu);
6195 const scalar_ty = operand_ty.scalarType(mod);6279 const scalar_ty = operand_ty.scalarType(zcu);
61966280
6197 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);6281 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
6198 const ref_ret = inst_scalar_cty.tag() == .array;6282 const ref_ret = inst_scalar_cty.tag() == .array;
...@@ -6234,15 +6318,15 @@ fn airCmpBuiltinCall(...@@ -6234,15 +6318,15 @@ fn airCmpBuiltinCall(
6234 operation: enum { cmp, operator },6318 operation: enum { cmp, operator },
6235 info: BuiltinInfo,6319 info: BuiltinInfo,
6236) !CValue {6320) !CValue {
6237 const mod = f.object.dg.module;6321 const zcu = f.object.dg.zcu;
6238 const lhs = try f.resolveInst(data.lhs);6322 const lhs = try f.resolveInst(data.lhs);
6239 const rhs = try f.resolveInst(data.rhs);6323 const rhs = try f.resolveInst(data.rhs);
6240 try reap(f, inst, &.{ data.lhs, data.rhs });6324 try reap(f, inst, &.{ data.lhs, data.rhs });
62416325
6242 const inst_ty = f.typeOfIndex(inst);6326 const inst_ty = f.typeOfIndex(inst);
6243 const inst_scalar_ty = inst_ty.scalarType(mod);6327 const inst_scalar_ty = inst_ty.scalarType(zcu);
6244 const operand_ty = f.typeOf(data.lhs);6328 const operand_ty = f.typeOf(data.lhs);
6245 const scalar_ty = operand_ty.scalarType(mod);6329 const scalar_ty = operand_ty.scalarType(zcu);
62466330
6247 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);6331 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
6248 const ref_ret = inst_scalar_cty.tag() == .array;6332 const ref_ret = inst_scalar_cty.tag() == .array;
...@@ -6275,7 +6359,7 @@ fn airCmpBuiltinCall(...@@ -6275,7 +6359,7 @@ fn airCmpBuiltinCall(
6275 try writer.writeByte(')');6359 try writer.writeByte(')');
6276 if (!ref_ret) try writer.print("{s}{}", .{6360 if (!ref_ret) try writer.print("{s}{}", .{
6277 compareOperatorC(operator),6361 compareOperatorC(operator),
6278 try f.fmtIntLiteral(Type.i32, try mod.intValue(Type.i32, 0)),6362 try f.fmtIntLiteral(try zcu.intValue(Type.i32, 0)),
6279 });6363 });
6280 try writer.writeAll(";\n");6364 try writer.writeAll(";\n");
6281 try v.end(f, inst, writer);6365 try v.end(f, inst, writer);
...@@ -6284,7 +6368,7 @@ fn airCmpBuiltinCall(...@@ -6284,7 +6368,7 @@ fn airCmpBuiltinCall(
6284}6368}
62856369
6286fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue {6370fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue {
6287 const mod = f.object.dg.module;6371 const zcu = f.object.dg.zcu;
6288 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;6372 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
6289 const extra = f.air.extraData(Air.Cmpxchg, ty_pl.payload).data;6373 const extra = f.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
6290 const inst_ty = f.typeOfIndex(inst);6374 const inst_ty = f.typeOfIndex(inst);
...@@ -6292,19 +6376,19 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6292,19 +6376,19 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6292 const expected_value = try f.resolveInst(extra.expected_value);6376 const expected_value = try f.resolveInst(extra.expected_value);
6293 const new_value = try f.resolveInst(extra.new_value);6377 const new_value = try f.resolveInst(extra.new_value);
6294 const ptr_ty = f.typeOf(extra.ptr);6378 const ptr_ty = f.typeOf(extra.ptr);
6295 const ty = ptr_ty.childType(mod);6379 const ty = ptr_ty.childType(zcu);
62966380
6297 const writer = f.object.writer();6381 const writer = f.object.writer();
6298 const new_value_mat = try Materialize.start(f, inst, writer, ty, new_value);6382 const new_value_mat = try Materialize.start(f, inst, writer, ty, new_value);
6299 try reap(f, inst, &.{ extra.ptr, extra.expected_value, extra.new_value });6383 try reap(f, inst, &.{ extra.ptr, extra.expected_value, extra.new_value });
63006384
6301 const repr_ty = if (ty.isRuntimeFloat())6385 const repr_ty = if (ty.isRuntimeFloat())
6302 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable6386 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6303 else6387 else
6304 ty;6388 ty;
63056389
6306 const local = try f.allocLocal(inst, inst_ty);6390 const local = try f.allocLocal(inst, inst_ty);
6307 if (inst_ty.isPtrLikeOptional(mod)) {6391 if (inst_ty.isPtrLikeOptional(zcu)) {
6308 {6392 {
6309 const a = try Assignment.start(f, writer, ty);6393 const a = try Assignment.start(f, writer, ty);
6310 try f.writeCValue(writer, local, .Other);6394 try f.writeCValue(writer, local, .Other);
...@@ -6317,7 +6401,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6317,7 +6401,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6317 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});6401 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});
6318 try f.renderType(writer, ty);6402 try f.renderType(writer, ty);
6319 try writer.writeByte(')');6403 try writer.writeByte(')');
6320 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");6404 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
6321 try writer.writeAll(" *)");6405 try writer.writeAll(" *)");
6322 try f.writeCValue(writer, ptr, .Other);6406 try f.writeCValue(writer, ptr, .Other);
6323 try writer.writeAll(", ");6407 try writer.writeAll(", ");
...@@ -6331,7 +6415,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6331,7 +6415,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6331 try writer.writeAll(", ");6415 try writer.writeAll(", ");
6332 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);6416 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
6333 try writer.writeAll(", ");6417 try writer.writeAll(", ");
6334 try f.object.dg.renderType(writer, repr_ty);6418 try f.renderType(writer, repr_ty);
6335 try writer.writeByte(')');6419 try writer.writeByte(')');
6336 try writer.writeAll(") {\n");6420 try writer.writeAll(") {\n");
6337 f.object.indent_writer.pushIndent();6421 f.object.indent_writer.pushIndent();
...@@ -6359,7 +6443,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6359,7 +6443,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6359 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});6443 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});
6360 try f.renderType(writer, ty);6444 try f.renderType(writer, ty);
6361 try writer.writeByte(')');6445 try writer.writeByte(')');
6362 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");6446 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
6363 try writer.writeAll(" *)");6447 try writer.writeAll(" *)");
6364 try f.writeCValue(writer, ptr, .Other);6448 try f.writeCValue(writer, ptr, .Other);
6365 try writer.writeAll(", ");6449 try writer.writeAll(", ");
...@@ -6373,7 +6457,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6373,7 +6457,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6373 try writer.writeAll(", ");6457 try writer.writeAll(", ");
6374 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);6458 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
6375 try writer.writeAll(", ");6459 try writer.writeAll(", ");
6376 try f.object.dg.renderType(writer, repr_ty);6460 try f.renderType(writer, repr_ty);
6377 try writer.writeByte(')');6461 try writer.writeByte(')');
6378 try a.end(f, writer);6462 try a.end(f, writer);
6379 }6463 }
...@@ -6389,12 +6473,12 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue...@@ -6389,12 +6473,12 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
6389}6473}
63906474
6391fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {6475fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6392 const mod = f.object.dg.module;6476 const zcu = f.object.dg.zcu;
6393 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;6477 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
6394 const extra = f.air.extraData(Air.AtomicRmw, pl_op.payload).data;6478 const extra = f.air.extraData(Air.AtomicRmw, pl_op.payload).data;
6395 const inst_ty = f.typeOfIndex(inst);6479 const inst_ty = f.typeOfIndex(inst);
6396 const ptr_ty = f.typeOf(pl_op.operand);6480 const ptr_ty = f.typeOf(pl_op.operand);
6397 const ty = ptr_ty.childType(mod);6481 const ty = ptr_ty.childType(zcu);
6398 const ptr = try f.resolveInst(pl_op.operand);6482 const ptr = try f.resolveInst(pl_op.operand);
6399 const operand = try f.resolveInst(extra.operand);6483 const operand = try f.resolveInst(extra.operand);
64006484
...@@ -6402,10 +6486,10 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6402,10 +6486,10 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6402 const operand_mat = try Materialize.start(f, inst, writer, ty, operand);6486 const operand_mat = try Materialize.start(f, inst, writer, ty, operand);
6403 try reap(f, inst, &.{ pl_op.operand, extra.operand });6487 try reap(f, inst, &.{ pl_op.operand, extra.operand });
64046488
6405 const repr_bits = @as(u16, @intCast(ty.abiSize(mod) * 8));6489 const repr_bits = @as(u16, @intCast(ty.abiSize(zcu) * 8));
6406 const is_float = ty.isRuntimeFloat();6490 const is_float = ty.isRuntimeFloat();
6407 const is_128 = repr_bits == 128;6491 const is_128 = repr_bits == 128;
6408 const repr_ty = if (is_float) mod.intType(.unsigned, repr_bits) catch unreachable else ty;6492 const repr_ty = if (is_float) zcu.intType(.unsigned, repr_bits) catch unreachable else ty;
64096493
6410 const local = try f.allocLocal(inst, inst_ty);6494 const local = try f.allocLocal(inst, inst_ty);
6411 try writer.print("zig_atomicrmw_{s}", .{toAtomicRmwSuffix(extra.op())});6495 try writer.print("zig_atomicrmw_{s}", .{toAtomicRmwSuffix(extra.op())});
...@@ -6421,7 +6505,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6421,7 +6505,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6421 if (use_atomic) try writer.writeAll("zig_atomic(");6505 if (use_atomic) try writer.writeAll("zig_atomic(");
6422 try f.renderType(writer, ty);6506 try f.renderType(writer, ty);
6423 if (use_atomic) try writer.writeByte(')');6507 if (use_atomic) try writer.writeByte(')');
6424 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");6508 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
6425 try writer.writeAll(" *)");6509 try writer.writeAll(" *)");
6426 try f.writeCValue(writer, ptr, .Other);6510 try f.writeCValue(writer, ptr, .Other);
6427 try writer.writeAll(", ");6511 try writer.writeAll(", ");
...@@ -6431,7 +6515,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6431,7 +6515,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6431 try writer.writeAll(", ");6515 try writer.writeAll(", ");
6432 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);6516 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
6433 try writer.writeAll(", ");6517 try writer.writeAll(", ");
6434 try f.object.dg.renderType(writer, repr_ty);6518 try f.renderType(writer, repr_ty);
6435 try writer.writeAll(");\n");6519 try writer.writeAll(");\n");
6436 try operand_mat.end(f, inst);6520 try operand_mat.end(f, inst);
64376521
...@@ -6444,15 +6528,15 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6444,15 +6528,15 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6444}6528}
64456529
6446fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {6530fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6447 const mod = f.object.dg.module;6531 const zcu = f.object.dg.zcu;
6448 const atomic_load = f.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;6532 const atomic_load = f.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
6449 const ptr = try f.resolveInst(atomic_load.ptr);6533 const ptr = try f.resolveInst(atomic_load.ptr);
6450 try reap(f, inst, &.{atomic_load.ptr});6534 try reap(f, inst, &.{atomic_load.ptr});
6451 const ptr_ty = f.typeOf(atomic_load.ptr);6535 const ptr_ty = f.typeOf(atomic_load.ptr);
6452 const ty = ptr_ty.childType(mod);6536 const ty = ptr_ty.childType(zcu);
64536537
6454 const repr_ty = if (ty.isRuntimeFloat())6538 const repr_ty = if (ty.isRuntimeFloat())
6455 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable6539 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6456 else6540 else
6457 ty;6541 ty;
64586542
...@@ -6465,7 +6549,7 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6465,7 +6549,7 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6465 try writer.writeAll(", (zig_atomic(");6549 try writer.writeAll(", (zig_atomic(");
6466 try f.renderType(writer, ty);6550 try f.renderType(writer, ty);
6467 try writer.writeByte(')');6551 try writer.writeByte(')');
6468 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");6552 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
6469 try writer.writeAll(" *)");6553 try writer.writeAll(" *)");
6470 try f.writeCValue(writer, ptr, .Other);6554 try f.writeCValue(writer, ptr, .Other);
6471 try writer.writeAll(", ");6555 try writer.writeAll(", ");
...@@ -6473,17 +6557,17 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6473,17 +6557,17 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6473 try writer.writeAll(", ");6557 try writer.writeAll(", ");
6474 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);6558 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
6475 try writer.writeAll(", ");6559 try writer.writeAll(", ");
6476 try f.object.dg.renderType(writer, repr_ty);6560 try f.renderType(writer, repr_ty);
6477 try writer.writeAll(");\n");6561 try writer.writeAll(");\n");
64786562
6479 return local;6563 return local;
6480}6564}
64816565
6482fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CValue {6566fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CValue {
6483 const mod = f.object.dg.module;6567 const zcu = f.object.dg.zcu;
6484 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;6568 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
6485 const ptr_ty = f.typeOf(bin_op.lhs);6569 const ptr_ty = f.typeOf(bin_op.lhs);
6486 const ty = ptr_ty.childType(mod);6570 const ty = ptr_ty.childType(zcu);
6487 const ptr = try f.resolveInst(bin_op.lhs);6571 const ptr = try f.resolveInst(bin_op.lhs);
6488 const element = try f.resolveInst(bin_op.rhs);6572 const element = try f.resolveInst(bin_op.rhs);
64896573
...@@ -6492,14 +6576,14 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa...@@ -6492,14 +6576,14 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
6492 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });6576 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
64936577
6494 const repr_ty = if (ty.isRuntimeFloat())6578 const repr_ty = if (ty.isRuntimeFloat())
6495 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable6579 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6496 else6580 else
6497 ty;6581 ty;
64986582
6499 try writer.writeAll("zig_atomic_store((zig_atomic(");6583 try writer.writeAll("zig_atomic_store((zig_atomic(");
6500 try f.renderType(writer, ty);6584 try f.renderType(writer, ty);
6501 try writer.writeByte(')');6585 try writer.writeByte(')');
6502 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");6586 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
6503 try writer.writeAll(" *)");6587 try writer.writeAll(" *)");
6504 try f.writeCValue(writer, ptr, .Other);6588 try f.writeCValue(writer, ptr, .Other);
6505 try writer.writeAll(", ");6589 try writer.writeAll(", ");
...@@ -6507,7 +6591,7 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa...@@ -6507,7 +6591,7 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
6507 try writer.print(", {s}, ", .{order});6591 try writer.print(", {s}, ", .{order});
6508 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);6592 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
6509 try writer.writeAll(", ");6593 try writer.writeAll(", ");
6510 try f.object.dg.renderType(writer, repr_ty);6594 try f.renderType(writer, repr_ty);
6511 try writer.writeAll(");\n");6595 try writer.writeAll(");\n");
6512 try element_mat.end(f, inst);6596 try element_mat.end(f, inst);
65136597
...@@ -6515,8 +6599,8 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa...@@ -6515,8 +6599,8 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
6515}6599}
65166600
6517fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !void {6601fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !void {
6518 const mod = f.object.dg.module;6602 const zcu = f.object.dg.zcu;
6519 if (ptr_ty.isSlice(mod)) {6603 if (ptr_ty.isSlice(zcu)) {
6520 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" });6604 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" });
6521 } else {6605 } else {
6522 try f.writeCValue(writer, ptr, .FunctionArgument);6606 try f.writeCValue(writer, ptr, .FunctionArgument);
...@@ -6524,14 +6608,14 @@ fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !vo...@@ -6524,14 +6608,14 @@ fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !vo
6524}6608}
65256609
6526fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {6610fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6527 const mod = f.object.dg.module;6611 const zcu = f.object.dg.zcu;
6528 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;6612 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
6529 const dest_ty = f.typeOf(bin_op.lhs);6613 const dest_ty = f.typeOf(bin_op.lhs);
6530 const dest_slice = try f.resolveInst(bin_op.lhs);6614 const dest_slice = try f.resolveInst(bin_op.lhs);
6531 const value = try f.resolveInst(bin_op.rhs);6615 const value = try f.resolveInst(bin_op.rhs);
6532 const elem_ty = f.typeOf(bin_op.rhs);6616 const elem_ty = f.typeOf(bin_op.rhs);
6533 const elem_abi_size = elem_ty.abiSize(mod);6617 const elem_abi_size = elem_ty.abiSize(zcu);
6534 const val_is_undef = if (try f.air.value(bin_op.rhs, mod)) |val| val.isUndefDeep(mod) else false;6618 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |val| val.isUndefDeep(zcu) else false;
6535 const writer = f.object.writer();6619 const writer = f.object.writer();
65366620
6537 if (val_is_undef) {6621 if (val_is_undef) {
...@@ -6541,7 +6625,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6541,7 +6625,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6541 }6625 }
65426626
6543 try writer.writeAll("memset(");6627 try writer.writeAll("memset(");
6544 switch (dest_ty.ptrSize(mod)) {6628 switch (dest_ty.ptrSize(zcu)) {
6545 .Slice => {6629 .Slice => {
6546 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });6630 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });
6547 try writer.writeAll(", 0xaa, ");6631 try writer.writeAll(", 0xaa, ");
...@@ -6553,8 +6637,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6553,8 +6637,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6553 }6637 }
6554 },6638 },
6555 .One => {6639 .One => {
6556 const array_ty = dest_ty.childType(mod);6640 const array_ty = dest_ty.childType(zcu);
6557 const len = array_ty.arrayLen(mod) * elem_abi_size;6641 const len = array_ty.arrayLen(zcu) * elem_abi_size;
65586642
6559 try f.writeCValue(writer, dest_slice, .FunctionArgument);6643 try f.writeCValue(writer, dest_slice, .FunctionArgument);
6560 try writer.print(", 0xaa, {d});\n", .{len});6644 try writer.print(", 0xaa, {d});\n", .{len});
...@@ -6565,12 +6649,12 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6565,12 +6649,12 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6565 return .none;6649 return .none;
6566 }6650 }
65676651
6568 if (elem_abi_size > 1 or dest_ty.isVolatilePtr(mod)) {6652 if (elem_abi_size > 1 or dest_ty.isVolatilePtr(zcu)) {
6569 // For the assignment in this loop, the array pointer needs to get6653 // For the assignment in this loop, the array pointer needs to get
6570 // casted to a regular pointer, otherwise an error like this occurs:6654 // casted to a regular pointer, otherwise an error like this occurs:
6571 // error: array type 'uint32_t[20]' (aka 'unsigned int[20]') is not assignable6655 // error: array type 'uint32_t[20]' (aka 'unsigned int[20]') is not assignable
6572 const elem_ptr_ty = try mod.ptrType(.{6656 const elem_ptr_ty = try zcu.ptrType(.{
6573 .child = elem_ty.ip_index,6657 .child = elem_ty.toIntern(),
6574 .flags = .{6658 .flags = .{
6575 .size = .C,6659 .size = .C,
6576 },6660 },
...@@ -6581,17 +6665,17 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6581,17 +6665,17 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6581 try writer.writeAll("for (");6665 try writer.writeAll("for (");
6582 try f.writeCValue(writer, index, .Other);6666 try f.writeCValue(writer, index, .Other);
6583 try writer.writeAll(" = ");6667 try writer.writeAll(" = ");
6584 try f.object.dg.renderValue(writer, Type.usize, try mod.intValue(Type.usize, 0), .Initializer);6668 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, 0), .Initializer);
6585 try writer.writeAll("; ");6669 try writer.writeAll("; ");
6586 try f.writeCValue(writer, index, .Other);6670 try f.writeCValue(writer, index, .Other);
6587 try writer.writeAll(" != ");6671 try writer.writeAll(" != ");
6588 switch (dest_ty.ptrSize(mod)) {6672 switch (dest_ty.ptrSize(zcu)) {
6589 .Slice => {6673 .Slice => {
6590 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "len" });6674 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "len" });
6591 },6675 },
6592 .One => {6676 .One => {
6593 const array_ty = dest_ty.childType(mod);6677 const array_ty = dest_ty.childType(zcu);
6594 try writer.print("{d}", .{array_ty.arrayLen(mod)});6678 try writer.print("{d}", .{array_ty.arrayLen(zcu)});
6595 },6679 },
6596 .Many, .C => unreachable,6680 .Many, .C => unreachable,
6597 }6681 }
...@@ -6620,7 +6704,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6620,7 +6704,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6620 const bitcasted = try bitcast(f, Type.u8, value, elem_ty);6704 const bitcasted = try bitcast(f, Type.u8, value, elem_ty);
66216705
6622 try writer.writeAll("memset(");6706 try writer.writeAll("memset(");
6623 switch (dest_ty.ptrSize(mod)) {6707 switch (dest_ty.ptrSize(zcu)) {
6624 .Slice => {6708 .Slice => {
6625 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });6709 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });
6626 try writer.writeAll(", ");6710 try writer.writeAll(", ");
...@@ -6630,8 +6714,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6630,8 +6714,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6630 try writer.writeAll(");\n");6714 try writer.writeAll(");\n");
6631 },6715 },
6632 .One => {6716 .One => {
6633 const array_ty = dest_ty.childType(mod);6717 const array_ty = dest_ty.childType(zcu);
6634 const len = array_ty.arrayLen(mod) * elem_abi_size;6718 const len = array_ty.arrayLen(zcu) * elem_abi_size;
66356719
6636 try f.writeCValue(writer, dest_slice, .FunctionArgument);6720 try f.writeCValue(writer, dest_slice, .FunctionArgument);
6637 try writer.writeAll(", ");6721 try writer.writeAll(", ");
...@@ -6646,7 +6730,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {...@@ -6646,7 +6730,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6646}6730}
66476731
6648fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {6732fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6649 const mod = f.object.dg.module;6733 const zcu = f.object.dg.zcu;
6650 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;6734 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
6651 const dest_ptr = try f.resolveInst(bin_op.lhs);6735 const dest_ptr = try f.resolveInst(bin_op.lhs);
6652 const src_ptr = try f.resolveInst(bin_op.rhs);6736 const src_ptr = try f.resolveInst(bin_op.rhs);
...@@ -6659,10 +6743,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6659,10 +6743,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6659 try writer.writeAll(", ");6743 try writer.writeAll(", ");
6660 try writeSliceOrPtr(f, writer, src_ptr, src_ty);6744 try writeSliceOrPtr(f, writer, src_ptr, src_ty);
6661 try writer.writeAll(", ");6745 try writer.writeAll(", ");
6662 switch (dest_ty.ptrSize(mod)) {6746 switch (dest_ty.ptrSize(zcu)) {
6663 .Slice => {6747 .Slice => {
6664 const elem_ty = dest_ty.childType(mod);6748 const elem_ty = dest_ty.childType(zcu);
6665 const elem_abi_size = elem_ty.abiSize(mod);6749 const elem_abi_size = elem_ty.abiSize(zcu);
6666 try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" });6750 try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" });
6667 if (elem_abi_size > 1) {6751 if (elem_abi_size > 1) {
6668 try writer.print(" * {d});\n", .{elem_abi_size});6752 try writer.print(" * {d});\n", .{elem_abi_size});
...@@ -6671,10 +6755,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6671,10 +6755,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6671 }6755 }
6672 },6756 },
6673 .One => {6757 .One => {
6674 const array_ty = dest_ty.childType(mod);6758 const array_ty = dest_ty.childType(zcu);
6675 const elem_ty = array_ty.childType(mod);6759 const elem_ty = array_ty.childType(zcu);
6676 const elem_abi_size = elem_ty.abiSize(mod);6760 const elem_abi_size = elem_ty.abiSize(zcu);
6677 const len = array_ty.arrayLen(mod) * elem_abi_size;6761 const len = array_ty.arrayLen(zcu) * elem_abi_size;
6678 try writer.print("{d});\n", .{len});6762 try writer.print("{d});\n", .{len});
6679 },6763 },
6680 .Many, .C => unreachable,6764 .Many, .C => unreachable,
...@@ -6685,16 +6769,16 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6685,16 +6769,16 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6685}6769}
66866770
6687fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {6771fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6688 const mod = f.object.dg.module;6772 const zcu = f.object.dg.zcu;
6689 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;6773 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
6690 const union_ptr = try f.resolveInst(bin_op.lhs);6774 const union_ptr = try f.resolveInst(bin_op.lhs);
6691 const new_tag = try f.resolveInst(bin_op.rhs);6775 const new_tag = try f.resolveInst(bin_op.rhs);
6692 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });6776 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
66936777
6694 const union_ty = f.typeOf(bin_op.lhs).childType(mod);6778 const union_ty = f.typeOf(bin_op.lhs).childType(zcu);
6695 const layout = union_ty.unionGetLayout(mod);6779 const layout = union_ty.unionGetLayout(zcu);
6696 if (layout.tag_size == 0) return .none;6780 if (layout.tag_size == 0) return .none;
6697 const tag_ty = union_ty.unionTagTypeSafety(mod).?;6781 const tag_ty = union_ty.unionTagTypeSafety(zcu).?;
66986782
6699 const writer = f.object.writer();6783 const writer = f.object.writer();
6700 const a = try Assignment.start(f, writer, tag_ty);6784 const a = try Assignment.start(f, writer, tag_ty);
...@@ -6706,14 +6790,14 @@ fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6706,14 +6790,14 @@ fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6706}6790}
67076791
6708fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {6792fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6709 const mod = f.object.dg.module;6793 const zcu = f.object.dg.zcu;
6710 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6794 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67116795
6712 const operand = try f.resolveInst(ty_op.operand);6796 const operand = try f.resolveInst(ty_op.operand);
6713 try reap(f, inst, &.{ty_op.operand});6797 try reap(f, inst, &.{ty_op.operand});
67146798
6715 const union_ty = f.typeOf(ty_op.operand);6799 const union_ty = f.typeOf(ty_op.operand);
6716 const layout = union_ty.unionGetLayout(mod);6800 const layout = union_ty.unionGetLayout(zcu);
6717 if (layout.tag_size == 0) return .none;6801 if (layout.tag_size == 0) return .none;
67186802
6719 const inst_ty = f.typeOfIndex(inst);6803 const inst_ty = f.typeOfIndex(inst);
...@@ -6728,7 +6812,7 @@ fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6728,7 +6812,7 @@ fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6728}6812}
67296813
6730fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {6814fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
6731 const mod = f.object.dg.module;6815 const zcu = f.object.dg.zcu;
6732 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;6816 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
67336817
6734 const inst_ty = f.typeOfIndex(inst);6818 const inst_ty = f.typeOfIndex(inst);
...@@ -6740,7 +6824,7 @@ fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6740,7 +6824,7 @@ fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
6740 const local = try f.allocLocal(inst, inst_ty);6824 const local = try f.allocLocal(inst, inst_ty);
6741 try f.writeCValue(writer, local, .Other);6825 try f.writeCValue(writer, local, .Other);
6742 try writer.print(" = {s}(", .{6826 try writer.print(" = {s}(", .{
6743 try f.getLazyFnName(.{ .tag_name = enum_ty.getOwnerDecl(mod) }, .{ .tag_name = enum_ty }),6827 try f.getLazyFnName(.{ .tag_name = enum_ty.getOwnerDecl(zcu) }, .{ .tag_name = enum_ty }),
6744 });6828 });
6745 try f.writeCValue(writer, operand, .Other);6829 try f.writeCValue(writer, operand, .Other);
6746 try writer.writeAll(");\n");6830 try writer.writeAll(");\n");
...@@ -6765,14 +6849,14 @@ fn airErrorName(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6765,14 +6849,14 @@ fn airErrorName(f: *Function, inst: Air.Inst.Index) !CValue {
6765}6849}
67666850
6767fn airSplat(f: *Function, inst: Air.Inst.Index) !CValue {6851fn airSplat(f: *Function, inst: Air.Inst.Index) !CValue {
6768 const mod = f.object.dg.module;6852 const zcu = f.object.dg.zcu;
6769 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;6853 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67706854
6771 const operand = try f.resolveInst(ty_op.operand);6855 const operand = try f.resolveInst(ty_op.operand);
6772 try reap(f, inst, &.{ty_op.operand});6856 try reap(f, inst, &.{ty_op.operand});
67736857
6774 const inst_ty = f.typeOfIndex(inst);6858 const inst_ty = f.typeOfIndex(inst);
6775 const inst_scalar_ty = inst_ty.scalarType(mod);6859 const inst_scalar_ty = inst_ty.scalarType(zcu);
67766860
6777 const writer = f.object.writer();6861 const writer = f.object.writer();
6778 const local = try f.allocLocal(inst, inst_ty);6862 const local = try f.allocLocal(inst, inst_ty);
...@@ -6820,7 +6904,7 @@ fn airSelect(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6820,7 +6904,7 @@ fn airSelect(f: *Function, inst: Air.Inst.Index) !CValue {
6820}6904}
68216905
6822fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {6906fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6823 const mod = f.object.dg.module;6907 const zcu = f.object.dg.zcu;
6824 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;6908 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
6825 const extra = f.air.extraData(Air.Shuffle, ty_pl.payload).data;6909 const extra = f.air.extraData(Air.Shuffle, ty_pl.payload).data;
68266910
...@@ -6836,15 +6920,15 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6836,15 +6920,15 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6836 for (0..extra.mask_len) |index| {6920 for (0..extra.mask_len) |index| {
6837 try f.writeCValue(writer, local, .Other);6921 try f.writeCValue(writer, local, .Other);
6838 try writer.writeByte('[');6922 try writer.writeByte('[');
6839 try f.object.dg.renderValue(writer, Type.usize, try mod.intValue(Type.usize, index), .Other);6923 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, index), .Other);
6840 try writer.writeAll("] = ");6924 try writer.writeAll("] = ");
68416925
6842 const mask_elem = (try mask.elemValue(mod, index)).toSignedInt(mod);6926 const mask_elem = (try mask.elemValue(zcu, index)).toSignedInt(zcu);
6843 const src_val = try mod.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));6927 const src_val = try zcu.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
68446928
6845 try f.writeCValue(writer, if (mask_elem >= 0) lhs else rhs, .Other);6929 try f.writeCValue(writer, if (mask_elem >= 0) lhs else rhs, .Other);
6846 try writer.writeByte('[');6930 try writer.writeByte('[');
6847 try f.object.dg.renderValue(writer, Type.usize, src_val, .Other);6931 try f.object.dg.renderValue(writer, src_val, .Other);
6848 try writer.writeAll("];\n");6932 try writer.writeAll("];\n");
6849 }6933 }
68506934
...@@ -6852,7 +6936,7 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6852,7 +6936,7 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6852}6936}
68536937
6854fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {6938fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6855 const mod = f.object.dg.module;6939 const zcu = f.object.dg.zcu;
6856 const reduce = f.air.instructions.items(.data)[@intFromEnum(inst)].reduce;6940 const reduce = f.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
68576941
6858 const scalar_ty = f.typeOfIndex(inst);6942 const scalar_ty = f.typeOfIndex(inst);
...@@ -6861,7 +6945,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6861,7 +6945,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6861 const operand_ty = f.typeOf(reduce.operand);6945 const operand_ty = f.typeOf(reduce.operand);
6862 const writer = f.object.writer();6946 const writer = f.object.writer();
68636947
6864 const use_operator = scalar_ty.bitSize(mod) <= 64;6948 const use_operator = scalar_ty.bitSize(zcu) <= 64;
6865 const op: union(enum) {6949 const op: union(enum) {
6866 const Func = struct { operation: []const u8, info: BuiltinInfo = .none };6950 const Func = struct { operation: []const u8, info: BuiltinInfo = .none };
6867 float_op: Func,6951 float_op: Func,
...@@ -6872,28 +6956,28 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6872,28 +6956,28 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6872 .And => if (use_operator) .{ .infix = " &= " } else .{ .builtin = .{ .operation = "and" } },6956 .And => if (use_operator) .{ .infix = " &= " } else .{ .builtin = .{ .operation = "and" } },
6873 .Or => if (use_operator) .{ .infix = " |= " } else .{ .builtin = .{ .operation = "or" } },6957 .Or => if (use_operator) .{ .infix = " |= " } else .{ .builtin = .{ .operation = "or" } },
6874 .Xor => if (use_operator) .{ .infix = " ^= " } else .{ .builtin = .{ .operation = "xor" } },6958 .Xor => if (use_operator) .{ .infix = " ^= " } else .{ .builtin = .{ .operation = "xor" } },
6875 .Min => switch (scalar_ty.zigTypeTag(mod)) {6959 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
6876 .Int => if (use_operator) .{ .ternary = " < " } else .{6960 .Int => if (use_operator) .{ .ternary = " < " } else .{
6877 .builtin = .{ .operation = "min" },6961 .builtin = .{ .operation = "min" },
6878 },6962 },
6879 .Float => .{ .float_op = .{ .operation = "fmin" } },6963 .Float => .{ .float_op = .{ .operation = "fmin" } },
6880 else => unreachable,6964 else => unreachable,
6881 },6965 },
6882 .Max => switch (scalar_ty.zigTypeTag(mod)) {6966 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
6883 .Int => if (use_operator) .{ .ternary = " > " } else .{6967 .Int => if (use_operator) .{ .ternary = " > " } else .{
6884 .builtin = .{ .operation = "max" },6968 .builtin = .{ .operation = "max" },
6885 },6969 },
6886 .Float => .{ .float_op = .{ .operation = "fmax" } },6970 .Float => .{ .float_op = .{ .operation = "fmax" } },
6887 else => unreachable,6971 else => unreachable,
6888 },6972 },
6889 .Add => switch (scalar_ty.zigTypeTag(mod)) {6973 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
6890 .Int => if (use_operator) .{ .infix = " += " } else .{6974 .Int => if (use_operator) .{ .infix = " += " } else .{
6891 .builtin = .{ .operation = "addw", .info = .bits },6975 .builtin = .{ .operation = "addw", .info = .bits },
6892 },6976 },
6893 .Float => .{ .builtin = .{ .operation = "add" } },6977 .Float => .{ .builtin = .{ .operation = "add" } },
6894 else => unreachable,6978 else => unreachable,
6895 },6979 },
6896 .Mul => switch (scalar_ty.zigTypeTag(mod)) {6980 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
6897 .Int => if (use_operator) .{ .infix = " *= " } else .{6981 .Int => if (use_operator) .{ .infix = " *= " } else .{
6898 .builtin = .{ .operation = "mulw", .info = .bits },6982 .builtin = .{ .operation = "mulw", .info = .bits },
6899 },6983 },
...@@ -6908,7 +6992,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6908,7 +6992,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6908 // Equivalent to:6992 // Equivalent to:
6909 // reduce: {6993 // reduce: {
6910 // var accum: T = init;6994 // var accum: T = init;
6911 // for (vec) : (elem) {6995 // for (vec) |elem| {
6912 // accum = func(accum, elem);6996 // accum = func(accum, elem);
6913 // }6997 // }
6914 // break :reduce accum;6998 // break :reduce accum;
...@@ -6918,40 +7002,40 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -6918,40 +7002,40 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6918 try f.writeCValue(writer, accum, .Other);7002 try f.writeCValue(writer, accum, .Other);
6919 try writer.writeAll(" = ");7003 try writer.writeAll(" = ");
69207004
6921 try f.object.dg.renderValue(writer, scalar_ty, switch (reduce.operation) {7005 try f.object.dg.renderValue(writer, switch (reduce.operation) {
6922 .Or, .Xor => switch (scalar_ty.zigTypeTag(mod)) {7006 .Or, .Xor => switch (scalar_ty.zigTypeTag(zcu)) {
6923 .Bool => Value.false,7007 .Bool => Value.false,
6924 .Int => try mod.intValue(scalar_ty, 0),7008 .Int => try zcu.intValue(scalar_ty, 0),
6925 else => unreachable,7009 else => unreachable,
6926 },7010 },
6927 .And => switch (scalar_ty.zigTypeTag(mod)) {7011 .And => switch (scalar_ty.zigTypeTag(zcu)) {
6928 .Bool => Value.true,7012 .Bool => Value.true,
6929 .Int => switch (scalar_ty.intInfo(mod).signedness) {7013 .Int => switch (scalar_ty.intInfo(zcu).signedness) {
6930 .unsigned => try scalar_ty.maxIntScalar(mod, scalar_ty),7014 .unsigned => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6931 .signed => try mod.intValue(scalar_ty, -1),7015 .signed => try zcu.intValue(scalar_ty, -1),
6932 },7016 },
6933 else => unreachable,7017 else => unreachable,
6934 },7018 },
6935 .Add => switch (scalar_ty.zigTypeTag(mod)) {7019 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
6936 .Int => try mod.intValue(scalar_ty, 0),7020 .Int => try zcu.intValue(scalar_ty, 0),
6937 .Float => try mod.floatValue(scalar_ty, 0.0),7021 .Float => try zcu.floatValue(scalar_ty, 0.0),
6938 else => unreachable,7022 else => unreachable,
6939 },7023 },
6940 .Mul => switch (scalar_ty.zigTypeTag(mod)) {7024 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
6941 .Int => try mod.intValue(scalar_ty, 1),7025 .Int => try zcu.intValue(scalar_ty, 1),
6942 .Float => try mod.floatValue(scalar_ty, 1.0),7026 .Float => try zcu.floatValue(scalar_ty, 1.0),
6943 else => unreachable,7027 else => unreachable,
6944 },7028 },
6945 .Min => switch (scalar_ty.zigTypeTag(mod)) {7029 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
6946 .Bool => Value.true,7030 .Bool => Value.true,
6947 .Int => try scalar_ty.maxIntScalar(mod, scalar_ty),7031 .Int => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6948 .Float => try mod.floatValue(scalar_ty, std.math.nan(f128)),7032 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
6949 else => unreachable,7033 else => unreachable,
6950 },7034 },
6951 .Max => switch (scalar_ty.zigTypeTag(mod)) {7035 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
6952 .Bool => Value.false,7036 .Bool => Value.false,
6953 .Int => try scalar_ty.minIntScalar(mod, scalar_ty),7037 .Int => try scalar_ty.minIntScalar(zcu, scalar_ty),
6954 .Float => try mod.floatValue(scalar_ty, std.math.nan(f128)),7038 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
6955 else => unreachable,7039 else => unreachable,
6956 },7040 },
6957 }, .Initializer);7041 }, .Initializer);
...@@ -7007,11 +7091,11 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7007,11 +7091,11 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
7007}7091}
70087092
7009fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {7093fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7010 const mod = f.object.dg.module;7094 const zcu = f.object.dg.zcu;
7011 const ip = &mod.intern_pool;7095 const ip = &zcu.intern_pool;
7012 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;7096 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
7013 const inst_ty = f.typeOfIndex(inst);7097 const inst_ty = f.typeOfIndex(inst);
7014 const len = @as(usize, @intCast(inst_ty.arrayLen(mod)));7098 const len = @as(usize, @intCast(inst_ty.arrayLen(zcu)));
7015 const elements = @as([]const Air.Inst.Ref, @ptrCast(f.air.extra[ty_pl.payload..][0..len]));7099 const elements = @as([]const Air.Inst.Ref, @ptrCast(f.air.extra[ty_pl.payload..][0..len]));
7016 const gpa = f.object.dg.gpa;7100 const gpa = f.object.dg.gpa;
7017 const resolved_elements = try gpa.alloc(CValue, elements.len);7101 const resolved_elements = try gpa.alloc(CValue, elements.len);
...@@ -7028,10 +7112,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7028,10 +7112,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70287112
7029 const writer = f.object.writer();7113 const writer = f.object.writer();
7030 const local = try f.allocLocal(inst, inst_ty);7114 const local = try f.allocLocal(inst, inst_ty);
7031 switch (inst_ty.zigTypeTag(mod)) {7115 switch (inst_ty.zigTypeTag(zcu)) {
7032 .Array, .Vector => {7116 .Array, .Vector => {
7033 const elem_ty = inst_ty.childType(mod);7117 const a = try Assignment.init(f, inst_ty.childType(zcu));
7034 const a = try Assignment.init(f, elem_ty);
7035 for (resolved_elements, 0..) |element, i| {7118 for (resolved_elements, 0..) |element, i| {
7036 try a.restart(f, writer);7119 try a.restart(f, writer);
7037 try f.writeCValue(writer, local, .Other);7120 try f.writeCValue(writer, local, .Other);
...@@ -7040,26 +7123,26 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7040,26 +7123,26 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7040 try f.writeCValue(writer, element, .Other);7123 try f.writeCValue(writer, element, .Other);
7041 try a.end(f, writer);7124 try a.end(f, writer);
7042 }7125 }
7043 if (inst_ty.sentinel(mod)) |sentinel| {7126 if (inst_ty.sentinel(zcu)) |sentinel| {
7044 try a.restart(f, writer);7127 try a.restart(f, writer);
7045 try f.writeCValue(writer, local, .Other);7128 try f.writeCValue(writer, local, .Other);
7046 try writer.print("[{d}]", .{resolved_elements.len});7129 try writer.print("[{d}]", .{resolved_elements.len});
7047 try a.assign(f, writer);7130 try a.assign(f, writer);
7048 try f.object.dg.renderValue(writer, elem_ty, sentinel, .Other);7131 try f.object.dg.renderValue(writer, sentinel, .Other);
7049 try a.end(f, writer);7132 try a.end(f, writer);
7050 }7133 }
7051 },7134 },
7052 .Struct => switch (inst_ty.containerLayout(mod)) {7135 .Struct => switch (inst_ty.containerLayout(zcu)) {
7053 .auto, .@"extern" => for (resolved_elements, 0..) |element, field_index| {7136 .auto, .@"extern" => for (resolved_elements, 0..) |element, field_index| {
7054 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;7137 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7055 const field_ty = inst_ty.structFieldType(field_index, mod);7138 const field_ty = inst_ty.structFieldType(field_index, zcu);
7056 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;7139 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70577140
7058 const a = try Assignment.start(f, writer, field_ty);7141 const a = try Assignment.start(f, writer, field_ty);
7059 try f.writeCValueMember(writer, local, if (inst_ty.isSimpleTuple(mod))7142 try f.writeCValueMember(writer, local, if (inst_ty.isSimpleTuple(zcu))
7060 .{ .field = field_index }7143 .{ .field = field_index }
7061 else7144 else
7062 .{ .identifier = ip.stringToSlice(inst_ty.legacyStructFieldName(@intCast(field_index), mod)) });7145 .{ .identifier = ip.stringToSlice(inst_ty.legacyStructFieldName(@intCast(field_index), zcu)) });
7063 try a.assign(f, writer);7146 try a.assign(f, writer);
7064 try f.writeCValue(writer, element, .Other);7147 try f.writeCValue(writer, element, .Other);
7065 try a.end(f, writer);7148 try a.end(f, writer);
...@@ -7067,17 +7150,17 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7067,17 +7150,17 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7067 .@"packed" => {7150 .@"packed" => {
7068 try f.writeCValue(writer, local, .Other);7151 try f.writeCValue(writer, local, .Other);
7069 try writer.writeAll(" = ");7152 try writer.writeAll(" = ");
7070 const int_info = inst_ty.intInfo(mod);7153 const int_info = inst_ty.intInfo(zcu);
70717154
7072 const bit_offset_ty = try mod.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));7155 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
70737156
7074 var bit_offset: u64 = 0;7157 var bit_offset: u64 = 0;
70757158
7076 var empty = true;7159 var empty = true;
7077 for (0..elements.len) |field_index| {7160 for (0..elements.len) |field_index| {
7078 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;7161 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7079 const field_ty = inst_ty.structFieldType(field_index, mod);7162 const field_ty = inst_ty.structFieldType(field_index, zcu);
7080 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;7163 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70817164
7082 if (!empty) {7165 if (!empty) {
7083 try writer.writeAll("zig_or_");7166 try writer.writeAll("zig_or_");
...@@ -7088,9 +7171,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7088,9 +7171,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7088 }7171 }
7089 empty = true;7172 empty = true;
7090 for (resolved_elements, 0..) |element, field_index| {7173 for (resolved_elements, 0..) |element, field_index| {
7091 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;7174 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7092 const field_ty = inst_ty.structFieldType(field_index, mod);7175 const field_ty = inst_ty.structFieldType(field_index, zcu);
7093 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;7176 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70947177
7095 if (!empty) try writer.writeAll(", ");7178 if (!empty) try writer.writeAll(", ");
7096 // TODO: Skip this entire shift if val is 0?7179 // TODO: Skip this entire shift if val is 0?
...@@ -7098,13 +7181,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7098,13 +7181,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7098 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_ty);7181 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_ty);
7099 try writer.writeByte('(');7182 try writer.writeByte('(');
71007183
7101 if (inst_ty.isAbiInt(mod) and (field_ty.isAbiInt(mod) or field_ty.isPtrAtRuntime(mod))) {7184 if (inst_ty.isAbiInt(zcu) and (field_ty.isAbiInt(zcu) or field_ty.isPtrAtRuntime(zcu))) {
7102 try f.renderIntCast(writer, inst_ty, element, .{}, field_ty, .FunctionArgument);7185 try f.renderIntCast(writer, inst_ty, element, .{}, field_ty, .FunctionArgument);
7103 } else {7186 } else {
7104 try writer.writeByte('(');7187 try writer.writeByte('(');
7105 try f.renderType(writer, inst_ty);7188 try f.renderType(writer, inst_ty);
7106 try writer.writeByte(')');7189 try writer.writeByte(')');
7107 if (field_ty.isPtrAtRuntime(mod)) {7190 if (field_ty.isPtrAtRuntime(zcu)) {
7108 try writer.writeByte('(');7191 try writer.writeByte('(');
7109 try f.renderType(writer, switch (int_info.signedness) {7192 try f.renderType(writer, switch (int_info.signedness) {
7110 .unsigned => Type.usize,7193 .unsigned => Type.usize,
...@@ -7115,14 +7198,14 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7115,14 +7198,14 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7115 try f.writeCValue(writer, element, .Other);7198 try f.writeCValue(writer, element, .Other);
7116 }7199 }
71177200
7118 try writer.writeAll(", ");7201 try writer.print(", {}", .{
7119 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);7202 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
7120 try f.object.dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);7203 });
7121 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);7204 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);
7122 try writer.writeByte(')');7205 try writer.writeByte(')');
7123 if (!empty) try writer.writeByte(')');7206 if (!empty) try writer.writeByte(')');
71247207
7125 bit_offset += field_ty.bitSize(mod);7208 bit_offset += field_ty.bitSize(zcu);
7126 empty = false;7209 empty = false;
7127 }7210 }
71287211
...@@ -7136,13 +7219,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7136,13 +7219,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7136}7219}
71377220
7138fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {7221fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7139 const mod = f.object.dg.module;7222 const zcu = f.object.dg.zcu;
7140 const ip = &mod.intern_pool;7223 const ip = &zcu.intern_pool;
7141 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;7224 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
7142 const extra = f.air.extraData(Air.UnionInit, ty_pl.payload).data;7225 const extra = f.air.extraData(Air.UnionInit, ty_pl.payload).data;
71437226
7144 const union_ty = f.typeOfIndex(inst);7227 const union_ty = f.typeOfIndex(inst);
7145 const union_obj = mod.typeToUnion(union_ty).?;7228 const union_obj = zcu.typeToUnion(union_ty).?;
7146 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];7229 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
7147 const payload_ty = f.typeOf(extra.init);7230 const payload_ty = f.typeOf(extra.init);
7148 const payload = try f.resolveInst(extra.init);7231 const payload = try f.resolveInst(extra.init);
...@@ -7158,19 +7241,16 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7158,19 +7241,16 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7158 return local;7241 return local;
7159 }7242 }
71607243
7161 const field: CValue = if (union_ty.unionTagTypeSafety(mod)) |tag_ty| field: {7244 const field: CValue = if (union_ty.unionTagTypeSafety(zcu)) |tag_ty| field: {
7162 const layout = union_ty.unionGetLayout(mod);7245 const layout = union_ty.unionGetLayout(zcu);
7163 if (layout.tag_size != 0) {7246 if (layout.tag_size != 0) {
7164 const field_index = tag_ty.enumFieldIndex(field_name, mod).?;7247 const field_index = tag_ty.enumFieldIndex(field_name, zcu).?;
71657248 const tag_val = try zcu.enumValueFieldIndex(tag_ty, field_index);
7166 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
7167
7168 const int_val = try tag_val.intFromEnum(tag_ty, mod);
71697249
7170 const a = try Assignment.start(f, writer, tag_ty);7250 const a = try Assignment.start(f, writer, tag_ty);
7171 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });7251 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });
7172 try a.assign(f, writer);7252 try a.assign(f, writer);
7173 try writer.print("{}", .{try f.fmtIntLiteral(tag_ty, int_val)});7253 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, zcu))});
7174 try a.end(f, writer);7254 try a.end(f, writer);
7175 }7255 }
7176 break :field .{ .payload_identifier = ip.stringToSlice(field_name) };7256 break :field .{ .payload_identifier = ip.stringToSlice(field_name) };
...@@ -7185,7 +7265,7 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7185,7 +7265,7 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7185}7265}
71867266
7187fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {7267fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
7188 const mod = f.object.dg.module;7268 const zcu = f.object.dg.zcu;
7189 const prefetch = f.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;7269 const prefetch = f.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
71907270
7191 const ptr_ty = f.typeOf(prefetch.ptr);7271 const ptr_ty = f.typeOf(prefetch.ptr);
...@@ -7196,7 +7276,7 @@ fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7196,7 +7276,7 @@ fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
7196 switch (prefetch.cache) {7276 switch (prefetch.cache) {
7197 .data => {7277 .data => {
7198 try writer.writeAll("zig_prefetch(");7278 try writer.writeAll("zig_prefetch(");
7199 if (ptr_ty.isSlice(mod))7279 if (ptr_ty.isSlice(zcu))
7200 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" })7280 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" })
7201 else7281 else
7202 try f.writeCValue(writer, ptr, .FunctionArgument);7282 try f.writeCValue(writer, ptr, .FunctionArgument);
...@@ -7242,14 +7322,14 @@ fn airWasmMemoryGrow(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7242,14 +7322,14 @@ fn airWasmMemoryGrow(f: *Function, inst: Air.Inst.Index) !CValue {
7242}7322}
72437323
7244fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {7324fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {
7245 const mod = f.object.dg.module;7325 const zcu = f.object.dg.zcu;
7246 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;7326 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72477327
7248 const operand = try f.resolveInst(un_op);7328 const operand = try f.resolveInst(un_op);
7249 try reap(f, inst, &.{un_op});7329 try reap(f, inst, &.{un_op});
72507330
7251 const operand_ty = f.typeOf(un_op);7331 const operand_ty = f.typeOf(un_op);
7252 const scalar_ty = operand_ty.scalarType(mod);7332 const scalar_ty = operand_ty.scalarType(zcu);
72537333
7254 const writer = f.object.writer();7334 const writer = f.object.writer();
7255 const local = try f.allocLocal(inst, operand_ty);7335 const local = try f.allocLocal(inst, operand_ty);
...@@ -7268,15 +7348,15 @@ fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7268,15 +7348,15 @@ fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {
7268}7348}
72697349
7270fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {7350fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {
7271 const mod = f.object.dg.module;7351 const zcu = f.object.dg.zcu;
7272 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;7352 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
7273 const operand = try f.resolveInst(ty_op.operand);7353 const operand = try f.resolveInst(ty_op.operand);
7274 const ty = f.typeOf(ty_op.operand);7354 const ty = f.typeOf(ty_op.operand);
7275 const scalar_ty = ty.scalarType(mod);7355 const scalar_ty = ty.scalarType(zcu);
72767356
7277 switch (scalar_ty.zigTypeTag(mod)) {7357 switch (scalar_ty.zigTypeTag(zcu)) {
7278 .Int => if (ty.zigTypeTag(mod) == .Vector) {7358 .Int => if (ty.zigTypeTag(zcu) == .Vector) {
7279 return f.fail("TODO implement airAbs for '{}'", .{ty.fmt(mod)});7359 return f.fail("TODO implement airAbs for '{}'", .{ty.fmt(zcu)});
7280 } else {7360 } else {
7281 return airUnBuiltinCall(f, inst, "abs", .none);7361 return airUnBuiltinCall(f, inst, "abs", .none);
7282 },7362 },
...@@ -7286,8 +7366,8 @@ fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7286,8 +7366,8 @@ fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {
7286}7366}
72877367
7288fn unFloatOp(f: *Function, inst: Air.Inst.Index, operand: CValue, ty: Type, operation: []const u8) !CValue {7368fn unFloatOp(f: *Function, inst: Air.Inst.Index, operand: CValue, ty: Type, operation: []const u8) !CValue {
7289 const mod = f.object.dg.module;7369 const zcu = f.object.dg.zcu;
7290 const scalar_ty = ty.scalarType(mod);7370 const scalar_ty = ty.scalarType(zcu);
72917371
7292 const writer = f.object.writer();7372 const writer = f.object.writer();
7293 const local = try f.allocLocal(inst, ty);7373 const local = try f.allocLocal(inst, ty);
...@@ -7316,7 +7396,7 @@ fn airUnFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVal...@@ -7316,7 +7396,7 @@ fn airUnFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVal
7316}7396}
73177397
7318fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CValue {7398fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CValue {
7319 const mod = f.object.dg.module;7399 const zcu = f.object.dg.zcu;
7320 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;7400 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
73217401
7322 const lhs = try f.resolveInst(bin_op.lhs);7402 const lhs = try f.resolveInst(bin_op.lhs);
...@@ -7324,7 +7404,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa...@@ -7324,7 +7404,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa
7324 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });7404 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
73257405
7326 const inst_ty = f.typeOfIndex(inst);7406 const inst_ty = f.typeOfIndex(inst);
7327 const inst_scalar_ty = inst_ty.scalarType(mod);7407 const inst_scalar_ty = inst_ty.scalarType(zcu);
73287408
7329 const writer = f.object.writer();7409 const writer = f.object.writer();
7330 const local = try f.allocLocal(inst, inst_ty);7410 const local = try f.allocLocal(inst, inst_ty);
...@@ -7346,7 +7426,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa...@@ -7346,7 +7426,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa
7346}7426}
73477427
7348fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {7428fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7349 const mod = f.object.dg.module;7429 const zcu = f.object.dg.zcu;
7350 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;7430 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
7351 const bin_op = f.air.extraData(Air.Bin, pl_op.payload).data;7431 const bin_op = f.air.extraData(Air.Bin, pl_op.payload).data;
73527432
...@@ -7356,7 +7436,7 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7356,7 +7436,7 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7356 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs, pl_op.operand });7436 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs, pl_op.operand });
73577437
7358 const inst_ty = f.typeOfIndex(inst);7438 const inst_ty = f.typeOfIndex(inst);
7359 const inst_scalar_ty = inst_ty.scalarType(mod);7439 const inst_scalar_ty = inst_ty.scalarType(zcu);
73607440
7361 const writer = f.object.writer();7441 const writer = f.object.writer();
7362 const local = try f.allocLocal(inst, inst_ty);7442 const local = try f.allocLocal(inst, inst_ty);
...@@ -7381,11 +7461,11 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {...@@ -7381,11 +7461,11 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7381}7461}
73827462
7383fn airCVaStart(f: *Function, inst: Air.Inst.Index) !CValue {7463fn airCVaStart(f: *Function, inst: Air.Inst.Index) !CValue {
7384 const mod = f.object.dg.module;7464 const zcu = f.object.dg.zcu;
7385 const inst_ty = f.typeOfIndex(inst);7465 const inst_ty = f.typeOfIndex(inst);
7386 const decl_index = f.object.dg.pass.decl;7466 const decl_index = f.object.dg.pass.decl;
7387 const decl = mod.declPtr(decl_index);7467 const decl = zcu.declPtr(decl_index);
7388 const fn_cty = try f.typeToCType(decl.typeOf(mod), .complete);7468 const fn_cty = try f.typeToCType(decl.typeOf(zcu), .complete);
7389 const param_len = fn_cty.castTag(.varargs_function).?.data.param_types.len;7469 const param_len = fn_cty.castTag(.varargs_function).?.data.param_types.len;
73907470
7391 const writer = f.object.writer();7471 const writer = f.object.writer();
...@@ -7589,9 +7669,8 @@ fn signAbbrev(signedness: std.builtin.Signedness) u8 {...@@ -7589,9 +7669,8 @@ fn signAbbrev(signedness: std.builtin.Signedness) u8 {
7589 };7669 };
7590}7670}
75917671
7592fn compilerRtAbbrev(ty: Type, mod: *Module) []const u8 {7672fn compilerRtAbbrev(ty: Type, zcu: *Zcu, target: std.Target) []const u8 {
7593 const target = mod.getTarget();7673 return if (ty.isInt(zcu)) switch (ty.intInfo(zcu).bits) {
7594 return if (ty.isInt(mod)) switch (ty.intInfo(mod).bits) {
7595 1...32 => "si",7674 1...32 => "si",
7596 33...64 => "di",7675 33...64 => "di",
7597 65...128 => "ti",7676 65...128 => "ti",
...@@ -7753,8 +7832,8 @@ fn formatIntLiteral(...@@ -7753,8 +7832,8 @@ fn formatIntLiteral(
7753 options: std.fmt.FormatOptions,7832 options: std.fmt.FormatOptions,
7754 writer: anytype,7833 writer: anytype,
7755) @TypeOf(writer).Error!void {7834) @TypeOf(writer).Error!void {
7756 const mod = data.dg.module;7835 const zcu = data.dg.zcu;
7757 const target = mod.getTarget();7836 const target = &data.dg.mod.resolved_target.result;
77587837
7759 const ExpectedContents = struct {7838 const ExpectedContents = struct {
7760 const base = 10;7839 const base = 10;
...@@ -7774,7 +7853,7 @@ fn formatIntLiteral(...@@ -7774,7 +7853,7 @@ fn formatIntLiteral(
7774 defer allocator.free(undef_limbs);7853 defer allocator.free(undef_limbs);
77757854
7776 var int_buf: Value.BigIntSpace = undefined;7855 var int_buf: Value.BigIntSpace = undefined;
7777 const int = if (data.val.isUndefDeep(mod)) blk: {7856 const int = if (data.val.isUndefDeep(zcu)) blk: {
7778 undef_limbs = try allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(data.int_info.bits));7857 undef_limbs = try allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(data.int_info.bits));
7779 @memset(undef_limbs, undefPattern(BigIntLimb));7858 @memset(undef_limbs, undefPattern(BigIntLimb));
77807859
...@@ -7785,10 +7864,10 @@ fn formatIntLiteral(...@@ -7785,10 +7864,10 @@ fn formatIntLiteral(
7785 };7864 };
7786 undef_int.truncate(undef_int.toConst(), data.int_info.signedness, data.int_info.bits);7865 undef_int.truncate(undef_int.toConst(), data.int_info.signedness, data.int_info.bits);
7787 break :blk undef_int.toConst();7866 break :blk undef_int.toConst();
7788 } else data.val.toBigInt(&int_buf, mod);7867 } else data.val.toBigInt(&int_buf, zcu);
7789 assert(int.fitsInTwosComp(data.int_info.signedness, data.int_info.bits));7868 assert(int.fitsInTwosComp(data.int_info.signedness, data.int_info.bits));
77907869
7791 const c_bits: usize = @intCast(data.cty.byteSize(data.dg.ctypes.set, target) * 8);7870 const c_bits: usize = @intCast(data.cty.byteSize(data.dg.ctypes.set, data.dg.mod) * 8);
7792 var one_limbs: [BigInt.calcLimbLen(1)]BigIntLimb = undefined;7871 var one_limbs: [BigInt.calcLimbLen(1)]BigIntLimb = undefined;
7793 const one = BigInt.Mutable.init(&one_limbs, 1).toConst();7872 const one = BigInt.Mutable.init(&one_limbs, 1).toConst();
77947873
...@@ -7919,7 +7998,7 @@ fn formatIntLiteral(...@@ -7919,7 +7998,7 @@ fn formatIntLiteral(
7919 .int_info = c_limb_int_info,7998 .int_info = c_limb_int_info,
7920 .kind = data.kind,7999 .kind = data.kind,
7921 .cty = c_limb_cty,8000 .cty = c_limb_cty,
7922 .val = try mod.intValue_big(Type.comptime_int, c_limb_mut.toConst()),8001 .val = try zcu.intValue_big(Type.comptime_int, c_limb_mut.toConst()),
7923 }, fmt, options, writer);8002 }, fmt, options, writer);
7924 }8003 }
7925 }8004 }
...@@ -8016,21 +8095,17 @@ const Vectorize = struct {...@@ -8016,21 +8095,17 @@ const Vectorize = struct {
8016 index: CValue = .none,8095 index: CValue = .none,
80178096
8018 pub fn start(f: *Function, inst: Air.Inst.Index, writer: anytype, ty: Type) !Vectorize {8097 pub fn start(f: *Function, inst: Air.Inst.Index, writer: anytype, ty: Type) !Vectorize {
8019 const mod = f.object.dg.module;8098 const zcu = f.object.dg.zcu;
8020 return if (ty.zigTypeTag(mod) == .Vector) index: {8099 return if (ty.zigTypeTag(zcu) == .Vector) index: {
8021 const len_val = try mod.intValue(Type.usize, ty.vectorLen(mod));
8022
8023 const local = try f.allocLocal(inst, Type.usize);8100 const local = try f.allocLocal(inst, Type.usize);
80248101
8025 try writer.writeAll("for (");8102 try writer.writeAll("for (");
8026 try f.writeCValue(writer, local, .Other);8103 try f.writeCValue(writer, local, .Other);
8027 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 0))});8104 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
8028 try f.writeCValue(writer, local, .Other);8105 try f.writeCValue(writer, local, .Other);
8029 try writer.print(" < {d}; ", .{8106 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, ty.vectorLen(zcu)))});
8030 try f.fmtIntLiteral(Type.usize, len_val),
8031 });
8032 try f.writeCValue(writer, local, .Other);8107 try f.writeCValue(writer, local, .Other);
8033 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(Type.usize, try mod.intValue(Type.usize, 1))});8108 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 1))});
8034 f.object.indent_writer.pushIndent();8109 f.object.indent_writer.pushIndent();
80358110
8036 break :index .{ .index = local };8111 break :index .{ .index = local };
...@@ -8054,16 +8129,16 @@ const Vectorize = struct {...@@ -8054,16 +8129,16 @@ const Vectorize = struct {
8054 }8129 }
8055};8130};
80568131
8057fn lowerFnRetTy(ret_ty: Type, mod: *Module) !Type {8132fn lowerFnRetTy(ret_ty: Type, zcu: *Zcu) !Type {
8058 if (ret_ty.ip_index == .noreturn_type) return Type.noreturn;8133 if (ret_ty.toIntern() == .noreturn_type) return Type.noreturn;
80598134
8060 if (lowersToArray(ret_ty, mod)) {8135 if (lowersToArray(ret_ty, zcu)) {
8061 const gpa = mod.gpa;8136 const gpa = zcu.gpa;
8062 const ip = &mod.intern_pool;8137 const ip = &zcu.intern_pool;
8063 const names = [1]InternPool.NullTerminatedString{8138 const names = [1]InternPool.NullTerminatedString{
8064 try ip.getOrPutString(gpa, "array"),8139 try ip.getOrPutString(gpa, "array"),
8065 };8140 };
8066 const types = [1]InternPool.Index{ret_ty.ip_index};8141 const types = [1]InternPool.Index{ret_ty.toIntern()};
8067 const values = [1]InternPool.Index{.none};8142 const values = [1]InternPool.Index{.none};
8068 const interned = try ip.getAnonStructType(gpa, .{8143 const interned = try ip.getAnonStructType(gpa, .{
8069 .names = &names,8144 .names = &names,
...@@ -8073,13 +8148,13 @@ fn lowerFnRetTy(ret_ty: Type, mod: *Module) !Type {...@@ -8073,13 +8148,13 @@ fn lowerFnRetTy(ret_ty: Type, mod: *Module) !Type {
8073 return Type.fromInterned(interned);8148 return Type.fromInterned(interned);
8074 }8149 }
80758150
8076 return if (ret_ty.hasRuntimeBitsIgnoreComptime(mod)) ret_ty else Type.void;8151 return if (ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) ret_ty else Type.void;
8077}8152}
80788153
8079fn lowersToArray(ty: Type, mod: *Module) bool {8154fn lowersToArray(ty: Type, zcu: *Zcu) bool {
8080 return switch (ty.zigTypeTag(mod)) {8155 return switch (ty.zigTypeTag(zcu)) {
8081 .Array, .Vector => return true,8156 .Array, .Vector => return true,
8082 else => return ty.isAbiInt(mod) and toCIntBits(@as(u32, @intCast(ty.bitSize(mod)))) == null,8157 else => return ty.isAbiInt(zcu) and toCIntBits(@as(u32, @intCast(ty.bitSize(zcu)))) == null,
8083 };8158 };
8084}8159}
80858160
...@@ -8098,7 +8173,7 @@ fn die(f: *Function, inst: Air.Inst.Index, ref: Air.Inst.Ref) !void {...@@ -8098,7 +8173,7 @@ fn die(f: *Function, inst: Air.Inst.Index, ref: Air.Inst.Ref) !void {
8098 const ref_inst = ref.toIndex() orelse return;8173 const ref_inst = ref.toIndex() orelse return;
8099 const c_value = (f.value_map.fetchRemove(ref) orelse return).value;8174 const c_value = (f.value_map.fetchRemove(ref) orelse return).value;
8100 const local_index = switch (c_value) {8175 const local_index = switch (c_value) {
8101 .local, .new_local => |l| l,8176 .new_local, .local => |l| l,
8102 else => return,8177 else => return,
8103 };8178 };
8104 try freeLocal(f, inst, local_index, ref_inst);8179 try freeLocal(f, inst, local_index, ref_inst);
src/codegen/c/type.zig+156-142
...@@ -3,10 +3,10 @@ const mem = std.mem;...@@ -3,10 +3,10 @@ const mem = std.mem;
3const Allocator = mem.Allocator;3const Allocator = mem.Allocator;
4const assert = std.debug.assert;4const assert = std.debug.assert;
5const autoHash = std.hash.autoHash;5const autoHash = std.hash.autoHash;
6const Target = std.Target;
76
8const Alignment = @import("../../InternPool.zig").Alignment;7const Alignment = @import("../../InternPool.zig").Alignment;
9const Module = @import("../../Module.zig");8const Zcu = @import("../../Module.zig");
9const Module = @import("../../Package/Module.zig");
10const InternPool = @import("../../InternPool.zig");10const InternPool = @import("../../InternPool.zig");
11const Type = @import("../../type.zig").Type;11const Type = @import("../../type.zig").Type;
1212
...@@ -280,7 +280,7 @@ pub const CType = extern union {...@@ -280,7 +280,7 @@ pub const CType = extern union {
280 };280 };
281 };281 };
282282
283 pub const AlignAs = struct {283 pub const AlignAs = packed struct {
284 @"align": Alignment,284 @"align": Alignment,
285 abi: Alignment,285 abi: Alignment,
286286
...@@ -298,19 +298,19 @@ pub const CType = extern union {...@@ -298,19 +298,19 @@ pub const CType = extern union {
298 Alignment.fromNonzeroByteUnits(abi_alignment),298 Alignment.fromNonzeroByteUnits(abi_alignment),
299 );299 );
300 }300 }
301 pub fn abiAlign(ty: Type, mod: *Module) AlignAs {301 pub fn abiAlign(ty: Type, zcu: *Zcu) AlignAs {
302 const abi_align = ty.abiAlignment(mod);302 const abi_align = ty.abiAlignment(zcu);
303 return init(abi_align, abi_align);303 return init(abi_align, abi_align);
304 }304 }
305 pub fn fieldAlign(struct_ty: Type, field_i: usize, mod: *Module) AlignAs {305 pub fn fieldAlign(struct_ty: Type, field_i: usize, zcu: *Zcu) AlignAs {
306 return init(306 return init(
307 struct_ty.structFieldAlign(field_i, mod),307 struct_ty.structFieldAlign(field_i, zcu),
308 struct_ty.structFieldType(field_i, mod).abiAlignment(mod),308 struct_ty.structFieldType(field_i, zcu).abiAlignment(zcu),
309 );309 );
310 }310 }
311 pub fn unionPayloadAlign(union_ty: Type, mod: *Module) AlignAs {311 pub fn unionPayloadAlign(union_ty: Type, zcu: *Zcu) AlignAs {
312 const union_obj = mod.typeToUnion(union_ty).?;312 const union_obj = zcu.typeToUnion(union_ty).?;
313 const union_payload_align = mod.unionAbiAlignment(union_obj);313 const union_payload_align = zcu.unionAbiAlignment(union_obj);
314 return init(union_payload_align, union_payload_align);314 return init(union_payload_align, union_payload_align);
315 }315 }
316316
...@@ -356,8 +356,8 @@ pub const CType = extern union {...@@ -356,8 +356,8 @@ pub const CType = extern union {
356 return self.map.entries.items(.hash)[index - Tag.no_payload_count];356 return self.map.entries.items(.hash)[index - Tag.no_payload_count];
357 }357 }
358358
359 pub fn typeToIndex(self: Set, ty: Type, mod: *Module, kind: Kind) ?Index {359 pub fn typeToIndex(self: Set, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) ?Index {
360 const lookup = Convert.Lookup{ .imm = .{ .set = &self, .mod = mod } };360 const lookup = Convert.Lookup{ .imm = .{ .set = &self, .zcu = zcu, .mod = mod } };
361361
362 var convert: Convert = undefined;362 var convert: Convert = undefined;
363 convert.initType(ty, kind, lookup) catch unreachable;363 convert.initType(ty, kind, lookup) catch unreachable;
...@@ -398,10 +398,11 @@ pub const CType = extern union {...@@ -398,10 +398,11 @@ pub const CType = extern union {
398 pub fn typeToIndex(398 pub fn typeToIndex(
399 self: *Promoted,399 self: *Promoted,
400 ty: Type,400 ty: Type,
401 zcu: *Zcu,
401 mod: *Module,402 mod: *Module,
402 kind: Kind,403 kind: Kind,
403 ) Allocator.Error!Index {404 ) Allocator.Error!Index {
404 const lookup = Convert.Lookup{ .mut = .{ .promoted = self, .mod = mod } };405 const lookup = Convert.Lookup{ .mut = .{ .promoted = self, .zcu = zcu, .mod = mod } };
405406
406 var convert: Convert = undefined;407 var convert: Convert = undefined;
407 try convert.initType(ty, kind, lookup);408 try convert.initType(ty, kind, lookup);
...@@ -417,7 +418,7 @@ pub const CType = extern union {...@@ -417,7 +418,7 @@ pub const CType = extern union {
417 );418 );
418 if (!gop.found_existing) {419 if (!gop.found_existing) {
419 errdefer _ = self.set.map.pop();420 errdefer _ = self.set.map.pop();
420 gop.key_ptr.* = try createFromConvert(self, ty, lookup.getModule(), kind, convert);421 gop.key_ptr.* = try createFromConvert(self, ty, zcu, mod, kind, convert);
421 }422 }
422 if (std.debug.runtime_safety) {423 if (std.debug.runtime_safety) {
423 const adapter = TypeAdapter64{424 const adapter = TypeAdapter64{
...@@ -457,15 +458,15 @@ pub const CType = extern union {...@@ -457,15 +458,15 @@ pub const CType = extern union {
457 return promoted.cTypeToIndex(cty);458 return promoted.cTypeToIndex(cty);
458 }459 }
459460
460 pub fn typeToCType(self: *Store, gpa: Allocator, ty: Type, mod: *Module, kind: Kind) !CType {461 pub fn typeToCType(self: *Store, gpa: Allocator, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) !CType {
461 const idx = try self.typeToIndex(gpa, ty, mod, kind);462 const idx = try self.typeToIndex(gpa, ty, zcu, mod, kind);
462 return self.indexToCType(idx);463 return self.indexToCType(idx);
463 }464 }
464465
465 pub fn typeToIndex(self: *Store, gpa: Allocator, ty: Type, mod: *Module, kind: Kind) !Index {466 pub fn typeToIndex(self: *Store, gpa: Allocator, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) !Index {
466 var promoted = self.promote(gpa);467 var promoted = self.promote(gpa);
467 defer self.demote(promoted);468 defer self.demote(promoted);
468 return promoted.typeToIndex(ty, mod, kind);469 return promoted.typeToIndex(ty, zcu, mod, kind);
469 }470 }
470471
471 pub fn clearRetainingCapacity(self: *Store, gpa: Allocator) void {472 pub fn clearRetainingCapacity(self: *Store, gpa: Allocator) void {
...@@ -549,9 +550,9 @@ pub const CType = extern union {...@@ -549,9 +550,9 @@ pub const CType = extern union {
549 };550 };
550 }551 }
551552
552 pub fn signedness(self: CType, target: std.Target) std.builtin.Signedness {553 pub fn signedness(self: CType, mod: *Module) std.builtin.Signedness {
553 return switch (self.tag()) {554 return switch (self.tag()) {
554 .char => target.charSignedness(),555 .char => mod.resolved_target.result.charSignedness(),
555 .@"signed char",556 .@"signed char",
556 .short,557 .short,
557 .int,558 .int,
...@@ -854,7 +855,8 @@ pub const CType = extern union {...@@ -854,7 +855,8 @@ pub const CType = extern union {
854 }855 }
855 }856 }
856857
857 pub fn floatActiveBits(self: CType, target: Target) u16 {858 pub fn floatActiveBits(self: CType, mod: *Module) u16 {
859 const target = &mod.resolved_target.result;
858 return switch (self.tag()) {860 return switch (self.tag()) {
859 .float => target.c_type_bit_size(.float),861 .float => target.c_type_bit_size(.float),
860 .double => target.c_type_bit_size(.double),862 .double => target.c_type_bit_size(.double),
...@@ -868,7 +870,8 @@ pub const CType = extern union {...@@ -868,7 +870,8 @@ pub const CType = extern union {
868 };870 };
869 }871 }
870872
871 pub fn byteSize(self: CType, store: Store.Set, target: Target) u64 {873 pub fn byteSize(self: CType, store: Store.Set, mod: *Module) u64 {
874 const target = &mod.resolved_target.result;
872 return switch (self.tag()) {875 return switch (self.tag()) {
873 .void => 0,876 .void => 0,
874 .char, .@"signed char", ._Bool, .@"unsigned char", .bool, .uint8_t, .int8_t => 1,877 .char, .@"signed char", ._Bool, .@"unsigned char", .bool, .uint8_t, .int8_t => 1,
...@@ -906,7 +909,7 @@ pub const CType = extern union {...@@ -906,7 +909,7 @@ pub const CType = extern union {
906 .vector,909 .vector,
907 => {910 => {
908 const data = self.cast(Payload.Sequence).?.data;911 const data = self.cast(Payload.Sequence).?.data;
909 return data.len * store.indexToCType(data.elem_type).byteSize(store, target);912 return data.len * store.indexToCType(data.elem_type).byteSize(store, mod);
910 },913 },
911914
912 .fwd_anon_struct,915 .fwd_anon_struct,
...@@ -1248,13 +1251,18 @@ pub const CType = extern union {...@@ -1248,13 +1251,18 @@ pub const CType = extern union {
1248 }1251 }
12491252
1250 pub const Lookup = union(enum) {1253 pub const Lookup = union(enum) {
1251 fail: *Module,1254 fail: struct {
1255 zcu: *Zcu,
1256 mod: *Module,
1257 },
1252 imm: struct {1258 imm: struct {
1253 set: *const Store.Set,1259 set: *const Store.Set,
1260 zcu: *Zcu,
1254 mod: *Module,1261 mod: *Module,
1255 },1262 },
1256 mut: struct {1263 mut: struct {
1257 promoted: *Store.Promoted,1264 promoted: *Store.Promoted,
1265 zcu: *Zcu,
1258 mod: *Module,1266 mod: *Module,
1259 },1267 },
12601268
...@@ -1265,15 +1273,15 @@ pub const CType = extern union {...@@ -1265,15 +1273,15 @@ pub const CType = extern union {
1265 };1273 };
1266 }1274 }
12671275
1268 pub fn getTarget(self: @This()) Target {1276 pub fn getZcu(self: @This()) *Zcu {
1269 return self.getModule().getTarget();1277 return switch (self) {
1278 inline else => |pl| pl.zcu,
1279 };
1270 }1280 }
12711281
1272 pub fn getModule(self: @This()) *Module {1282 pub fn getModule(self: @This()) *Module {
1273 return switch (self) {1283 return switch (self) {
1274 .fail => |mod| mod,1284 inline else => |pl| pl.mod,
1275 .imm => |imm| imm.mod,
1276 .mut => |mut| mut.mod,
1277 };1285 };
1278 }1286 }
12791287
...@@ -1288,8 +1296,8 @@ pub const CType = extern union {...@@ -1288,8 +1296,8 @@ pub const CType = extern union {
1288 pub fn typeToIndex(self: @This(), ty: Type, kind: Kind) !?Index {1296 pub fn typeToIndex(self: @This(), ty: Type, kind: Kind) !?Index {
1289 return switch (self) {1297 return switch (self) {
1290 .fail => null,1298 .fail => null,
1291 .imm => |imm| imm.set.typeToIndex(ty, imm.mod, kind),1299 .imm => |imm| imm.set.typeToIndex(ty, imm.zcu, imm.mod, kind),
1292 .mut => |mut| try mut.promoted.typeToIndex(ty, mut.mod, kind),1300 .mut => |mut| try mut.promoted.typeToIndex(ty, mut.zcu, mut.mod, kind),
1293 };1301 };
1294 }1302 }
12951303
...@@ -1300,7 +1308,7 @@ pub const CType = extern union {...@@ -1300,7 +1308,7 @@ pub const CType = extern union {
1300 pub fn freeze(self: @This()) @This() {1308 pub fn freeze(self: @This()) @This() {
1301 return switch (self) {1309 return switch (self) {
1302 .fail, .imm => self,1310 .fail, .imm => self,
1303 .mut => |mut| .{ .imm = .{ .set = &mut.promoted.set, .mod = mut.mod } },1311 .mut => |mut| .{ .imm = .{ .set = &mut.promoted.set, .zcu = mut.zcu, .mod = mut.mod } },
1304 };1312 };
1305 }1313 }
1306 };1314 };
...@@ -1354,7 +1362,7 @@ pub const CType = extern union {...@@ -1354,7 +1362,7 @@ pub const CType = extern union {
1354 self.storage.anon.fields[0] = .{1362 self.storage.anon.fields[0] = .{
1355 .name = "array",1363 .name = "array",
1356 .type = array_idx,1364 .type = array_idx,
1357 .alignas = AlignAs.abiAlign(ty, lookup.getModule()),1365 .alignas = AlignAs.abiAlign(ty, lookup.getZcu()),
1358 };1366 };
1359 self.initAnon(kind, fwd_idx, 1);1367 self.initAnon(kind, fwd_idx, 1);
1360 } else self.init(switch (kind) {1368 } else self.init(switch (kind) {
...@@ -1366,13 +1374,13 @@ pub const CType = extern union {...@@ -1366,13 +1374,13 @@ pub const CType = extern union {
1366 }1374 }
13671375
1368 pub fn initType(self: *@This(), ty: Type, kind: Kind, lookup: Lookup) !void {1376 pub fn initType(self: *@This(), ty: Type, kind: Kind, lookup: Lookup) !void {
1369 const mod = lookup.getModule();1377 const zcu = lookup.getZcu();
1370 const ip = &mod.intern_pool;1378 const ip = &zcu.intern_pool;
13711379
1372 self.* = undefined;1380 self.* = undefined;
1373 if (!ty.isFnOrHasRuntimeBitsIgnoreComptime(mod))1381 if (!ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu))
1374 self.init(.void)1382 self.init(.void)
1375 else if (ty.isAbiInt(mod)) switch (ty.ip_index) {1383 else if (ty.isAbiInt(zcu)) switch (ty.ip_index) {
1376 .usize_type => self.init(.uintptr_t),1384 .usize_type => self.init(.uintptr_t),
1377 .isize_type => self.init(.intptr_t),1385 .isize_type => self.init(.intptr_t),
1378 .c_char_type => self.init(.char),1386 .c_char_type => self.init(.char),
...@@ -1384,13 +1392,13 @@ pub const CType = extern union {...@@ -1384,13 +1392,13 @@ pub const CType = extern union {
1384 .c_ulong_type => self.init(.@"unsigned long"),1392 .c_ulong_type => self.init(.@"unsigned long"),
1385 .c_longlong_type => self.init(.@"long long"),1393 .c_longlong_type => self.init(.@"long long"),
1386 .c_ulonglong_type => self.init(.@"unsigned long long"),1394 .c_ulonglong_type => self.init(.@"unsigned long long"),
1387 else => switch (tagFromIntInfo(ty.intInfo(mod))) {1395 else => switch (tagFromIntInfo(ty.intInfo(zcu))) {
1388 .void => unreachable,1396 .void => unreachable,
1389 else => |t| self.init(t),1397 else => |t| self.init(t),
1390 .array => switch (kind) {1398 .array => switch (kind) {
1391 .forward, .complete, .global => {1399 .forward, .complete, .global => {
1392 const abi_size = ty.abiSize(mod);1400 const abi_size = ty.abiSize(zcu);
1393 const abi_align = ty.abiAlignment(mod).toByteUnits(0);1401 const abi_align = ty.abiAlignment(zcu).toByteUnits(0);
1394 self.storage = .{ .seq = .{ .base = .{ .tag = .array }, .data = .{1402 self.storage = .{ .seq = .{ .base = .{ .tag = .array }, .data = .{
1395 .len = @divExact(abi_size, abi_align),1403 .len = @divExact(abi_size, abi_align),
1396 .elem_type = tagFromIntInfo(.{1404 .elem_type = tagFromIntInfo(.{
...@@ -1406,7 +1414,7 @@ pub const CType = extern union {...@@ -1406,7 +1414,7 @@ pub const CType = extern union {
1406 .payload => unreachable,1414 .payload => unreachable,
1407 },1415 },
1408 },1416 },
1409 } else switch (ty.zigTypeTag(mod)) {1417 } else switch (ty.zigTypeTag(zcu)) {
1410 .Frame => unreachable,1418 .Frame => unreachable,
1411 .AnyFrame => unreachable,1419 .AnyFrame => unreachable,
14121420
...@@ -1436,7 +1444,7 @@ pub const CType = extern union {...@@ -1436,7 +1444,7 @@ pub const CType = extern union {
1436 }),1444 }),
14371445
1438 .Pointer => {1446 .Pointer => {
1439 const info = ty.ptrInfo(mod);1447 const info = ty.ptrInfo(zcu);
1440 switch (info.flags.size) {1448 switch (info.flags.size) {
1441 .Slice => {1449 .Slice => {
1442 if (switch (kind) {1450 if (switch (kind) {
...@@ -1444,18 +1452,18 @@ pub const CType = extern union {...@@ -1444,18 +1452,18 @@ pub const CType = extern union {
1444 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),1452 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),
1445 .payload => unreachable,1453 .payload => unreachable,
1446 }) |fwd_idx| {1454 }) |fwd_idx| {
1447 const ptr_ty = ty.slicePtrFieldType(mod);1455 const ptr_ty = ty.slicePtrFieldType(zcu);
1448 if (try lookup.typeToIndex(ptr_ty, kind)) |ptr_idx| {1456 if (try lookup.typeToIndex(ptr_ty, kind)) |ptr_idx| {
1449 self.storage = .{ .anon = undefined };1457 self.storage = .{ .anon = undefined };
1450 self.storage.anon.fields[0] = .{1458 self.storage.anon.fields[0] = .{
1451 .name = "ptr",1459 .name = "ptr",
1452 .type = ptr_idx,1460 .type = ptr_idx,
1453 .alignas = AlignAs.abiAlign(ptr_ty, mod),1461 .alignas = AlignAs.abiAlign(ptr_ty, zcu),
1454 };1462 };
1455 self.storage.anon.fields[1] = .{1463 self.storage.anon.fields[1] = .{
1456 .name = "len",1464 .name = "len",
1457 .type = Tag.uintptr_t.toIndex(),1465 .type = Tag.uintptr_t.toIndex(),
1458 .alignas = AlignAs.abiAlign(Type.usize, mod),1466 .alignas = AlignAs.abiAlign(Type.usize, zcu),
1459 };1467 };
1460 self.initAnon(kind, fwd_idx, 2);1468 self.initAnon(kind, fwd_idx, 2);
1461 } else self.init(switch (kind) {1469 } else self.init(switch (kind) {
...@@ -1478,11 +1486,16 @@ pub const CType = extern union {...@@ -1478,11 +1486,16 @@ pub const CType = extern union {
1478 },1486 },
1479 };1487 };
14801488
1481 const pointee_ty = if (info.packed_offset.host_size > 0 and1489 const pointee_ty = if (info.packed_offset.host_size > 0 and info.flags.vector_index == .none)
1482 info.flags.vector_index == .none)1490 try zcu.intType(.unsigned, info.packed_offset.host_size * 8)
1483 try mod.intType(.unsigned, info.packed_offset.host_size * 8)1491 else if (info.flags.alignment == .none or
1492 info.flags.alignment.compareStrict(.gte, Type.fromInterned(info.child).abiAlignment(zcu)))
1493 Type.fromInterned(info.child)
1484 else1494 else
1485 Type.fromInterned(info.child);1495 try zcu.intType(.unsigned, @min(
1496 info.flags.alignment.toByteUnitsOptional().?,
1497 lookup.getModule().resolved_target.result.maxIntAlignment(),
1498 ) * 8);
14861499
1487 if (try lookup.typeToIndex(pointee_ty, .forward)) |child_idx| {1500 if (try lookup.typeToIndex(pointee_ty, .forward)) |child_idx| {
1488 self.storage = .{ .child = .{1501 self.storage = .{ .child = .{
...@@ -1495,24 +1508,24 @@ pub const CType = extern union {...@@ -1495,24 +1508,24 @@ pub const CType = extern union {
1495 }1508 }
1496 },1509 },
14971510
1498 .Struct, .Union => |zig_ty_tag| if (ty.containerLayout(mod) == .@"packed") {1511 .Struct, .Union => |zig_ty_tag| if (ty.containerLayout(zcu) == .@"packed") {
1499 if (mod.typeToPackedStruct(ty)) |packed_struct| {1512 if (zcu.typeToPackedStruct(ty)) |packed_struct| {
1500 try self.initType(Type.fromInterned(packed_struct.backingIntType(ip).*), kind, lookup);1513 try self.initType(Type.fromInterned(packed_struct.backingIntType(ip).*), kind, lookup);
1501 } else {1514 } else {
1502 const bits: u16 = @intCast(ty.bitSize(mod));1515 const bits: u16 = @intCast(ty.bitSize(zcu));
1503 const int_ty = try mod.intType(.unsigned, bits);1516 const int_ty = try zcu.intType(.unsigned, bits);
1504 try self.initType(int_ty, kind, lookup);1517 try self.initType(int_ty, kind, lookup);
1505 }1518 }
1506 } else if (ty.isTupleOrAnonStruct(mod)) {1519 } else if (ty.isTupleOrAnonStruct(zcu)) {
1507 if (lookup.isMutable()) {1520 if (lookup.isMutable()) {
1508 for (0..switch (zig_ty_tag) {1521 for (0..switch (zig_ty_tag) {
1509 .Struct => ty.structFieldCount(mod),1522 .Struct => ty.structFieldCount(zcu),
1510 .Union => mod.typeToUnion(ty).?.field_types.len,1523 .Union => zcu.typeToUnion(ty).?.field_types.len,
1511 else => unreachable,1524 else => unreachable,
1512 }) |field_i| {1525 }) |field_i| {
1513 const field_ty = ty.structFieldType(field_i, mod);1526 const field_ty = ty.structFieldType(field_i, zcu);
1514 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or1527 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1515 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1528 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1516 _ = try lookup.typeToIndex(field_ty, switch (kind) {1529 _ = try lookup.typeToIndex(field_ty, switch (kind) {
1517 .forward, .forward_parameter => .forward,1530 .forward, .forward_parameter => .forward,
1518 .complete, .parameter => .complete,1531 .complete, .parameter => .complete,
...@@ -1540,14 +1553,14 @@ pub const CType = extern union {...@@ -1540,14 +1553,14 @@ pub const CType = extern union {
1540 .payload => unreachable,1553 .payload => unreachable,
1541 });1554 });
1542 } else {1555 } else {
1543 const tag_ty = ty.unionTagTypeSafety(mod);1556 const tag_ty = ty.unionTagTypeSafety(zcu);
1544 const is_tagged_union_wrapper = kind != .payload and tag_ty != null;1557 const is_tagged_union_wrapper = kind != .payload and tag_ty != null;
1545 const is_struct = zig_ty_tag == .Struct or is_tagged_union_wrapper;1558 const is_struct = zig_ty_tag == .Struct or is_tagged_union_wrapper;
1546 switch (kind) {1559 switch (kind) {
1547 .forward, .forward_parameter => {1560 .forward, .forward_parameter => {
1548 self.storage = .{ .fwd = .{1561 self.storage = .{ .fwd = .{
1549 .base = .{ .tag = if (is_struct) .fwd_struct else .fwd_union },1562 .base = .{ .tag = if (is_struct) .fwd_struct else .fwd_union },
1550 .data = ty.getOwnerDecl(mod),1563 .data = ty.getOwnerDecl(zcu),
1551 } };1564 } };
1552 self.value = .{ .cty = initPayload(&self.storage.fwd) };1565 self.value = .{ .cty = initPayload(&self.storage.fwd) };
1553 },1566 },
...@@ -1562,7 +1575,7 @@ pub const CType = extern union {...@@ -1562,7 +1575,7 @@ pub const CType = extern union {
1562 self.storage.anon.fields[field_count] = .{1575 self.storage.anon.fields[field_count] = .{
1563 .name = "payload",1576 .name = "payload",
1564 .type = payload_idx.?,1577 .type = payload_idx.?,
1565 .alignas = AlignAs.unionPayloadAlign(ty, mod),1578 .alignas = AlignAs.unionPayloadAlign(ty, zcu),
1566 };1579 };
1567 field_count += 1;1580 field_count += 1;
1568 }1581 }
...@@ -1570,7 +1583,7 @@ pub const CType = extern union {...@@ -1570,7 +1583,7 @@ pub const CType = extern union {
1570 self.storage.anon.fields[field_count] = .{1583 self.storage.anon.fields[field_count] = .{
1571 .name = "tag",1584 .name = "tag",
1572 .type = tag_idx.?,1585 .type = tag_idx.?,
1573 .alignas = AlignAs.abiAlign(tag_ty.?, mod),1586 .alignas = AlignAs.abiAlign(tag_ty.?, zcu),
1574 };1587 };
1575 field_count += 1;1588 field_count += 1;
1576 }1589 }
...@@ -1583,19 +1596,19 @@ pub const CType = extern union {...@@ -1583,19 +1596,19 @@ pub const CType = extern union {
1583 } };1596 } };
1584 self.value = .{ .cty = initPayload(&self.storage.anon.pl.complete) };1597 self.value = .{ .cty = initPayload(&self.storage.anon.pl.complete) };
1585 } else self.init(.@"struct");1598 } else self.init(.@"struct");
1586 } else if (kind == .payload and ty.unionHasAllZeroBitFieldTypes(mod)) {1599 } else if (kind == .payload and ty.unionHasAllZeroBitFieldTypes(zcu)) {
1587 self.init(.void);1600 self.init(.void);
1588 } else {1601 } else {
1589 var is_packed = false;1602 var is_packed = false;
1590 for (0..switch (zig_ty_tag) {1603 for (0..switch (zig_ty_tag) {
1591 .Struct => ty.structFieldCount(mod),1604 .Struct => ty.structFieldCount(zcu),
1592 .Union => mod.typeToUnion(ty).?.field_types.len,1605 .Union => zcu.typeToUnion(ty).?.field_types.len,
1593 else => unreachable,1606 else => unreachable,
1594 }) |field_i| {1607 }) |field_i| {
1595 const field_ty = ty.structFieldType(field_i, mod);1608 const field_ty = ty.structFieldType(field_i, zcu);
1596 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1609 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
15971610
1598 const field_align = AlignAs.fieldAlign(ty, field_i, mod);1611 const field_align = AlignAs.fieldAlign(ty, field_i, zcu);
1599 if (field_align.abiOrder().compare(.lt)) {1612 if (field_align.abiOrder().compare(.lt)) {
1600 is_packed = true;1613 is_packed = true;
1601 if (!lookup.isMutable()) break;1614 if (!lookup.isMutable()) break;
...@@ -1634,9 +1647,9 @@ pub const CType = extern union {...@@ -1634,9 +1647,9 @@ pub const CType = extern union {
1634 .Vector => .vector,1647 .Vector => .vector,
1635 else => unreachable,1648 else => unreachable,
1636 };1649 };
1637 if (try lookup.typeToIndex(ty.childType(mod), kind)) |child_idx| {1650 if (try lookup.typeToIndex(ty.childType(zcu), kind)) |child_idx| {
1638 self.storage = .{ .seq = .{ .base = .{ .tag = t }, .data = .{1651 self.storage = .{ .seq = .{ .base = .{ .tag = t }, .data = .{
1639 .len = ty.arrayLenIncludingSentinel(mod),1652 .len = ty.arrayLenIncludingSentinel(zcu),
1640 .elem_type = child_idx,1653 .elem_type = child_idx,
1641 } } };1654 } } };
1642 self.value = .{ .cty = initPayload(&self.storage.seq) };1655 self.value = .{ .cty = initPayload(&self.storage.seq) };
...@@ -1648,9 +1661,9 @@ pub const CType = extern union {...@@ -1648,9 +1661,9 @@ pub const CType = extern union {
1648 },1661 },
16491662
1650 .Optional => {1663 .Optional => {
1651 const payload_ty = ty.optionalChild(mod);1664 const payload_ty = ty.optionalChild(zcu);
1652 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {1665 if (payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1653 if (ty.optionalReprIsPayload(mod)) {1666 if (ty.optionalReprIsPayload(zcu)) {
1654 try self.initType(payload_ty, kind, lookup);1667 try self.initType(payload_ty, kind, lookup);
1655 } else if (switch (kind) {1668 } else if (switch (kind) {
1656 .forward, .forward_parameter => @as(Index, undefined),1669 .forward, .forward_parameter => @as(Index, undefined),
...@@ -1667,12 +1680,12 @@ pub const CType = extern union {...@@ -1667,12 +1680,12 @@ pub const CType = extern union {
1667 self.storage.anon.fields[0] = .{1680 self.storage.anon.fields[0] = .{
1668 .name = "payload",1681 .name = "payload",
1669 .type = payload_idx,1682 .type = payload_idx,
1670 .alignas = AlignAs.abiAlign(payload_ty, mod),1683 .alignas = AlignAs.abiAlign(payload_ty, zcu),
1671 };1684 };
1672 self.storage.anon.fields[1] = .{1685 self.storage.anon.fields[1] = .{
1673 .name = "is_null",1686 .name = "is_null",
1674 .type = Tag.bool.toIndex(),1687 .type = Tag.bool.toIndex(),
1675 .alignas = AlignAs.abiAlign(Type.bool, mod),1688 .alignas = AlignAs.abiAlign(Type.bool, zcu),
1676 };1689 };
1677 self.initAnon(kind, fwd_idx, 2);1690 self.initAnon(kind, fwd_idx, 2);
1678 } else self.init(switch (kind) {1691 } else self.init(switch (kind) {
...@@ -1690,14 +1703,14 @@ pub const CType = extern union {...@@ -1690,14 +1703,14 @@ pub const CType = extern union {
1690 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),1703 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),
1691 .payload => unreachable,1704 .payload => unreachable,
1692 }) |fwd_idx| {1705 }) |fwd_idx| {
1693 const payload_ty = ty.errorUnionPayload(mod);1706 const payload_ty = ty.errorUnionPayload(zcu);
1694 if (try lookup.typeToIndex(payload_ty, switch (kind) {1707 if (try lookup.typeToIndex(payload_ty, switch (kind) {
1695 .forward, .forward_parameter => .forward,1708 .forward, .forward_parameter => .forward,
1696 .complete, .parameter => .complete,1709 .complete, .parameter => .complete,
1697 .global => .global,1710 .global => .global,
1698 .payload => unreachable,1711 .payload => unreachable,
1699 })) |payload_idx| {1712 })) |payload_idx| {
1700 const error_ty = ty.errorUnionSet(mod);1713 const error_ty = ty.errorUnionSet(zcu);
1701 if (payload_idx == Tag.void.toIndex()) {1714 if (payload_idx == Tag.void.toIndex()) {
1702 try self.initType(error_ty, kind, lookup);1715 try self.initType(error_ty, kind, lookup);
1703 } else if (try lookup.typeToIndex(error_ty, kind)) |error_idx| {1716 } else if (try lookup.typeToIndex(error_ty, kind)) |error_idx| {
...@@ -1705,12 +1718,12 @@ pub const CType = extern union {...@@ -1705,12 +1718,12 @@ pub const CType = extern union {
1705 self.storage.anon.fields[0] = .{1718 self.storage.anon.fields[0] = .{
1706 .name = "payload",1719 .name = "payload",
1707 .type = payload_idx,1720 .type = payload_idx,
1708 .alignas = AlignAs.abiAlign(payload_ty, mod),1721 .alignas = AlignAs.abiAlign(payload_ty, zcu),
1709 };1722 };
1710 self.storage.anon.fields[1] = .{1723 self.storage.anon.fields[1] = .{
1711 .name = "error",1724 .name = "error",
1712 .type = error_idx,1725 .type = error_idx,
1713 .alignas = AlignAs.abiAlign(error_ty, mod),1726 .alignas = AlignAs.abiAlign(error_ty, zcu),
1714 };1727 };
1715 self.initAnon(kind, fwd_idx, 2);1728 self.initAnon(kind, fwd_idx, 2);
1716 } else self.init(switch (kind) {1729 } else self.init(switch (kind) {
...@@ -1729,7 +1742,7 @@ pub const CType = extern union {...@@ -1729,7 +1742,7 @@ pub const CType = extern union {
1729 .Opaque => self.init(.void),1742 .Opaque => self.init(.void),
17301743
1731 .Fn => {1744 .Fn => {
1732 const info = mod.typeToFunc(ty).?;1745 const info = zcu.typeToFunc(ty).?;
1733 if (!info.is_generic) {1746 if (!info.is_generic) {
1734 if (lookup.isMutable()) {1747 if (lookup.isMutable()) {
1735 const param_kind: Kind = switch (kind) {1748 const param_kind: Kind = switch (kind) {
...@@ -1739,7 +1752,7 @@ pub const CType = extern union {...@@ -1739,7 +1752,7 @@ pub const CType = extern union {
1739 };1752 };
1740 _ = try lookup.typeToIndex(Type.fromInterned(info.return_type), param_kind);1753 _ = try lookup.typeToIndex(Type.fromInterned(info.return_type), param_kind);
1741 for (info.param_types.get(ip)) |param_type| {1754 for (info.param_types.get(ip)) |param_type| {
1742 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;1755 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
1743 _ = try lookup.typeToIndex(Type.fromInterned(param_type), param_kind);1756 _ = try lookup.typeToIndex(Type.fromInterned(param_type), param_kind);
1744 }1757 }
1745 }1758 }
...@@ -1906,20 +1919,21 @@ pub const CType = extern union {...@@ -1906,20 +1919,21 @@ pub const CType = extern union {
1906 }1919 }
1907 }1920 }
19081921
1909 fn createFromType(store: *Store.Promoted, ty: Type, mod: *Module, kind: Kind) !CType {1922 fn createFromType(store: *Store.Promoted, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) !CType {
1910 var convert: Convert = undefined;1923 var convert: Convert = undefined;
1911 try convert.initType(ty, kind, .{ .imm = .{ .set = &store.set, .mod = mod } });1924 try convert.initType(ty, kind, .{ .imm = .{ .set = &store.set, .zcu = zcu } });
1912 return createFromConvert(store, ty, mod, kind, &convert);1925 return createFromConvert(store, ty, zcu, mod, kind, &convert);
1913 }1926 }
19141927
1915 fn createFromConvert(1928 fn createFromConvert(
1916 store: *Store.Promoted,1929 store: *Store.Promoted,
1917 ty: Type,1930 ty: Type,
1931 zcu: *Zcu,
1918 mod: *Module,1932 mod: *Module,
1919 kind: Kind,1933 kind: Kind,
1920 convert: Convert,1934 convert: Convert,
1921 ) !CType {1935 ) !CType {
1922 const ip = &mod.intern_pool;1936 const ip = &zcu.intern_pool;
1923 const arena = store.arena.allocator();1937 const arena = store.arena.allocator();
1924 switch (convert.value) {1938 switch (convert.value) {
1925 .cty => |c| return c.copy(arena),1939 .cty => |c| return c.copy(arena),
...@@ -1937,18 +1951,18 @@ pub const CType = extern union {...@@ -1937,18 +1951,18 @@ pub const CType = extern union {
1937 .packed_struct,1951 .packed_struct,
1938 .packed_union,1952 .packed_union,
1939 => {1953 => {
1940 const zig_ty_tag = ty.zigTypeTag(mod);1954 const zig_ty_tag = ty.zigTypeTag(zcu);
1941 const fields_len = switch (zig_ty_tag) {1955 const fields_len = switch (zig_ty_tag) {
1942 .Struct => ty.structFieldCount(mod),1956 .Struct => ty.structFieldCount(zcu),
1943 .Union => mod.typeToUnion(ty).?.field_types.len,1957 .Union => zcu.typeToUnion(ty).?.field_types.len,
1944 else => unreachable,1958 else => unreachable,
1945 };1959 };
19461960
1947 var c_fields_len: usize = 0;1961 var c_fields_len: usize = 0;
1948 for (0..fields_len) |field_i| {1962 for (0..fields_len) |field_i| {
1949 const field_ty = ty.structFieldType(field_i, mod);1963 const field_ty = ty.structFieldType(field_i, zcu);
1950 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or1964 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1951 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1965 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1952 c_fields_len += 1;1966 c_fields_len += 1;
1953 }1967 }
19541968
...@@ -1956,26 +1970,26 @@ pub const CType = extern union {...@@ -1956,26 +1970,26 @@ pub const CType = extern union {
1956 var c_field_i: usize = 0;1970 var c_field_i: usize = 0;
1957 for (0..fields_len) |field_i_usize| {1971 for (0..fields_len) |field_i_usize| {
1958 const field_i: u32 = @intCast(field_i_usize);1972 const field_i: u32 = @intCast(field_i_usize);
1959 const field_ty = ty.structFieldType(field_i, mod);1973 const field_ty = ty.structFieldType(field_i, zcu);
1960 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or1974 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1961 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;1975 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
19621976
1963 defer c_field_i += 1;1977 defer c_field_i += 1;
1964 fields_pl[c_field_i] = .{1978 fields_pl[c_field_i] = .{
1965 .name = try if (ty.isSimpleTuple(mod))1979 .name = try if (ty.isSimpleTuple(zcu))
1966 std.fmt.allocPrintZ(arena, "f{}", .{field_i})1980 std.fmt.allocPrintZ(arena, "f{}", .{field_i})
1967 else1981 else
1968 arena.dupeZ(u8, ip.stringToSlice(switch (zig_ty_tag) {1982 arena.dupeZ(u8, ip.stringToSlice(switch (zig_ty_tag) {
1969 .Struct => ty.legacyStructFieldName(field_i, mod),1983 .Struct => ty.legacyStructFieldName(field_i, zcu),
1970 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],1984 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
1971 else => unreachable,1985 else => unreachable,
1972 })),1986 })),
1973 .type = store.set.typeToIndex(field_ty, mod, switch (kind) {1987 .type = store.set.typeToIndex(field_ty, zcu, mod, switch (kind) {
1974 .forward, .forward_parameter => .forward,1988 .forward, .forward_parameter => .forward,
1975 .complete, .parameter, .payload => .complete,1989 .complete, .parameter, .payload => .complete,
1976 .global => .global,1990 .global => .global,
1977 }).?,1991 }).?,
1978 .alignas = AlignAs.fieldAlign(ty, field_i, mod),1992 .alignas = AlignAs.fieldAlign(ty, field_i, zcu),
1979 };1993 };
1980 }1994 }
19811995
...@@ -1996,8 +2010,8 @@ pub const CType = extern union {...@@ -1996,8 +2010,8 @@ pub const CType = extern union {
1996 const unnamed_pl = try arena.create(Payload.Unnamed);2010 const unnamed_pl = try arena.create(Payload.Unnamed);
1997 unnamed_pl.* = .{ .base = .{ .tag = t }, .data = .{2011 unnamed_pl.* = .{ .base = .{ .tag = t }, .data = .{
1998 .fields = fields_pl,2012 .fields = fields_pl,
1999 .owner_decl = ty.getOwnerDecl(mod),2013 .owner_decl = ty.getOwnerDecl(zcu),
2000 .id = if (ty.unionTagTypeSafety(mod)) |_| 0 else unreachable,2014 .id = if (ty.unionTagTypeSafety(zcu)) |_| 0 else unreachable,
2001 } };2015 } };
2002 return initPayload(unnamed_pl);2016 return initPayload(unnamed_pl);
2003 },2017 },
...@@ -2012,7 +2026,7 @@ pub const CType = extern union {...@@ -2012,7 +2026,7 @@ pub const CType = extern union {
2012 const struct_pl = try arena.create(Payload.Aggregate);2026 const struct_pl = try arena.create(Payload.Aggregate);
2013 struct_pl.* = .{ .base = .{ .tag = t }, .data = .{2027 struct_pl.* = .{ .base = .{ .tag = t }, .data = .{
2014 .fields = fields_pl,2028 .fields = fields_pl,
2015 .fwd_decl = store.set.typeToIndex(ty, mod, .forward).?,2029 .fwd_decl = store.set.typeToIndex(ty, zcu, mod, .forward).?,
2016 } };2030 } };
2017 return initPayload(struct_pl);2031 return initPayload(struct_pl);
2018 },2032 },
...@@ -2024,7 +2038,7 @@ pub const CType = extern union {...@@ -2024,7 +2038,7 @@ pub const CType = extern union {
2024 .function,2038 .function,
2025 .varargs_function,2039 .varargs_function,
2026 => {2040 => {
2027 const info = mod.typeToFunc(ty).?;2041 const info = zcu.typeToFunc(ty).?;
2028 assert(!info.is_generic);2042 assert(!info.is_generic);
2029 const param_kind: Kind = switch (kind) {2043 const param_kind: Kind = switch (kind) {
2030 .forward, .forward_parameter => .forward_parameter,2044 .forward, .forward_parameter => .forward_parameter,
...@@ -2034,21 +2048,21 @@ pub const CType = extern union {...@@ -2034,21 +2048,21 @@ pub const CType = extern union {
20342048
2035 var c_params_len: usize = 0;2049 var c_params_len: usize = 0;
2036 for (info.param_types.get(ip)) |param_type| {2050 for (info.param_types.get(ip)) |param_type| {
2037 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;2051 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2038 c_params_len += 1;2052 c_params_len += 1;
2039 }2053 }
20402054
2041 const params_pl = try arena.alloc(Index, c_params_len);2055 const params_pl = try arena.alloc(Index, c_params_len);
2042 var c_param_i: usize = 0;2056 var c_param_i: usize = 0;
2043 for (info.param_types.get(ip)) |param_type| {2057 for (info.param_types.get(ip)) |param_type| {
2044 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;2058 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2045 params_pl[c_param_i] = store.set.typeToIndex(Type.fromInterned(param_type), mod, param_kind).?;2059 params_pl[c_param_i] = store.set.typeToIndex(Type.fromInterned(param_type), zcu, mod, param_kind).?;
2046 c_param_i += 1;2060 c_param_i += 1;
2047 }2061 }
20482062
2049 const fn_pl = try arena.create(Payload.Function);2063 const fn_pl = try arena.create(Payload.Function);
2050 fn_pl.* = .{ .base = .{ .tag = t }, .data = .{2064 fn_pl.* = .{ .base = .{ .tag = t }, .data = .{
2051 .return_type = store.set.typeToIndex(Type.fromInterned(info.return_type), mod, param_kind).?,2065 .return_type = store.set.typeToIndex(Type.fromInterned(info.return_type), zcu, mod, param_kind).?,
2052 .param_types = params_pl,2066 .param_types = params_pl,
2053 } };2067 } };
2054 return initPayload(fn_pl);2068 return initPayload(fn_pl);
...@@ -2075,8 +2089,8 @@ pub const CType = extern union {...@@ -2075,8 +2089,8 @@ pub const CType = extern union {
2075 }2089 }
20762090
2077 pub fn eql(self: @This(), ty: Type, cty: CType) bool {2091 pub fn eql(self: @This(), ty: Type, cty: CType) bool {
2078 const mod = self.lookup.getModule();2092 const zcu = self.lookup.getZcu();
2079 const ip = &mod.intern_pool;2093 const ip = &zcu.intern_pool;
2080 switch (self.convert.value) {2094 switch (self.convert.value) {
2081 .cty => |c| return c.eql(cty),2095 .cty => |c| return c.eql(cty),
2082 .tag => |t| {2096 .tag => |t| {
...@@ -2086,24 +2100,24 @@ pub const CType = extern union {...@@ -2086,24 +2100,24 @@ pub const CType = extern union {
2086 .fwd_anon_struct,2100 .fwd_anon_struct,
2087 .fwd_anon_union,2101 .fwd_anon_union,
2088 => {2102 => {
2089 if (!ty.isTupleOrAnonStruct(mod)) return false;2103 if (!ty.isTupleOrAnonStruct(zcu)) return false;
20902104
2091 var name_buf: [2105 var name_buf: [
2092 std.fmt.count("f{}", .{std.math.maxInt(usize)})2106 std.fmt.count("f{}", .{std.math.maxInt(usize)})
2093 ]u8 = undefined;2107 ]u8 = undefined;
2094 const c_fields = cty.cast(Payload.Fields).?.data;2108 const c_fields = cty.cast(Payload.Fields).?.data;
20952109
2096 const zig_ty_tag = ty.zigTypeTag(mod);2110 const zig_ty_tag = ty.zigTypeTag(zcu);
2097 var c_field_i: usize = 0;2111 var c_field_i: usize = 0;
2098 for (0..switch (zig_ty_tag) {2112 for (0..switch (zig_ty_tag) {
2099 .Struct => ty.structFieldCount(mod),2113 .Struct => ty.structFieldCount(zcu),
2100 .Union => mod.typeToUnion(ty).?.field_types.len,2114 .Union => zcu.typeToUnion(ty).?.field_types.len,
2101 else => unreachable,2115 else => unreachable,
2102 }) |field_i_usize| {2116 }) |field_i_usize| {
2103 const field_i: u32 = @intCast(field_i_usize);2117 const field_i: u32 = @intCast(field_i_usize);
2104 const field_ty = ty.structFieldType(field_i, mod);2118 const field_ty = ty.structFieldType(field_i, zcu);
2105 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or2119 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
2106 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;2120 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
21072121
2108 defer c_field_i += 1;2122 defer c_field_i += 1;
2109 const c_field = &c_fields[c_field_i];2123 const c_field = &c_fields[c_field_i];
...@@ -2115,16 +2129,16 @@ pub const CType = extern union {...@@ -2115,16 +2129,16 @@ pub const CType = extern union {
2115 .payload => unreachable,2129 .payload => unreachable,
2116 }) or !mem.eql(2130 }) or !mem.eql(
2117 u8,2131 u8,
2118 if (ty.isSimpleTuple(mod))2132 if (ty.isSimpleTuple(zcu))
2119 std.fmt.bufPrintZ(&name_buf, "f{}", .{field_i}) catch unreachable2133 std.fmt.bufPrintZ(&name_buf, "f{}", .{field_i}) catch unreachable
2120 else2134 else
2121 ip.stringToSlice(switch (zig_ty_tag) {2135 ip.stringToSlice(switch (zig_ty_tag) {
2122 .Struct => ty.legacyStructFieldName(field_i, mod),2136 .Struct => ty.legacyStructFieldName(field_i, zcu),
2123 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],2137 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
2124 else => unreachable,2138 else => unreachable,
2125 }),2139 }),
2126 mem.span(c_field.name),2140 mem.span(c_field.name),
2127 ) or AlignAs.fieldAlign(ty, field_i, mod).@"align" !=2141 ) or AlignAs.fieldAlign(ty, field_i, zcu).@"align" !=
2128 c_field.alignas.@"align") return false;2142 c_field.alignas.@"align") return false;
2129 }2143 }
2130 return true;2144 return true;
...@@ -2136,9 +2150,9 @@ pub const CType = extern union {...@@ -2136,9 +2150,9 @@ pub const CType = extern union {
2136 .packed_unnamed_union,2150 .packed_unnamed_union,
2137 => switch (self.kind) {2151 => switch (self.kind) {
2138 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,2152 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,
2139 .payload => if (ty.unionTagTypeSafety(mod)) |_| {2153 .payload => if (ty.unionTagTypeSafety(zcu)) |_| {
2140 const data = cty.cast(Payload.Unnamed).?.data;2154 const data = cty.cast(Payload.Unnamed).?.data;
2141 return ty.getOwnerDecl(mod) == data.owner_decl and data.id == 0;2155 return ty.getOwnerDecl(zcu) == data.owner_decl and data.id == 0;
2142 } else unreachable,2156 } else unreachable,
2143 },2157 },
21442158
...@@ -2157,9 +2171,9 @@ pub const CType = extern union {...@@ -2157,9 +2171,9 @@ pub const CType = extern union {
2157 .function,2171 .function,
2158 .varargs_function,2172 .varargs_function,
2159 => {2173 => {
2160 if (ty.zigTypeTag(mod) != .Fn) return false;2174 if (ty.zigTypeTag(zcu) != .Fn) return false;
21612175
2162 const info = mod.typeToFunc(ty).?;2176 const info = zcu.typeToFunc(ty).?;
2163 assert(!info.is_generic);2177 assert(!info.is_generic);
2164 const data = cty.cast(Payload.Function).?.data;2178 const data = cty.cast(Payload.Function).?.data;
2165 const param_kind: Kind = switch (self.kind) {2179 const param_kind: Kind = switch (self.kind) {
...@@ -2173,7 +2187,7 @@ pub const CType = extern union {...@@ -2173,7 +2187,7 @@ pub const CType = extern union {
21732187
2174 var c_param_i: usize = 0;2188 var c_param_i: usize = 0;
2175 for (info.param_types.get(ip)) |param_type| {2189 for (info.param_types.get(ip)) |param_type| {
2176 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;2190 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
21772191
2178 if (c_param_i >= data.param_types.len) return false;2192 if (c_param_i >= data.param_types.len) return false;
2179 const param_cty = data.param_types[c_param_i];2193 const param_cty = data.param_types[c_param_i];
...@@ -2213,8 +2227,8 @@ pub const CType = extern union {...@@ -2213,8 +2227,8 @@ pub const CType = extern union {
2213 .tag => |t| {2227 .tag => |t| {
2214 autoHash(hasher, t);2228 autoHash(hasher, t);
22152229
2216 const mod = self.lookup.getModule();2230 const zcu = self.lookup.getZcu();
2217 const ip = &mod.intern_pool;2231 const ip = &zcu.intern_pool;
2218 switch (t) {2232 switch (t) {
2219 .fwd_anon_struct,2233 .fwd_anon_struct,
2220 .fwd_anon_union,2234 .fwd_anon_union,
...@@ -2223,16 +2237,16 @@ pub const CType = extern union {...@@ -2223,16 +2237,16 @@ pub const CType = extern union {
2223 std.fmt.count("f{}", .{std.math.maxInt(usize)})2237 std.fmt.count("f{}", .{std.math.maxInt(usize)})
2224 ]u8 = undefined;2238 ]u8 = undefined;
22252239
2226 const zig_ty_tag = ty.zigTypeTag(mod);2240 const zig_ty_tag = ty.zigTypeTag(zcu);
2227 for (0..switch (ty.zigTypeTag(mod)) {2241 for (0..switch (ty.zigTypeTag(zcu)) {
2228 .Struct => ty.structFieldCount(mod),2242 .Struct => ty.structFieldCount(zcu),
2229 .Union => mod.typeToUnion(ty).?.field_types.len,2243 .Union => zcu.typeToUnion(ty).?.field_types.len,
2230 else => unreachable,2244 else => unreachable,
2231 }) |field_i_usize| {2245 }) |field_i_usize| {
2232 const field_i: u32 = @intCast(field_i_usize);2246 const field_i: u32 = @intCast(field_i_usize);
2233 const field_ty = ty.structFieldType(field_i, mod);2247 const field_ty = ty.structFieldType(field_i, zcu);
2234 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or2248 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
2235 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;2249 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
22362250
2237 self.updateHasherRecurse(hasher, field_ty, switch (self.kind) {2251 self.updateHasherRecurse(hasher, field_ty, switch (self.kind) {
2238 .forward, .forward_parameter => .forward,2252 .forward, .forward_parameter => .forward,
...@@ -2240,15 +2254,15 @@ pub const CType = extern union {...@@ -2240,15 +2254,15 @@ pub const CType = extern union {
2240 .global => .global,2254 .global => .global,
2241 .payload => unreachable,2255 .payload => unreachable,
2242 });2256 });
2243 hasher.update(if (ty.isSimpleTuple(mod))2257 hasher.update(if (ty.isSimpleTuple(zcu))
2244 std.fmt.bufPrint(&name_buf, "f{}", .{field_i}) catch unreachable2258 std.fmt.bufPrint(&name_buf, "f{}", .{field_i}) catch unreachable
2245 else2259 else
2246 mod.intern_pool.stringToSlice(switch (zig_ty_tag) {2260 zcu.intern_pool.stringToSlice(switch (zig_ty_tag) {
2247 .Struct => ty.legacyStructFieldName(field_i, mod),2261 .Struct => ty.legacyStructFieldName(field_i, zcu),
2248 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],2262 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
2249 else => unreachable,2263 else => unreachable,
2250 }));2264 }));
2251 autoHash(hasher, AlignAs.fieldAlign(ty, field_i, mod).@"align");2265 autoHash(hasher, AlignAs.fieldAlign(ty, field_i, zcu).@"align");
2252 }2266 }
2253 },2267 },
22542268
...@@ -2258,8 +2272,8 @@ pub const CType = extern union {...@@ -2258,8 +2272,8 @@ pub const CType = extern union {
2258 .packed_unnamed_union,2272 .packed_unnamed_union,
2259 => switch (self.kind) {2273 => switch (self.kind) {
2260 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,2274 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,
2261 .payload => if (ty.unionTagTypeSafety(mod)) |_| {2275 .payload => if (ty.unionTagTypeSafety(zcu)) |_| {
2262 autoHash(hasher, ty.getOwnerDecl(mod));2276 autoHash(hasher, ty.getOwnerDecl(zcu));
2263 autoHash(hasher, @as(u32, 0));2277 autoHash(hasher, @as(u32, 0));
2264 } else unreachable,2278 } else unreachable,
2265 },2279 },
...@@ -2275,7 +2289,7 @@ pub const CType = extern union {...@@ -2275,7 +2289,7 @@ pub const CType = extern union {
2275 .function,2289 .function,
2276 .varargs_function,2290 .varargs_function,
2277 => {2291 => {
2278 const info = mod.typeToFunc(ty).?;2292 const info = zcu.typeToFunc(ty).?;
2279 assert(!info.is_generic);2293 assert(!info.is_generic);
2280 const param_kind: Kind = switch (self.kind) {2294 const param_kind: Kind = switch (self.kind) {
2281 .forward, .forward_parameter => .forward_parameter,2295 .forward, .forward_parameter => .forward_parameter,
...@@ -2285,7 +2299,7 @@ pub const CType = extern union {...@@ -2285,7 +2299,7 @@ pub const CType = extern union {
22852299
2286 self.updateHasherRecurse(hasher, Type.fromInterned(info.return_type), param_kind);2300 self.updateHasherRecurse(hasher, Type.fromInterned(info.return_type), param_kind);
2287 for (info.param_types.get(ip)) |param_type| {2301 for (info.param_types.get(ip)) |param_type| {
2288 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;2302 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2289 self.updateHasherRecurse(hasher, Type.fromInterned(param_type), param_kind);2303 self.updateHasherRecurse(hasher, Type.fromInterned(param_type), param_kind);
2290 }2304 }
2291 },2305 },
src/link/C.zig+66-48
...@@ -6,7 +6,8 @@ const fs = std.fs;...@@ -6,7 +6,8 @@ const fs = std.fs;
66
7const C = @This();7const C = @This();
8const build_options = @import("build_options");8const build_options = @import("build_options");
9const Module = @import("../Module.zig");9const Zcu = @import("../Module.zig");
10const Module = @import("../Package/Module.zig");
10const InternPool = @import("../InternPool.zig");11const InternPool = @import("../InternPool.zig");
11const Alignment = InternPool.Alignment;12const Alignment = InternPool.Alignment;
12const Compilation = @import("../Compilation.zig");13const Compilation = @import("../Compilation.zig");
...@@ -177,16 +178,16 @@ pub fn freeDecl(self: *C, decl_index: InternPool.DeclIndex) void {...@@ -177,16 +178,16 @@ pub fn freeDecl(self: *C, decl_index: InternPool.DeclIndex) void {
177178
178pub fn updateFunc(179pub fn updateFunc(
179 self: *C,180 self: *C,
180 module: *Module,181 zcu: *Zcu,
181 func_index: InternPool.Index,182 func_index: InternPool.Index,
182 air: Air,183 air: Air,
183 liveness: Liveness,184 liveness: Liveness,
184) !void {185) !void {
185 const gpa = self.base.comp.gpa;186 const gpa = self.base.comp.gpa;
186187
187 const func = module.funcInfo(func_index);188 const func = zcu.funcInfo(func_index);
188 const decl_index = func.owner_decl;189 const decl_index = func.owner_decl;
189 const decl = module.declPtr(decl_index);190 const decl = zcu.declPtr(decl_index);
190 const gop = try self.decl_table.getOrPut(gpa, decl_index);191 const gop = try self.decl_table.getOrPut(gpa, decl_index);
191 if (!gop.found_existing) gop.value_ptr.* = .{};192 if (!gop.found_existing) gop.value_ptr.* = .{};
192 const ctypes = &gop.value_ptr.ctypes;193 const ctypes = &gop.value_ptr.ctypes;
...@@ -206,10 +207,11 @@ pub fn updateFunc(...@@ -206,10 +207,11 @@ pub fn updateFunc(
206 .object = .{207 .object = .{
207 .dg = .{208 .dg = .{
208 .gpa = gpa,209 .gpa = gpa,
209 .module = module,210 .zcu = zcu,
211 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
210 .error_msg = null,212 .error_msg = null,
211 .pass = .{ .decl = decl_index },213 .pass = .{ .decl = decl_index },
212 .is_naked_fn = decl.typeOf(module).fnCallingConvention(module) == .Naked,214 .is_naked_fn = decl.typeOf(zcu).fnCallingConvention(zcu) == .Naked,
213 .fwd_decl = fwd_decl.toManaged(gpa),215 .fwd_decl = fwd_decl.toManaged(gpa),
214 .ctypes = ctypes.*,216 .ctypes = ctypes.*,
215 .anon_decl_deps = self.anon_decls,217 .anon_decl_deps = self.anon_decls,
...@@ -232,7 +234,7 @@ pub fn updateFunc(...@@ -232,7 +234,7 @@ pub fn updateFunc(
232234
233 codegen.genFunc(&function) catch |err| switch (err) {235 codegen.genFunc(&function) catch |err| switch (err) {
234 error.AnalysisFail => {236 error.AnalysisFail => {
235 try module.failed_decls.put(gpa, decl_index, function.object.dg.error_msg.?);237 try zcu.failed_decls.put(gpa, decl_index, function.object.dg.error_msg.?);
236 return;238 return;
237 },239 },
238 else => |e| return e,240 else => |e| return e,
...@@ -249,7 +251,7 @@ pub fn updateFunc(...@@ -249,7 +251,7 @@ pub fn updateFunc(
249 gop.value_ptr.fwd_decl = try self.addString(function.object.dg.fwd_decl.items);251 gop.value_ptr.fwd_decl = try self.addString(function.object.dg.fwd_decl.items);
250}252}
251253
252fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {254fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
253 const gpa = self.base.comp.gpa;255 const gpa = self.base.comp.gpa;
254 const anon_decl = self.anon_decls.keys()[i];256 const anon_decl = self.anon_decls.keys()[i];
255257
...@@ -261,7 +263,8 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {...@@ -261,7 +263,8 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
261 var object: codegen.Object = .{263 var object: codegen.Object = .{
262 .dg = .{264 .dg = .{
263 .gpa = gpa,265 .gpa = gpa,
264 .module = module,266 .zcu = zcu,
267 .mod = zcu.root_mod,
265 .error_msg = null,268 .error_msg = null,
266 .pass = .{ .anon = anon_decl },269 .pass = .{ .anon = anon_decl },
267 .is_naked_fn = false,270 .is_naked_fn = false,
...@@ -283,12 +286,12 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {...@@ -283,12 +286,12 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
283 code.* = object.code.moveToUnmanaged();286 code.* = object.code.moveToUnmanaged();
284 }287 }
285288
286 const c_value: codegen.CValue = .{ .constant = anon_decl };289 const c_value: codegen.CValue = .{ .constant = Value.fromInterned(anon_decl) };
287 const alignment: Alignment = self.aligned_anon_decls.get(anon_decl) orelse .none;290 const alignment: Alignment = self.aligned_anon_decls.get(anon_decl) orelse .none;
288 codegen.genDeclValue(&object, Value.fromInterned(anon_decl), false, c_value, alignment, .none) catch |err| switch (err) {291 codegen.genDeclValue(&object, c_value.constant, false, c_value, alignment, .none) catch |err| switch (err) {
289 error.AnalysisFail => {292 error.AnalysisFail => {
290 @panic("TODO: C backend AnalysisFail on anonymous decl");293 @panic("TODO: C backend AnalysisFail on anonymous decl");
291 //try module.failed_decls.put(gpa, decl_index, object.dg.error_msg.?);294 //try zcu.failed_decls.put(gpa, decl_index, object.dg.error_msg.?);
292 //return;295 //return;
293 },296 },
294 else => |e| return e,297 else => |e| return e,
...@@ -304,12 +307,13 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {...@@ -304,12 +307,13 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
304 };307 };
305}308}
306309
307pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !void {310pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
308 const tracy = trace(@src());311 const tracy = trace(@src());
309 defer tracy.end();312 defer tracy.end();
310313
311 const gpa = self.base.comp.gpa;314 const gpa = self.base.comp.gpa;
312315
316 const decl = zcu.declPtr(decl_index);
313 const gop = try self.decl_table.getOrPut(gpa, decl_index);317 const gop = try self.decl_table.getOrPut(gpa, decl_index);
314 if (!gop.found_existing) {318 if (!gop.found_existing) {
315 gop.value_ptr.* = .{};319 gop.value_ptr.* = .{};
...@@ -324,7 +328,8 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !...@@ -324,7 +328,8 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
324 var object: codegen.Object = .{328 var object: codegen.Object = .{
325 .dg = .{329 .dg = .{
326 .gpa = gpa,330 .gpa = gpa,
327 .module = module,331 .zcu = zcu,
332 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
328 .error_msg = null,333 .error_msg = null,
329 .pass = .{ .decl = decl_index },334 .pass = .{ .decl = decl_index },
330 .is_naked_fn = false,335 .is_naked_fn = false,
...@@ -347,7 +352,7 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !...@@ -347,7 +352,7 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
347352
348 codegen.genDecl(&object) catch |err| switch (err) {353 codegen.genDecl(&object) catch |err| switch (err) {
349 error.AnalysisFail => {354 error.AnalysisFail => {
350 try module.failed_decls.put(gpa, decl_index, object.dg.error_msg.?);355 try zcu.failed_decls.put(gpa, decl_index, object.dg.error_msg.?);
351 return;356 return;
352 },357 },
353 else => |e| return e,358 else => |e| return e,
...@@ -362,11 +367,11 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !...@@ -362,11 +367,11 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
362 gop.value_ptr.fwd_decl = try self.addString(object.dg.fwd_decl.items);367 gop.value_ptr.fwd_decl = try self.addString(object.dg.fwd_decl.items);
363}368}
364369
365pub fn updateDeclLineNumber(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !void {370pub fn updateDeclLineNumber(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
366 // The C backend does not have the ability to fix line numbers without re-generating371 // The C backend does not have the ability to fix line numbers without re-generating
367 // the entire Decl.372 // the entire Decl.
368 _ = self;373 _ = self;
369 _ = module;374 _ = zcu;
370 _ = decl_index;375 _ = decl_index;
371}376}
372377
...@@ -399,12 +404,12 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -399,12 +404,12 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
399404
400 const comp = self.base.comp;405 const comp = self.base.comp;
401 const gpa = comp.gpa;406 const gpa = comp.gpa;
402 const module = self.base.comp.module.?;407 const zcu = self.base.comp.module.?;
403408
404 {409 {
405 var i: usize = 0;410 var i: usize = 0;
406 while (i < self.anon_decls.count()) : (i += 1) {411 while (i < self.anon_decls.count()) : (i += 1) {
407 try updateAnonDecl(self, module, i);412 try updateAnonDecl(self, zcu, i);
408 }413 }
409 }414 }
410415
...@@ -414,7 +419,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -414,7 +419,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
414 var f: Flush = .{};419 var f: Flush = .{};
415 defer f.deinit(gpa);420 defer f.deinit(gpa);
416421
417 const abi_defines = try self.abiDefines(module.getTarget());422 const abi_defines = try self.abiDefines(zcu.getTarget());
418 defer abi_defines.deinit();423 defer abi_defines.deinit();
419424
420 // Covers defines, zig.h, ctypes, asm, lazy fwd.425 // Covers defines, zig.h, ctypes, asm, lazy fwd.
...@@ -429,7 +434,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -429,7 +434,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
429 {434 {
430 var asm_buf = f.asm_buf.toManaged(gpa);435 var asm_buf = f.asm_buf.toManaged(gpa);
431 defer f.asm_buf = asm_buf.moveToUnmanaged();436 defer f.asm_buf = asm_buf.moveToUnmanaged();
432 try codegen.genGlobalAsm(module, asm_buf.writer());437 try codegen.genGlobalAsm(zcu, asm_buf.writer());
433 f.appendBufAssumeCapacity(asm_buf.items);438 f.appendBufAssumeCapacity(asm_buf.items);
434 }439 }
435440
...@@ -438,7 +443,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -438,7 +443,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
438443
439 self.lazy_fwd_decl_buf.clearRetainingCapacity();444 self.lazy_fwd_decl_buf.clearRetainingCapacity();
440 self.lazy_code_buf.clearRetainingCapacity();445 self.lazy_code_buf.clearRetainingCapacity();
441 try self.flushErrDecls(&f.lazy_ctypes);446 try self.flushErrDecls(zcu, &f.lazy_ctypes);
442447
443 // Unlike other backends, the .c code we are emitting has order-dependent decls.448 // Unlike other backends, the .c code we are emitting has order-dependent decls.
444 // `CType`s, forward decls, and non-functions first.449 // `CType`s, forward decls, and non-functions first.
...@@ -446,19 +451,20 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -446,19 +451,20 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
446 {451 {
447 var export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};452 var export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
448 defer export_names.deinit(gpa);453 defer export_names.deinit(gpa);
449 try export_names.ensureTotalCapacity(gpa, @intCast(module.decl_exports.entries.len));454 try export_names.ensureTotalCapacity(gpa, @intCast(zcu.decl_exports.entries.len));
450 for (module.decl_exports.values()) |exports| for (exports.items) |@"export"|455 for (zcu.decl_exports.values()) |exports| for (exports.items) |@"export"|
451 try export_names.put(gpa, @"export".opts.name, {});456 try export_names.put(gpa, @"export".opts.name, {});
452457
453 for (self.anon_decls.values()) |*decl_block| {458 for (self.anon_decls.values()) |*decl_block| {
454 try self.flushDeclBlock(&f, decl_block, export_names, .none);459 try self.flushDeclBlock(zcu, zcu.root_mod, &f, decl_block, export_names, .none);
455 }460 }
456461
457 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {462 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {
458 assert(module.declPtr(decl_index).has_tv);463 const decl = zcu.declPtr(decl_index);
459 const decl = module.declPtr(decl_index);464 assert(decl.has_tv);
460 const extern_symbol_name = if (decl.isExtern(module)) decl.name.toOptional() else .none;465 const extern_symbol_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;
461 try self.flushDeclBlock(&f, decl_block, export_names, extern_symbol_name);466 const mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod;
467 try self.flushDeclBlock(zcu, mod, &f, decl_block, export_names, extern_symbol_name);
462 }468 }
463 }469 }
464470
...@@ -466,14 +472,14 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v...@@ -466,14 +472,14 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
466 // We need to flush lazy ctypes after flushing all decls but before flushing any decl ctypes.472 // We need to flush lazy ctypes after flushing all decls but before flushing any decl ctypes.
467 // This ensures that every lazy CType.Index exactly matches the global CType.Index.473 // This ensures that every lazy CType.Index exactly matches the global CType.Index.
468 assert(f.ctypes.count() == 0);474 assert(f.ctypes.count() == 0);
469 try self.flushCTypes(&f, .flush, f.lazy_ctypes);475 try self.flushCTypes(zcu, &f, .flush, f.lazy_ctypes);
470476
471 for (self.anon_decls.keys(), self.anon_decls.values()) |anon_decl, decl_block| {477 for (self.anon_decls.keys(), self.anon_decls.values()) |anon_decl, decl_block| {
472 try self.flushCTypes(&f, .{ .anon = anon_decl }, decl_block.ctypes);478 try self.flushCTypes(zcu, &f, .{ .anon = anon_decl }, decl_block.ctypes);
473 }479 }
474480
475 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, decl_block| {481 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, decl_block| {
476 try self.flushCTypes(&f, .{ .decl = decl_index }, decl_block.ctypes);482 try self.flushCTypes(zcu, &f, .{ .decl = decl_index }, decl_block.ctypes);
477 }483 }
478 }484 }
479485
...@@ -543,12 +549,12 @@ const FlushDeclError = error{...@@ -543,12 +549,12 @@ const FlushDeclError = error{
543549
544fn flushCTypes(550fn flushCTypes(
545 self: *C,551 self: *C,
552 zcu: *Zcu,
546 f: *Flush,553 f: *Flush,
547 pass: codegen.DeclGen.Pass,554 pass: codegen.DeclGen.Pass,
548 decl_ctypes: codegen.CType.Store,555 decl_ctypes: codegen.CType.Store,
549) FlushDeclError!void {556) FlushDeclError!void {
550 const gpa = self.base.comp.gpa;557 const gpa = self.base.comp.gpa;
551 const mod = self.base.comp.module.?;
552558
553 const decl_ctypes_len = decl_ctypes.count();559 const decl_ctypes_len = decl_ctypes.count();
554 f.ctypes_map.clearRetainingCapacity();560 f.ctypes_map.clearRetainingCapacity();
...@@ -615,7 +621,7 @@ fn flushCTypes(...@@ -615,7 +621,7 @@ fn flushCTypes(
615 assert(decl_cty.hash(decl_ctypes.set) == global_cty.hash(global_ctypes.set));621 assert(decl_cty.hash(decl_ctypes.set) == global_cty.hash(global_ctypes.set));
616 }622 }
617 try codegen.genTypeDecl(623 try codegen.genTypeDecl(
618 mod,624 zcu,
619 writer,625 writer,
620 global_ctypes.set,626 global_ctypes.set,
621 global_idx,627 global_idx,
...@@ -627,7 +633,7 @@ fn flushCTypes(...@@ -627,7 +633,7 @@ fn flushCTypes(
627 }633 }
628}634}
629635
630fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {636fn flushErrDecls(self: *C, zcu: *Zcu, ctypes: *codegen.CType.Store) FlushDeclError!void {
631 const gpa = self.base.comp.gpa;637 const gpa = self.base.comp.gpa;
632638
633 const fwd_decl = &self.lazy_fwd_decl_buf;639 const fwd_decl = &self.lazy_fwd_decl_buf;
...@@ -636,7 +642,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {...@@ -636,7 +642,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {
636 var object = codegen.Object{642 var object = codegen.Object{
637 .dg = .{643 .dg = .{
638 .gpa = gpa,644 .gpa = gpa,
639 .module = self.base.comp.module.?,645 .zcu = zcu,
646 .mod = zcu.root_mod,
640 .error_msg = null,647 .error_msg = null,
641 .pass = .flush,648 .pass = .flush,
642 .is_naked_fn = false,649 .is_naked_fn = false,
...@@ -667,6 +674,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {...@@ -667,6 +674,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {
667674
668fn flushLazyFn(675fn flushLazyFn(
669 self: *C,676 self: *C,
677 zcu: *Zcu,
678 mod: *Module,
670 ctypes: *codegen.CType.Store,679 ctypes: *codegen.CType.Store,
671 lazy_fn: codegen.LazyFnMap.Entry,680 lazy_fn: codegen.LazyFnMap.Entry,
672) FlushDeclError!void {681) FlushDeclError!void {
...@@ -678,7 +687,8 @@ fn flushLazyFn(...@@ -678,7 +687,8 @@ fn flushLazyFn(
678 var object = codegen.Object{687 var object = codegen.Object{
679 .dg = .{688 .dg = .{
680 .gpa = gpa,689 .gpa = gpa,
681 .module = self.base.comp.module.?,690 .zcu = zcu,
691 .mod = mod,
682 .error_msg = null,692 .error_msg = null,
683 .pass = .flush,693 .pass = .flush,
684 .is_naked_fn = false,694 .is_naked_fn = false,
...@@ -709,7 +719,13 @@ fn flushLazyFn(...@@ -709,7 +719,13 @@ fn flushLazyFn(
709 ctypes.* = object.dg.ctypes.move();719 ctypes.* = object.dg.ctypes.move();
710}720}
711721
712fn flushLazyFns(self: *C, f: *Flush, lazy_fns: codegen.LazyFnMap) FlushDeclError!void {722fn flushLazyFns(
723 self: *C,
724 zcu: *Zcu,
725 mod: *Module,
726 f: *Flush,
727 lazy_fns: codegen.LazyFnMap,
728) FlushDeclError!void {
713 const gpa = self.base.comp.gpa;729 const gpa = self.base.comp.gpa;
714 try f.lazy_fns.ensureUnusedCapacity(gpa, @intCast(lazy_fns.count()));730 try f.lazy_fns.ensureUnusedCapacity(gpa, @intCast(lazy_fns.count()));
715731
...@@ -718,19 +734,21 @@ fn flushLazyFns(self: *C, f: *Flush, lazy_fns: codegen.LazyFnMap) FlushDeclError...@@ -718,19 +734,21 @@ fn flushLazyFns(self: *C, f: *Flush, lazy_fns: codegen.LazyFnMap) FlushDeclError
718 const gop = f.lazy_fns.getOrPutAssumeCapacity(entry.key_ptr.*);734 const gop = f.lazy_fns.getOrPutAssumeCapacity(entry.key_ptr.*);
719 if (gop.found_existing) continue;735 if (gop.found_existing) continue;
720 gop.value_ptr.* = {};736 gop.value_ptr.* = {};
721 try self.flushLazyFn(&f.lazy_ctypes, entry);737 try self.flushLazyFn(zcu, mod, &f.lazy_ctypes, entry);
722 }738 }
723}739}
724740
725fn flushDeclBlock(741fn flushDeclBlock(
726 self: *C,742 self: *C,
743 zcu: *Zcu,
744 mod: *Module,
727 f: *Flush,745 f: *Flush,
728 decl_block: *DeclBlock,746 decl_block: *DeclBlock,
729 export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void),747 export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void),
730 extern_symbol_name: InternPool.OptionalNullTerminatedString,748 extern_symbol_name: InternPool.OptionalNullTerminatedString,
731) FlushDeclError!void {749) FlushDeclError!void {
732 const gpa = self.base.comp.gpa;750 const gpa = self.base.comp.gpa;
733 try self.flushLazyFns(f, decl_block.lazy_fns);751 try self.flushLazyFns(zcu, mod, f, decl_block.lazy_fns);
734 try f.all_buffers.ensureUnusedCapacity(gpa, 1);752 try f.all_buffers.ensureUnusedCapacity(gpa, 1);
735 fwd_decl: {753 fwd_decl: {
736 if (extern_symbol_name.unwrap()) |name| {754 if (extern_symbol_name.unwrap()) |name| {
...@@ -740,15 +758,15 @@ fn flushDeclBlock(...@@ -740,15 +758,15 @@ fn flushDeclBlock(
740 }758 }
741}759}
742760
743pub fn flushEmitH(module: *Module) !void {761pub fn flushEmitH(zcu: *Zcu) !void {
744 const tracy = trace(@src());762 const tracy = trace(@src());
745 defer tracy.end();763 defer tracy.end();
746764
747 const emit_h = module.emit_h orelse return;765 const emit_h = zcu.emit_h orelse return;
748766
749 // We collect a list of buffers to write, and write them all at once with pwritev 😎767 // We collect a list of buffers to write, and write them all at once with pwritev 😎
750 const num_buffers = emit_h.decl_table.count() + 1;768 const num_buffers = emit_h.decl_table.count() + 1;
751 var all_buffers = try std.ArrayList(std.posix.iovec_const).initCapacity(module.gpa, num_buffers);769 var all_buffers = try std.ArrayList(std.posix.iovec_const).initCapacity(zcu.gpa, num_buffers);
752 defer all_buffers.deinit();770 defer all_buffers.deinit();
753771
754 var file_size: u64 = zig_h.len;772 var file_size: u64 = zig_h.len;
...@@ -771,7 +789,7 @@ pub fn flushEmitH(module: *Module) !void {...@@ -771,7 +789,7 @@ pub fn flushEmitH(module: *Module) !void {
771 }789 }
772 }790 }
773791
774 const directory = emit_h.loc.directory orelse module.comp.local_cache_directory;792 const directory = emit_h.loc.directory orelse zcu.comp.local_cache_directory;
775 const file = try directory.handle.createFile(emit_h.loc.basename, .{793 const file = try directory.handle.createFile(emit_h.loc.basename, .{
776 // We set the end position explicitly below; by not truncating the file, we possibly794 // We set the end position explicitly below; by not truncating the file, we possibly
777 // make it easier on the file system by doing 1 reallocation instead of two.795 // make it easier on the file system by doing 1 reallocation instead of two.
...@@ -785,12 +803,12 @@ pub fn flushEmitH(module: *Module) !void {...@@ -785,12 +803,12 @@ pub fn flushEmitH(module: *Module) !void {
785803
786pub fn updateExports(804pub fn updateExports(
787 self: *C,805 self: *C,
788 module: *Module,806 zcu: *Zcu,
789 exported: Module.Exported,807 exported: Zcu.Exported,
790 exports: []const *Module.Export,808 exports: []const *Zcu.Export,
791) !void {809) !void {
792 _ = exports;810 _ = exports;
793 _ = exported;811 _ = exported;
794 _ = module;812 _ = zcu;
795 _ = self;813 _ = self;
796}814}