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;
165165#endif
166166
167167#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
169170#elif _MSC_VER
170#define zig_linksection(name, def, ...) __pragma(section(name, __VA_ARGS__)) __declspec(allocate(name)) def
171#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))
171173#else
172#define zig_linksection(name, def, ...) zig_linksection_unavailable
174#define zig_linksection(name) zig_linksection_unavailable
175#define zig_linksection_fn zig_linksection
173176#endif
174177
175178#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
34513451
34523452 var dg: c_codegen.DeclGen = .{
34533453 .gpa = gpa,
3454 .module = module,
3454 .zcu = module,
3455 .mod = module.namespacePtr(decl.src_namespace).file_scope.mod,
34553456 .error_msg = null,
34563457 .pass = .{ .decl = decl_index },
34573458 .is_naked_fn = false,
src/codegen/c.zig+1267-1192
......@@ -5,12 +5,13 @@ const mem = std.mem;
55const log = std.log.scoped(.c);
66
77const link = @import("../link.zig");
8const Module = @import("../Module.zig");
8const Zcu = @import("../Module.zig");
9const Module = @import("../Package/Module.zig");
910const Compilation = @import("../Compilation.zig");
1011const Value = @import("../Value.zig");
1112const Type = @import("../type.zig").Type;
1213const C = link.File.C;
13const Decl = Module.Decl;
14const Decl = Zcu.Decl;
1415const trace = @import("../tracy.zig").trace;
1516const LazySrcLoc = std.zig.LazySrcLoc;
1617const Air = @import("../Air.zig");
......@@ -30,7 +31,7 @@ pub const CValue = union(enum) {
3031 /// Address of a local.
3132 local_ref: LocalIndex,
3233 /// A constant instruction, to be rendered inline.
33 constant: InternPool.Index,
34 constant: Value,
3435 /// Index into the parameters
3536 arg: usize,
3637 /// The array field of a parameter
......@@ -72,13 +73,15 @@ pub const LazyFnValue = struct {
7273};
7374pub const LazyFnMap = std.AutoArrayHashMapUnmanaged(LazyFnKey, LazyFnValue);
7475
75const LoopDepth = u16;
7676const Local = struct {
7777 cty_idx: CType.Index,
78 alignas: CType.AlignAs,
78 flags: packed struct(u32) {
79 alignas: CType.AlignAs,
80 _: u20 = undefined,
81 },
7982
8083 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 };
8285 }
8386};
8487
......@@ -300,11 +303,11 @@ pub const Function = struct {
300303 const gop = try f.value_map.getOrPut(ref);
301304 if (gop.found_existing) return gop.value_ptr.*;
302305
303 const mod = f.object.dg.module;
304 const val = (try f.air.value(ref, mod)).?;
306 const zcu = f.object.dg.zcu;
307 const val = (try f.air.value(ref, zcu)).?;
305308 const ty = f.typeOf(ref);
306309
307 const result: CValue = if (lowersToArray(ty, mod)) result: {
310 const result: CValue = if (lowersToArray(ty, zcu)) result: {
308311 const writer = f.object.codeHeaderWriter();
309312 const alignment: Alignment = .none;
310313 const decl_c_value = try f.allocLocalValue(ty, alignment);
......@@ -313,17 +316,17 @@ pub const Function = struct {
313316 try writer.writeAll("static ");
314317 try f.object.dg.renderTypeAndName(writer, ty, decl_c_value, Const, alignment, .complete);
315318 try writer.writeAll(" = ");
316 try f.object.dg.renderValue(writer, ty, val, .StaticInitializer);
319 try f.object.dg.renderValue(writer, val, .StaticInitializer);
317320 try writer.writeAll(";\n ");
318321 break :result decl_c_value;
319 } else .{ .constant = val.toIntern() };
322 } else .{ .constant = val };
320323
321324 gop.value_ptr.* = result;
322325 return result;
323326 }
324327
325328 fn wantSafety(f: *Function) bool {
326 return switch (f.object.dg.module.optimizeMode()) {
329 return switch (f.object.dg.zcu.optimizeMode()) {
327330 .Debug, .ReleaseSafe => true,
328331 .ReleaseFast, .ReleaseSmall => false,
329332 };
......@@ -333,11 +336,13 @@ pub const Function = struct {
333336 /// those which go into `allocs`. This function does not add the resulting local into `allocs`;
334337 /// that responsibility lies with the caller.
335338 fn allocLocalValue(f: *Function, ty: Type, alignment: Alignment) !CValue {
336 const mod = f.object.dg.module;
339 const zcu = f.object.dg.zcu;
337340 const gpa = f.object.dg.gpa;
338341 try f.locals.append(gpa, .{
339342 .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 },
341346 });
342347 return .{ .new_local = @intCast(f.locals.items.len - 1) };
343348 }
......@@ -355,79 +360,100 @@ pub const Function = struct {
355360 /// Only allocates the local; does not print anything. Will attempt to re-use locals, so should
356361 /// not be used for persistent locals (i.e. those in `allocs`).
357362 fn allocAlignedLocal(f: *Function, ty: Type, _: CQualifiers, alignment: Alignment) !CValue {
358 const mod = f.object.dg.module;
363 const zcu = f.object.dg.zcu;
359364 if (f.free_locals_map.getPtr(.{
360365 .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)),
362367 })) |locals_list| {
363368 if (locals_list.popOrNull()) |local_entry| {
364369 return .{ .new_local = local_entry.key };
365370 }
366371 }
367372
368 return try f.allocLocalValue(ty, alignment);
373 return f.allocLocalValue(ty, alignment);
369374 }
370375
371376 fn writeCValue(f: *Function, w: anytype, c_value: CValue, location: ValueRenderLocation) !void {
372377 switch (c_value) {
373 .constant => |val| try f.object.dg.renderValue(
374 w,
375 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),
376 Value.fromInterned(val),
377 location,
378 ),
379 .undef => |ty| try f.object.dg.renderValue(w, ty, Value.undef, location),
378 .none => unreachable,
379 .new_local, .local => |i| try w.print("t{d}", .{i}),
380 .local_ref => |i| {
381 const local = &f.locals.items[i];
382 if (local.flags.alignas.abiOrder().compare(.lt)) {
383 const zcu = f.object.dg.zcu;
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),
380400 else => try f.object.dg.writeCValue(w, c_value),
381401 }
382402 }
383403
384404 fn writeCValueDeref(f: *Function, w: anytype, c_value: CValue) !void {
385405 switch (c_value) {
386 .constant => |val| {
406 .none => unreachable,
407 .new_local, .local, .constant => {
387408 try w.writeAll("(*");
388 try f.object.dg.renderValue(
389 w,
390 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),
391 Value.fromInterned(val),
392 .Other,
393 );
409 try f.writeCValue(w, c_value, .Other);
410 try w.writeByte(')');
411 },
412 .local_ref => |i| try w.print("t{d}", .{i}),
413 .arg => |i| try w.print("(*a{d})", .{i}),
414 .arg_array => |i| {
415 try w.writeAll("(*");
416 try f.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" });
394417 try w.writeByte(')');
395418 },
396419 else => try f.object.dg.writeCValueDeref(w, c_value),
397420 }
398421 }
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 {
401429 switch (c_value) {
402 .constant => |val| {
403 try f.object.dg.renderValue(
404 w,
405 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),
406 Value.fromInterned(val),
407 .Other,
408 );
409 try w.writeByte('.');
410 try f.writeCValue(w, member, .Other);
430 .new_local, .local, .local_ref, .constant, .arg, .arg_array => {
431 try f.writeCValue(writer, c_value, .Other);
432 try writer.writeByte('.');
433 try f.writeCValue(writer, member, .Other);
411434 },
412 else => try f.object.dg.writeCValueMember(w, c_value, member),
435 else => return f.object.dg.writeCValueMember(writer, c_value, member),
413436 }
414437 }
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 {
417440 switch (c_value) {
418 .constant => |val| {
419 try w.writeByte('(');
420 try f.object.dg.renderValue(
421 w,
422 Type.fromInterned(f.object.dg.module.intern_pool.typeOf(val)),
423 Value.fromInterned(val),
424 .Other,
425 );
426 try w.writeAll(")->");
427 try f.writeCValue(w, member, .Other);
441 .new_local, .local, .arg, .arg_array => {
442 try f.writeCValue(writer, c_value, .Other);
443 try writer.writeAll("->");
444 },
445 .constant => {
446 try writer.writeByte('(');
447 try f.writeCValue(writer, c_value, .Other);
448 try writer.writeAll(")->");
449 },
450 .local_ref => {
451 try f.writeCValueDeref(writer, c_value);
452 try writer.writeByte('.');
428453 },
429 else => try f.object.dg.writeCValueDerefMember(w, c_value, member),
454 else => return f.object.dg.writeCValueDerefMember(writer, c_value, member),
430455 }
456 try f.writeCValue(writer, member, .Other);
431457 }
432458
433459 fn fail(f: *Function, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
......@@ -462,8 +488,8 @@ pub const Function = struct {
462488 return f.object.dg.renderIntCast(w, dest_ty, .{ .c_value = .{ .f = f, .value = src, .v = v } }, src_ty, location);
463489 }
464490
465 fn fmtIntLiteral(f: *Function, ty: Type, val: Value) !std.fmt.Formatter(formatIntLiteral) {
466 return f.object.dg.fmtIntLiteral(ty, val, .Other);
491 fn fmtIntLiteral(f: *Function, val: Value) !std.fmt.Formatter(formatIntLiteral) {
492 return f.object.dg.fmtIntLiteral(val, .Other);
467493 }
468494
469495 fn getLazyFnName(f: *Function, key: LazyFnKey, data: LazyFnValue.Data) ![]const u8 {
......@@ -475,7 +501,7 @@ pub const Function = struct {
475501 var promoted = f.object.dg.ctypes.promote(gpa);
476502 defer f.object.dg.ctypes.demote(promoted);
477503 const arena = promoted.arena.allocator();
478 const mod = f.object.dg.module;
504 const zcu = f.object.dg.zcu;
479505
480506 gop.value_ptr.* = .{
481507 .fn_name = switch (key) {
......@@ -484,7 +510,7 @@ pub const Function = struct {
484510 .never_inline,
485511 => |owner_decl| try std.fmt.allocPrint(arena, "zig_{s}_{}__{d}", .{
486512 @tagName(key),
487 fmtIdent(mod.intern_pool.stringToSlice(mod.declPtr(owner_decl).name)),
513 fmtIdent(zcu.intern_pool.stringToSlice(zcu.declPtr(owner_decl).name)),
488514 @intFromEnum(owner_decl),
489515 }),
490516 },
......@@ -510,17 +536,17 @@ pub const Function = struct {
510536 }
511537
512538 fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {
513 const mod = f.object.dg.module;
514 return f.air.typeOf(inst, &mod.intern_pool);
539 const zcu = f.object.dg.zcu;
540 return f.air.typeOf(inst, &zcu.intern_pool);
515541 }
516542
517543 fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {
518 const mod = f.object.dg.module;
519 return f.air.typeOfIndex(inst, &mod.intern_pool);
544 const zcu = f.object.dg.zcu;
545 return f.air.typeOfIndex(inst, &zcu.intern_pool);
520546 }
521547};
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`.
524550/// It is not available when generating .h file.
525551pub const Object = struct {
526552 dg: DeclGen,
......@@ -542,12 +568,13 @@ pub const Object = struct {
542568/// This data is available both when outputting .c code and when outputting an .h file.
543569pub const DeclGen = struct {
544570 gpa: mem.Allocator,
545 module: *Module,
571 zcu: *Zcu,
572 mod: *Module,
546573 pass: Pass,
547574 is_naked_fn: bool,
548575 /// This is a borrowed reference from `link.C`.
549576 fwd_decl: std.ArrayList(u8),
550 error_msg: ?*Module.ErrorMsg,
577 error_msg: ?*Zcu.ErrorMsg,
551578 ctypes: CType.Store,
552579 /// Keeps track of anonymous decls that need to be rendered before this
553580 /// (named) Decl in the output C code.
......@@ -566,75 +593,70 @@ pub const DeclGen = struct {
566593
567594 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
568595 @setCold(true);
569 const mod = dg.module;
596 const zcu = dg.zcu;
570597 const decl_index = dg.pass.decl;
571 const decl = mod.declPtr(decl_index);
572 const src_loc = decl.srcLoc(mod);
573 dg.error_msg = try Module.ErrorMsg.create(dg.gpa, src_loc, format, args);
598 const decl = zcu.declPtr(decl_index);
599 const src_loc = decl.srcLoc(zcu);
600 dg.error_msg = try Zcu.ErrorMsg.create(dg.gpa, src_loc, format, args);
574601 return error.AnalysisFail;
575602 }
576603
577604 fn renderAnonDeclValue(
578605 dg: *DeclGen,
579606 writer: anytype,
580 ty: Type,
581607 ptr_val: Value,
582608 anon_decl: InternPool.Key.Ptr.Addr.AnonDecl,
583609 location: ValueRenderLocation,
584610 ) error{ OutOfMemory, AnalysisFail }!void {
585 const mod = dg.module;
586 const ip = &mod.intern_pool;
587 const decl_val = anon_decl.val;
588 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));
611 const zcu = dg.zcu;
612 const ip = &zcu.intern_pool;
613 const decl_val = Value.fromInterned(anon_decl.val);
614 const decl_ty = decl_val.typeOf(zcu);
589615
590616 // 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)) {
592 return dg.writeCValue(writer, .{ .undef = ty });
617 const ptr_ty = ptr_val.typeOf(zcu);
618 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(zcu)) {
619 return dg.writeCValue(writer, .{ .undef = ptr_ty });
593620 }
594621
595622 // Chase function values in order to be able to reference the original function.
596 if (Value.fromInterned(decl_val).getFunction(mod)) |func| {
597 _ = func;
598 _ = ptr_val;
599 _ = 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 }
623 if (decl_val.getFunction(zcu)) |func|
624 return dg.renderDeclValue(writer, ptr_val, func.owner_decl, location);
625 if (decl_val.getExternFunc(zcu)) |extern_func|
626 return dg.renderDeclValue(writer, ptr_val, extern_func.decl, location);
608627
609 assert(Value.fromInterned(decl_val).getVariable(mod) == null);
628 assert(decl_val.getVariable(zcu) == null);
610629
611630 // We shouldn't cast C function pointers as this is UB (when you call
612631 // them). The analysis until now should ensure that the C function
613632 // pointers are compatible. If they are not, then there is a bug
614633 // 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);
616 if (need_typecast) {
634 const child_cty = (try dg.typeToCType(ptr_ty, .complete)).cast(CType.Payload.Child).?.data;
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) {
617639 try writer.writeAll("((");
618 try dg.renderType(writer, ty);
640 try dg.renderType(writer, ptr_ty);
619641 try writer.writeByte(')');
620642 }
621643 try writer.writeByte('&');
622644 try renderAnonDeclName(writer, decl_val);
623 if (need_typecast) try writer.writeByte(')');
645 if (need_cast) try writer.writeByte(')');
624646
625647 // Indicate that the anon decl should be rendered to the output so that
626648 // our reference above is not undefined.
627649 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);
629651 if (!gop.found_existing) gop.value_ptr.* = .{};
630652
631653 // Only insert an alignment entry if the alignment is greater than ABI
632654 // alignment. If there is already an entry, keep the greater alignment.
633655 const explicit_alignment = ptr_type.flags.alignment;
634656 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);
636658 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);
638660 aligned_gop.value_ptr.* = if (aligned_gop.found_existing)
639661 aligned_gop.value_ptr.maxStrict(explicit_alignment)
640662 else
......@@ -646,41 +668,45 @@ pub const DeclGen = struct {
646668 fn renderDeclValue(
647669 dg: *DeclGen,
648670 writer: anytype,
649 ty: Type,
650671 val: Value,
651672 decl_index: InternPool.DeclIndex,
652673 location: ValueRenderLocation,
653674 ) error{ OutOfMemory, AnalysisFail }!void {
654 const mod = dg.module;
655 const decl = mod.declPtr(decl_index);
675 const zcu = dg.zcu;
676 const decl = zcu.declPtr(decl_index);
656677 assert(decl.has_tv);
657678
658679 // 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)) {
660683 return dg.writeCValue(writer, .{ .undef = ty });
661684 }
662685
663686 // 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)
665 return dg.renderDeclValue(writer, ty, val, func.owner_decl, location);
666 if (decl.val.getExternFunc(mod)) |extern_func| if (extern_func.decl != decl_index)
667 return dg.renderDeclValue(writer, ty, val, extern_func.decl, location);
687 if (decl.val.getFunction(zcu)) |func| if (func.owner_decl != decl_index)
688 return dg.renderDeclValue(writer, val, func.owner_decl, location);
689 if (decl.val.getExternFunc(zcu)) |extern_func| if (extern_func.decl != decl_index)
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
671694 // We shouldn't cast C function pointers as this is UB (when you call
672695 // them). The analysis until now should ensure that the C function
673696 // pointers are compatible. If they are not, then there is a bug
674697 // 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);
676 if (need_typecast) {
698 const child_cty = (try dg.typeToCType(ty, .complete)).cast(CType.Payload.Child).?.data;
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) {
677703 try writer.writeAll("((");
678704 try dg.renderType(writer, ty);
679705 try writer.writeByte(')');
680706 }
681707 try writer.writeByte('&');
682708 try dg.renderDeclName(writer, decl_index, 0);
683 if (need_typecast) try writer.writeByte(')');
709 if (need_cast) try writer.writeByte(')');
684710 }
685711
686712 /// Renders a "parent" pointer by recursing to the root decl/variable
......@@ -691,31 +717,32 @@ pub const DeclGen = struct {
691717 ptr_val: InternPool.Index,
692718 location: ValueRenderLocation,
693719 ) error{ OutOfMemory, AnalysisFail }!void {
694 const mod = dg.module;
695 const ptr_ty = Type.fromInterned(mod.intern_pool.typeOf(ptr_val));
720 const zcu = dg.zcu;
721 const ip = &zcu.intern_pool;
722 const ptr_ty = Type.fromInterned(ip.typeOf(ptr_val));
696723 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;
698726 switch (ptr.addr) {
699 .decl => |d| try dg.renderDeclValue(writer, ptr_ty, Value.fromInterned(ptr_val), d, location),
700 .anon_decl => |anon_decl| try dg.renderAnonDeclValue(writer, ptr_ty, Value.fromInterned(ptr_val), anon_decl, location),
727 .decl => |d| try dg.renderDeclValue(writer, Value.fromInterned(ptr_val), d, location),
728 .anon_decl => |anon_decl| try dg.renderAnonDeclValue(writer, Value.fromInterned(ptr_val), anon_decl, location),
701729 .int => |int| {
702730 try writer.writeByte('(');
703731 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)});
705733 },
706734 .eu_payload, .opt_payload => |base| {
707 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(base));
708 const base_ty = ptr_base_ty.childType(mod);
735 const ptr_base_ty = Type.fromInterned(ip.typeOf(base));
736 const base_ty = ptr_base_ty.childType(zcu);
709737 // Ensure complete type definition is visible before accessing fields.
710738 _ = try dg.typeToIndex(base_ty, .complete);
711739 const payload_ty = switch (ptr.addr) {
712 .eu_payload => base_ty.errorUnionPayload(mod),
713 .opt_payload => base_ty.optionalChild(mod),
740 .eu_payload => base_ty.errorUnionPayload(zcu),
741 .opt_payload => base_ty.optionalChild(zcu),
714742 else => unreachable,
715743 };
716 const ptr_payload_ty = try mod.adjustPtrTypeChild(ptr_base_ty, payload_ty);
717 const ptr_payload_cty = try dg.typeToIndex(ptr_payload_ty, .complete);
718 if (ptr_cty != ptr_payload_cty) {
744 const payload_cty = try dg.typeToIndex(payload_ty, .forward);
745 if (ptr_child_cty != payload_cty) {
719746 try writer.writeByte('(');
720747 try dg.renderCType(writer, ptr_cty);
721748 try writer.writeByte(')');
......@@ -725,70 +752,90 @@ pub const DeclGen = struct {
725752 try writer.writeAll(")->payload");
726753 },
727754 .elem => |elem| {
728 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(elem.base));
729 const elem_ty = ptr_base_ty.elemType2(mod);
730 const ptr_elem_ty = try mod.adjustPtrTypeChild(ptr_base_ty, elem_ty);
731 const ptr_elem_cty = try dg.typeToIndex(ptr_elem_ty, .complete);
732 if (ptr_cty != ptr_elem_cty) {
755 const ptr_base_ty = Type.fromInterned(ip.typeOf(elem.base));
756 const elem_ty = ptr_base_ty.elemType2(zcu);
757 const elem_cty = try dg.typeToIndex(elem_ty, .forward);
758 if (ptr_child_cty != elem_cty) {
733759 try writer.writeByte('(');
734760 try dg.renderCType(writer, ptr_cty);
735761 try writer.writeByte(')');
736762 }
737763 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)
739765 try writer.writeByte('*');
740766 try dg.renderParentPtr(writer, elem.base, location);
741767 try writer.print(")[{d}]", .{elem.index});
742768 },
743769 .field => |field| {
744 const ptr_base_ty = Type.fromInterned(mod.intern_pool.typeOf(field.base));
745 const base_ty = ptr_base_ty.childType(mod);
770 const ptr_base_ty = Type.fromInterned(ip.typeOf(field.base));
771 const base_ty = ptr_base_ty.childType(zcu);
746772 // Ensure complete type definition is visible before accessing fields.
747773 _ = try dg.typeToIndex(base_ty, .complete);
748 const field_ty = switch (mod.intern_pool.indexToKey(base_ty.toIntern())) {
749 .anon_struct_type, .struct_type, .union_type => base_ty.structFieldType(@as(usize, @intCast(field.index)), mod),
750 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
751 .One, .Many, .C => unreachable,
752 .Slice => switch (field.index) {
753 Value.slice_ptr_index => base_ty.slicePtrFieldType(mod),
754 Value.slice_len_index => Type.usize,
755 else => unreachable,
756 },
774 switch (fieldLocation(ptr_base_ty, ptr_ty, @as(u32, @intCast(field.index)), zcu)) {
775 .begin => {
776 const ptr_base_cty = try dg.typeToIndex(ptr_base_ty, .complete);
777 if (ptr_cty != ptr_base_cty) {
778 try writer.writeByte('(');
779 try dg.renderCType(writer, ptr_cty);
780 try writer.writeByte(')');
781 }
782 try dg.renderParentPtr(writer, field.base, location);
757783 },
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),
769784 .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 }
770806 try writer.writeAll("&(");
771807 try dg.renderParentPtr(writer, field.base, location);
772808 try writer.writeAll(")->");
773809 try dg.writeCValue(writer, name);
774810 },
775811 .byte_offset => |byte_offset| {
776 const u8_ptr_ty = try mod.adjustPtrTypeChild(ptr_ty, Type.u8);
777 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);
812 const u8_ptr_ty = try zcu.adjustPtrTypeChild(ptr_ty, Type.u8);
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 }
779820 try writer.writeAll("((");
780 try dg.renderType(writer, u8_ptr_ty);
821 try dg.renderCType(writer, u8_ptr_cty);
781822 try writer.writeByte(')');
782823 try dg.renderParentPtr(writer, field.base, location);
783824 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),
785826 });
786827 },
787828 .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 }
788835 try writer.writeAll("((");
789836 try dg.renderParentPtr(writer, field.base, location);
790837 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),
792839 });
793840 },
794841 }
......@@ -800,215 +847,21 @@ pub const DeclGen = struct {
800847 fn renderValue(
801848 dg: *DeclGen,
802849 writer: anytype,
803 ty: Type,
804850 val: Value,
805851 location: ValueRenderLocation,
806852 ) error{ OutOfMemory, AnalysisFail }!void {
807 const mod = dg.module;
808 const ip = &mod.intern_pool;
853 const zcu = dg.zcu;
854 const ip = &zcu.intern_pool;
855 const target = &dg.mod.resolved_target.result;
809856
810 const target = mod.getTarget();
811857 const initializer_type: ValueRenderLocation = switch (location) {
812858 .StaticInitializer => .StaticInitializer,
813859 else => .Initializer,
814860 };
815861
816 const safety_on = switch (mod.optimizeMode()) {
817 .Debug, .ReleaseSafe => true,
818 .ReleaseFast, .ReleaseSmall => false,
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)) {
862 const ty = val.typeOf(zcu);
863 if (val.isUndefDeep(zcu)) return dg.renderUndefValue(writer, ty, location);
864 switch (ip.indexToKey(val.toIntern())) {
1012865 // types, not values
1013866 .int_type,
1014867 .ptr_type,
......@@ -1050,26 +903,28 @@ pub const DeclGen = struct {
1050903 .empty_enum_value,
1051904 => unreachable, // non-runtime values
1052905 .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)}),
1054907 .lazy_align, .lazy_size => {
1055908 try writer.writeAll("((");
1056909 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 )});
1058914 },
1059915 },
1060916 .err => |err| try writer.print("zig_error_{}", .{
1061917 fmtIdent(ip.stringToSlice(err.name)),
1062918 }),
1063919 .error_union => |error_union| {
1064 const payload_ty = ty.errorUnionPayload(mod);
1065 const error_ty = ty.errorUnionSet(mod);
1066 const err_int_ty = try mod.errorIntType();
1067 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
920 const payload_ty = ty.errorUnionPayload(zcu);
921 const error_ty = ty.errorUnionSet(zcu);
922 const err_int_ty = try zcu.errorIntType();
923 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1068924 switch (error_union.val) {
1069925 .err_name => |err_name| return dg.renderValue(
1070926 writer,
1071 error_ty,
1072 Value.fromInterned((try mod.intern(.{ .err = .{
927 Value.fromInterned((try zcu.intern(.{ .err = .{
1073928 .ty = error_ty.toIntern(),
1074929 .name = err_name,
1075930 } }))),
......@@ -1077,8 +932,7 @@ pub const DeclGen = struct {
1077932 ),
1078933 .payload => return dg.renderValue(
1079934 writer,
1080 err_int_ty,
1081 try mod.intValue(err_int_ty, 0),
935 try zcu.intValue(err_int_ty, 0),
1082936 location,
1083937 ),
1084938 }
......@@ -1093,9 +947,8 @@ pub const DeclGen = struct {
1093947 try writer.writeAll("{ .payload = ");
1094948 try dg.renderValue(
1095949 writer,
1096 payload_ty,
1097950 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(),
1099952 .payload => |payload| payload,
1100953 }),
1101954 initializer_type,
......@@ -1104,8 +957,7 @@ pub const DeclGen = struct {
1104957 switch (error_union.val) {
1105958 .err_name => |err_name| try dg.renderValue(
1106959 writer,
1107 error_ty,
1108 Value.fromInterned((try mod.intern(.{ .err = .{
960 Value.fromInterned((try zcu.intern(.{ .err = .{
1109961 .ty = error_ty.toIntern(),
1110962 .name = err_name,
1111963 } }))),
......@@ -1113,24 +965,23 @@ pub const DeclGen = struct {
1113965 ),
1114966 .payload => try dg.renderValue(
1115967 writer,
1116 err_int_ty,
1117 try mod.intValue(err_int_ty, 0),
968 try zcu.intValue(err_int_ty, 0),
1118969 location,
1119970 ),
1120971 }
1121972 try writer.writeAll(" }");
1122973 },
1123 .enum_tag => {
1124 const enum_tag = ip.indexToKey(val.ip_index).enum_tag;
1125 const int_tag_ty = ip.typeOf(enum_tag.int);
1126 try dg.renderValue(writer, Type.fromInterned(int_tag_ty), Value.fromInterned(enum_tag.int), location);
1127 },
974 .enum_tag => |enum_tag| try dg.renderValue(
975 writer,
976 Value.fromInterned(enum_tag.int),
977 location,
978 ),
1128979 .float => {
1129 const bits = ty.floatBits(target);
1130 const f128_val = val.toFloat(f128, mod);
980 const bits = ty.floatBits(target.*);
981 const f128_val = val.toFloat(f128, zcu);
1131982
1132983 // 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
1135986 assert(bits <= 128);
1136987 var repr_val_limbs: [BigInt.calcTwosCompLimbCount(128)]BigIntLimb = undefined;
......@@ -1141,26 +992,24 @@ pub const DeclGen = struct {
1141992 };
1142993
1143994 switch (bits) {
1144 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, mod)))),
1145 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, mod)))),
1146 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, mod)))),
1147 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, mod)))),
995 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, zcu)))),
996 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, zcu)))),
997 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, zcu)))),
998 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, zcu)))),
1148999 128 => repr_val_big.set(@as(u128, @bitCast(f128_val))),
11491000 else => unreachable,
11501001 }
11511002
1152 const repr_val = try mod.intValue_big(repr_ty, repr_val_big.toConst());
1153
11541003 var empty = true;
11551004 if (std.math.isFinite(f128_val)) {
11561005 try writer.writeAll("zig_make_");
11571006 try dg.renderTypeForBuiltinFnName(writer, ty);
11581007 try writer.writeByte('(');
11591008 switch (bits) {
1160 16 => try writer.print("{x}", .{val.toFloat(f16, mod)}),
1161 32 => try writer.print("{x}", .{val.toFloat(f32, mod)}),
1162 64 => try writer.print("{x}", .{val.toFloat(f64, mod)}),
1163 80 => try writer.print("{x}", .{val.toFloat(f80, mod)}),
1009 16 => try writer.print("{x}", .{val.toFloat(f16, zcu)}),
1010 32 => try writer.print("{x}", .{val.toFloat(f32, zcu)}),
1011 64 => try writer.print("{x}", .{val.toFloat(f64, zcu)}),
1012 80 => try writer.print("{x}", .{val.toFloat(f80, zcu)}),
11641013 128 => try writer.print("{x}", .{f128_val}),
11651014 else => unreachable,
11661015 }
......@@ -1200,17 +1049,20 @@ pub const DeclGen = struct {
12001049 if (std.math.isNan(f128_val)) switch (bits) {
12011050 // We only actually need to pass the significand, but it will get
12021051 // properly masked anyway, so just pass the whole value.
1203 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, mod)))}),
1204 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, mod)))}),
1205 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, mod)))}),
1206 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, mod)))}),
1052 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, zcu)))}),
1053 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, zcu)))}),
1054 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, zcu)))}),
1055 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, zcu)))}),
12071056 128 => try writer.print("\"0x{x}\"", .{@as(u128, @bitCast(f128_val))}),
12081057 else => unreachable,
12091058 };
12101059 try writer.writeAll(", ");
12111060 empty = false;
12121061 }
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 )});
12141066 if (!empty) try writer.writeByte(')');
12151067 },
12161068 .slice => |slice| {
......@@ -1220,42 +1072,39 @@ pub const DeclGen = struct {
12201072 try writer.writeByte(')');
12211073 }
12221074 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);
12241076 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);
12261078 try writer.writeByte('}');
12271079 },
12281080 .ptr => |ptr| switch (ptr.addr) {
1229 .decl => |d| try dg.renderDeclValue(writer, ty, val, d, location),
1230 .anon_decl => |decl_val| try dg.renderAnonDeclValue(writer, ty, val, decl_val, location),
1081 .decl => |d| try dg.renderDeclValue(writer, val, d, location),
1082 .anon_decl => |decl_val| try dg.renderAnonDeclValue(writer, val, decl_val, location),
12311083 .int => |int| {
12321084 try writer.writeAll("((");
12331085 try dg.renderType(writer, ty);
1234 try writer.print("){x})", .{
1235 try dg.fmtIntLiteral(Type.usize, Value.fromInterned(int), location),
1236 });
1086 try writer.print("){x})", .{try dg.fmtIntLiteral(Value.fromInterned(int), location)});
12371087 },
12381088 .eu_payload,
12391089 .opt_payload,
12401090 .elem,
12411091 .field,
1242 => try dg.renderParentPtr(writer, val.ip_index, location),
1092 => try dg.renderParentPtr(writer, val.toIntern(), location),
12431093 .comptime_field, .comptime_alloc => unreachable,
12441094 },
12451095 .opt => |opt| {
1246 const payload_ty = ty.optionalChild(mod);
1096 const payload_ty = ty.optionalChild(zcu);
12471097
12481098 const is_null_val = Value.makeBool(opt.val == .none);
1249 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod))
1250 return dg.renderValue(writer, Type.bool, is_null_val, location);
1099 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu))
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(
12531103 writer,
1254 payload_ty,
12551104 switch (opt.val) {
1256 .none => switch (payload_ty.zigTypeTag(mod)) {
1257 .ErrorSet => try mod.intValue(try mod.errorIntType(), 0),
1258 .Pointer => try mod.getCoerced(val, payload_ty),
1105 .none => switch (payload_ty.zigTypeTag(zcu)) {
1106 .ErrorSet => try zcu.intValue(try zcu.errorIntType(), 0),
1107 .Pointer => try zcu.getCoerced(val, payload_ty),
12591108 else => unreachable,
12601109 },
12611110 else => |payload| Value.fromInterned(payload),
......@@ -1270,15 +1119,19 @@ pub const DeclGen = struct {
12701119 }
12711120
12721121 try writer.writeAll("{ .payload = ");
1273 try dg.renderValue(writer, payload_ty, Value.fromInterned(switch (opt.val) {
1274 .none => try mod.intern(.{ .undef = payload_ty.ip_index }),
1275 else => |payload| payload,
1276 }), initializer_type);
1122 switch (opt.val) {
1123 .none => try dg.renderUndefValue(writer, payload_ty, initializer_type),
1124 else => |payload| try dg.renderValue(
1125 writer,
1126 Value.fromInterned(payload),
1127 initializer_type,
1128 ),
1129 }
12771130 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);
12791132 try writer.writeAll(" }");
12801133 },
1281 .aggregate => switch (ip.indexToKey(ty.ip_index)) {
1134 .aggregate => switch (ip.indexToKey(ty.toIntern())) {
12821135 .array_type, .vector_type => {
12831136 if (location == .FunctionArgument) {
12841137 try writer.writeByte('(');
......@@ -1287,21 +1140,21 @@ pub const DeclGen = struct {
12871140 }
12881141 // Fall back to generic implementation.
12891142
1290 const ai = ty.arrayInfo(mod);
1291 if (ai.elem_type.eql(Type.u8, mod)) {
1292 var literal = stringLiteral(writer, ty.arrayLenIncludingSentinel(mod));
1143 const ai = ty.arrayInfo(zcu);
1144 if (ai.elem_type.eql(Type.u8, zcu)) {
1145 var literal = stringLiteral(writer, ty.arrayLenIncludingSentinel(zcu));
12931146 try literal.start();
12941147 var index: usize = 0;
12951148 while (index < ai.len) : (index += 1) {
1296 const elem_val = try val.elemValue(mod, index);
1297 const elem_val_u8: u8 = if (elem_val.isUndef(mod))
1149 const elem_val = try val.elemValue(zcu, index);
1150 const elem_val_u8: u8 = if (elem_val.isUndef(zcu))
12981151 undefPattern(u8)
12991152 else
1300 @intCast(elem_val.toUnsignedInt(mod));
1153 @intCast(elem_val.toUnsignedInt(zcu));
13011154 try literal.writeChar(elem_val_u8);
13021155 }
13031156 if (ai.sentinel) |s| {
1304 const s_u8: u8 = @intCast(s.toUnsignedInt(mod));
1157 const s_u8: u8 = @intCast(s.toUnsignedInt(zcu));
13051158 if (s_u8 != 0) try literal.writeChar(s_u8);
13061159 }
13071160 try literal.end();
......@@ -1310,12 +1163,12 @@ pub const DeclGen = struct {
13101163 var index: usize = 0;
13111164 while (index < ai.len) : (index += 1) {
13121165 if (index != 0) try writer.writeByte(',');
1313 const elem_val = try val.elemValue(mod, index);
1314 try dg.renderValue(writer, ai.elem_type, elem_val, initializer_type);
1166 const elem_val = try val.elemValue(zcu, index);
1167 try dg.renderValue(writer, elem_val, initializer_type);
13151168 }
13161169 if (ai.sentinel) |s| {
13171170 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);
13191172 }
13201173 try writer.writeByte('}');
13211174 }
......@@ -1333,19 +1186,21 @@ pub const DeclGen = struct {
13331186 const comptime_val = tuple.values.get(ip)[field_index];
13341187 if (comptime_val != .none) continue;
13351188 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
13381191 if (!empty) try writer.writeByte(',');
13391192
1340 const field_val = Value.fromInterned(switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1341 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
1342 .ty = field_ty.toIntern(),
1343 .storage = .{ .u64 = bytes[field_index] },
1344 } }),
1345 .elems => |elems| elems[field_index],
1346 .repeated_elem => |elem| elem,
1347 });
1348 try dg.renderValue(writer, field_ty, field_val, initializer_type);
1193 const field_val = Value.fromInterned(
1194 switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1195 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1196 .ty = field_ty.toIntern(),
1197 .storage = .{ .u64 = bytes[field_index] },
1198 } }),
1199 .elems => |elems| elems[field_index],
1200 .repeated_elem => |elem| elem,
1201 },
1202 );
1203 try dg.renderValue(writer, field_val, initializer_type);
13491204
13501205 empty = false;
13511206 }
......@@ -1366,43 +1221,43 @@ pub const DeclGen = struct {
13661221 for (0..struct_type.field_types.len) |field_index| {
13671222 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
13681223 if (struct_type.fieldIsComptime(ip, field_index)) continue;
1369 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1224 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
13701225
13711226 if (!empty) try writer.writeByte(',');
1372 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1373 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
1227 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1228 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
13741229 .ty = field_ty.toIntern(),
13751230 .storage = .{ .u64 = bytes[field_index] },
13761231 } }),
13771232 .elems => |elems| elems[field_index],
13781233 .repeated_elem => |elem| elem,
13791234 };
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
13821237 empty = false;
13831238 }
13841239 try writer.writeByte('}');
13851240 },
13861241 .@"packed" => {
1387 const int_info = ty.intInfo(mod);
1242 const int_info = ty.intInfo(zcu);
13881243
13891244 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
13921247 var bit_offset: u64 = 0;
13931248 var eff_num_fields: usize = 0;
13941249
13951250 for (0..struct_type.field_types.len) |field_index| {
13961251 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;
13981253 eff_num_fields += 1;
13991254 }
14001255
14011256 if (eff_num_fields == 0) {
14021257 try writer.writeByte('(');
1403 try dg.renderValue(writer, ty, Value.undef, initializer_type);
1258 try dg.renderUndefValue(writer, ty, initializer_type);
14041259 try writer.writeByte(')');
1405 } else if (ty.bitSize(mod) > 64) {
1260 } else if (ty.bitSize(zcu) > 64) {
14061261 // zig_or_u128(zig_or_u128(zig_shl_u128(a, a_off), zig_shl_u128(b, b_off)), zig_shl_u128(c, c_off))
14071262 var num_or = eff_num_fields - 1;
14081263 while (num_or > 0) : (num_or -= 1) {
......@@ -1415,10 +1270,10 @@ pub const DeclGen = struct {
14151270 var needs_closing_paren = false;
14161271 for (0..struct_type.field_types.len) |field_index| {
14171272 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) {
1421 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
1275 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1276 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
14221277 .ty = field_ty.toIntern(),
14231278 .storage = .{ .u64 = bytes[field_index] },
14241279 } }),
......@@ -1432,8 +1287,7 @@ pub const DeclGen = struct {
14321287 try writer.writeByte('(');
14331288 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
14341289 try writer.writeAll(", ");
1435 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);
1436 try dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);
1290 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
14371291 try writer.writeByte(')');
14381292 } else {
14391293 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
......@@ -1442,7 +1296,7 @@ pub const DeclGen = struct {
14421296 if (needs_closing_paren) try writer.writeByte(')');
14431297 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);
14461300 needs_closing_paren = true;
14471301 eff_index += 1;
14481302 }
......@@ -1452,15 +1306,15 @@ pub const DeclGen = struct {
14521306 var empty = true;
14531307 for (0..struct_type.field_types.len) |field_index| {
14541308 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
14571311 if (!empty) try writer.writeAll(" | ");
14581312 try writer.writeByte('(');
14591313 try dg.renderType(writer, ty);
14601314 try writer.writeByte(')');
14611315
1462 const field_val = switch (ip.indexToKey(val.ip_index).aggregate.storage) {
1463 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
1316 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1317 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
14641318 .ty = field_ty.toIntern(),
14651319 .storage = .{ .u64 = bytes[field_index] },
14661320 } }),
......@@ -1469,15 +1323,14 @@ pub const DeclGen = struct {
14691323 };
14701324
14711325 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);
14731327 try writer.writeAll(" << ");
1474 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);
1475 try dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);
1328 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
14761329 } else {
1477 try dg.renderValue(writer, field_ty, Value.fromInterned(field_val), .Other);
1330 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
14781331 }
14791332
1480 bit_offset += field_ty.bitSize(mod);
1333 bit_offset += field_ty.bitSize(zcu);
14811334 empty = false;
14821335 }
14831336 try writer.writeByte(')');
......@@ -1488,9 +1341,9 @@ pub const DeclGen = struct {
14881341 else => unreachable,
14891342 },
14901343 .un => |un| {
1491 const union_obj = mod.typeToUnion(ty).?;
1344 const union_obj = zcu.typeToUnion(ty).?;
14921345 if (un.tag == .none) {
1493 const backing_ty = try ty.unionBackingType(mod);
1346 const backing_ty = try ty.unionBackingType(zcu);
14941347 switch (union_obj.getLayout(ip)) {
14951348 .@"packed" => {
14961349 if (!location.isInitializer()) {
......@@ -1498,20 +1351,20 @@ pub const DeclGen = struct {
14981351 try dg.renderType(writer, backing_ty);
14991352 try writer.writeByte(')');
15001353 }
1501 try dg.renderValue(writer, backing_ty, Value.fromInterned(un.val), initializer_type);
1354 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
15021355 },
15031356 .@"extern" => {
15041357 if (location == .StaticInitializer) {
15051358 return dg.fail("TODO: C backend: implement extern union backing type rendering in static initializers", .{});
15061359 }
15071360
1508 const ptr_ty = try mod.singleConstPtrType(ty);
1361 const ptr_ty = try zcu.singleConstPtrType(ty);
15091362 try writer.writeAll("*((");
15101363 try dg.renderType(writer, ptr_ty);
15111364 try writer.writeAll(")(");
15121365 try dg.renderType(writer, backing_ty);
15131366 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);
15151368 try writer.writeAll("})");
15161369 },
15171370 else => unreachable,
......@@ -1523,21 +1376,21 @@ pub const DeclGen = struct {
15231376 try writer.writeByte(')');
15241377 }
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)).?;
15271380 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
15281381 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];
15291382 if (union_obj.getLayout(ip) == .@"packed") {
1530 if (field_ty.hasRuntimeBits(mod)) {
1531 if (field_ty.isPtrAtRuntime(mod)) {
1383 if (field_ty.hasRuntimeBits(zcu)) {
1384 if (field_ty.isPtrAtRuntime(zcu)) {
15321385 try writer.writeByte('(');
15331386 try dg.renderType(writer, ty);
15341387 try writer.writeByte(')');
1535 } else if (field_ty.zigTypeTag(mod) == .Float) {
1388 } else if (field_ty.zigTypeTag(zcu) == .Float) {
15361389 try writer.writeByte('(');
15371390 try dg.renderType(writer, ty);
15381391 try writer.writeByte(')');
15391392 }
1540 try dg.renderValue(writer, field_ty, Value.fromInterned(un.val), initializer_type);
1393 try dg.renderValue(writer, Value.fromInterned(un.val), initializer_type);
15411394 } else {
15421395 try writer.writeAll("0");
15431396 }
......@@ -1545,30 +1398,236 @@ pub const DeclGen = struct {
15451398 }
15461399
15471400 try writer.writeByte('{');
1548 if (ty.unionTagTypeSafety(mod)) |tag_ty| {
1549 const layout = mod.getUnionLayout(union_obj);
1401 if (ty.unionTagTypeSafety(zcu)) |_| {
1402 const layout = zcu.getUnionLayout(union_obj);
15501403 if (layout.tag_size != 0) {
15511404 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);
15531406 }
1554 if (ty.unionHasAllZeroBitFieldTypes(mod)) return try writer.writeByte('}');
1407 if (ty.unionHasAllZeroBitFieldTypes(zcu)) return try writer.writeByte('}');
15551408 if (layout.tag_size != 0) try writer.writeByte(',');
15561409 try writer.writeAll(" .payload = {");
15571410 }
1558 if (field_ty.hasRuntimeBits(mod)) {
1411 if (field_ty.hasRuntimeBits(zcu)) {
15591412 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);
15611414 try writer.writeByte(' ');
15621415 } else for (0..union_obj.field_types.len) |this_field_index| {
15631416 const this_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[this_field_index]);
1564 if (!this_field_ty.hasRuntimeBits(mod)) continue;
1565 try dg.renderValue(writer, this_field_ty, Value.undef, initializer_type);
1417 if (!this_field_ty.hasRuntimeBits(zcu)) continue;
1418 try dg.renderUndefValue(writer, this_field_ty, initializer_type);
15661419 break;
15671420 }
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
15691533 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(')');
15701544 }
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('}');
15711566 },
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 }),
15721631 }
15731632 }
15741633
......@@ -1583,14 +1642,14 @@ pub const DeclGen = struct {
15831642 },
15841643 ) !void {
15851644 const store = &dg.ctypes.set;
1586 const mod = dg.module;
1587 const ip = &mod.intern_pool;
1645 const zcu = dg.zcu;
1646 const ip = &zcu.intern_pool;
15881647
1589 const fn_decl = mod.declPtr(fn_decl_index);
1590 const fn_ty = fn_decl.typeOf(mod);
1648 const fn_decl = zcu.declPtr(fn_decl_index);
1649 const fn_ty = fn_decl.typeOf(zcu);
15911650 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).?;
15941653 if (fn_info.cc == .Naked) {
15951654 switch (kind) {
15961655 .forward => try w.writeAll("zig_naked_decl "),
......@@ -1598,11 +1657,11 @@ pub const DeclGen = struct {
15981657 else => unreachable,
15991658 }
16001659 }
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)
16021661 try w.writeAll("zig_cold ");
16031662 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
16071666 if (toCallingConvention(fn_info.cc)) |call_conv| {
16081667 try w.print("{}zig_callconv({s})", .{ trailing, call_conv });
......@@ -1629,7 +1688,7 @@ pub const DeclGen = struct {
16291688 try renderTypeSuffix(
16301689 dg.pass,
16311690 store.*,
1632 mod,
1691 zcu,
16331692 w,
16341693 fn_cty_idx,
16351694 .suffix,
......@@ -1647,11 +1706,11 @@ pub const DeclGen = struct {
16471706 }
16481707 switch (name) {
16491708 .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);
16511710 const external_name = ip.stringToSlice(
16521711 if (maybe_exports) |exports|
16531712 exports.items[export_index].opts.name
1654 else if (fn_decl.isExtern(mod))
1713 else if (fn_decl.isExtern(zcu))
16551714 fn_decl.name
16561715 else
16571716 break :mangled,
......@@ -1694,15 +1753,15 @@ pub const DeclGen = struct {
16941753 }
16951754
16961755 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);
16981757 }
16991758
17001759 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);
17021761 }
17031762
17041763 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);
17061765 }
17071766
17081767 /// Renders a type as a single identifier, generating intermediate typedefs
......@@ -1722,9 +1781,9 @@ pub const DeclGen = struct {
17221781
17231782 fn renderCType(dg: *DeclGen, w: anytype, idx: CType.Index) error{ OutOfMemory, AnalysisFail }!void {
17241783 const store = &dg.ctypes.set;
1725 const mod = dg.module;
1726 _ = try renderTypePrefix(dg.pass, store.*, mod, w, idx, .suffix, .{});
1727 try renderTypeSuffix(dg.pass, store.*, mod, w, idx, .suffix, .{});
1784 const zcu = dg.zcu;
1785 _ = try renderTypePrefix(dg.pass, store.*, zcu, w, idx, .suffix, .{});
1786 try renderTypeSuffix(dg.pass, store.*, zcu, w, idx, .suffix, .{});
17281787 }
17291788
17301789 const IntCastContext = union(enum) {
......@@ -1737,15 +1796,13 @@ pub const DeclGen = struct {
17371796 value: Value,
17381797 },
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 {
17411800 switch (self.*) {
17421801 .c_value => |v| {
17431802 try v.f.writeCValue(w, v.value, location);
17441803 try v.v.elem(v.f, w);
17451804 },
1746 .value => |v| {
1747 try dg.renderValue(w, value_ty, v.value, location);
1748 },
1805 .value => |v| try dg.renderValue(w, v.value, location),
17491806 }
17501807 }
17511808 };
......@@ -1764,18 +1821,18 @@ pub const DeclGen = struct {
17641821 /// | > 64 bit integer | < 64 bit integer | zig_make_<dest_ty>(0, src)
17651822 /// | > 64 bit integer | > 64 bit integer | zig_make_<dest_ty>(zig_hi_<src_ty>(src), zig_lo_<src_ty>(src))
17661823 fn renderIntCast(dg: *DeclGen, w: anytype, dest_ty: Type, context: IntCastContext, src_ty: Type, location: ValueRenderLocation) !void {
1767 const mod = dg.module;
1768 const dest_bits = dest_ty.bitSize(mod);
1769 const dest_int_info = dest_ty.intInfo(mod);
1824 const zcu = dg.zcu;
1825 const dest_bits = dest_ty.bitSize(zcu);
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);
17721829 const src_eff_ty: Type = if (src_is_ptr) switch (dest_int_info.signedness) {
17731830 .unsigned => Type.usize,
17741831 .signed => Type.isize,
17751832 } else src_ty;
17761833
1777 const src_bits = src_eff_ty.bitSize(mod);
1778 const src_int_info = if (src_eff_ty.isAbiInt(mod)) src_eff_ty.intInfo(mod) else null;
1834 const src_bits = src_eff_ty.bitSize(zcu);
1835 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
17791836 if (dest_bits <= 64 and src_bits <= 64) {
17801837 const needs_cast = src_int_info == null or
17811838 (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or
......@@ -1791,7 +1848,7 @@ pub const DeclGen = struct {
17911848 try dg.renderType(w, src_eff_ty);
17921849 try w.writeByte(')');
17931850 }
1794 try context.writeValue(dg, w, src_ty, location);
1851 try context.writeValue(dg, w, location);
17951852 } else if (dest_bits <= 64 and src_bits > 64) {
17961853 assert(!src_is_ptr);
17971854 if (dest_bits < 64) {
......@@ -1802,7 +1859,7 @@ pub const DeclGen = struct {
18021859 try w.writeAll("zig_lo_");
18031860 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
18041861 try w.writeByte('(');
1805 try context.writeValue(dg, w, src_ty, .FunctionArgument);
1862 try context.writeValue(dg, w, .FunctionArgument);
18061863 try w.writeByte(')');
18071864 } else if (dest_bits > 64 and src_bits <= 64) {
18081865 try w.writeAll("zig_make_");
......@@ -1813,7 +1870,7 @@ pub const DeclGen = struct {
18131870 try dg.renderType(w, src_eff_ty);
18141871 try w.writeByte(')');
18151872 }
1816 try context.writeValue(dg, w, src_ty, .FunctionArgument);
1873 try context.writeValue(dg, w, .FunctionArgument);
18171874 try w.writeByte(')');
18181875 } else {
18191876 assert(!src_is_ptr);
......@@ -1822,11 +1879,11 @@ pub const DeclGen = struct {
18221879 try w.writeAll("(zig_hi_");
18231880 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
18241881 try w.writeByte('(');
1825 try context.writeValue(dg, w, src_ty, .FunctionArgument);
1882 try context.writeValue(dg, w, .FunctionArgument);
18261883 try w.writeAll("), zig_lo_");
18271884 try dg.renderTypeForBuiltinFnName(w, src_eff_ty);
18281885 try w.writeByte('(');
1829 try context.writeValue(dg, w, src_ty, .FunctionArgument);
1886 try context.writeValue(dg, w, .FunctionArgument);
18301887 try w.writeAll("))");
18311888 }
18321889 }
......@@ -1848,8 +1905,8 @@ pub const DeclGen = struct {
18481905 alignment: Alignment,
18491906 kind: CType.Kind,
18501907 ) error{ OutOfMemory, AnalysisFail }!void {
1851 const mod = dg.module;
1852 const alignas = CType.AlignAs.init(alignment, ty.abiAlignment(mod));
1908 const zcu = dg.zcu;
1909 const alignas = CType.AlignAs.init(alignment, ty.abiAlignment(zcu));
18531910 try dg.renderCTypeAndName(w, try dg.typeToIndex(ty, kind), name, qualifiers, alignas);
18541911 }
18551912
......@@ -1862,7 +1919,7 @@ pub const DeclGen = struct {
18621919 alignas: CType.AlignAs,
18631920 ) error{ OutOfMemory, AnalysisFail }!void {
18641921 const store = &dg.ctypes.set;
1865 const mod = dg.module;
1922 const zcu = dg.zcu;
18661923
18671924 switch (alignas.abiOrder()) {
18681925 .lt => try w.print("zig_under_align({}) ", .{alignas.toByteUnits()}),
......@@ -1870,39 +1927,46 @@ pub const DeclGen = struct {
18701927 .gt => try w.print("zig_align({}) ", .{alignas.toByteUnits()}),
18711928 }
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);
18741931 try w.print("{}", .{trailing});
1875 try dg.writeCValue(w, name);
1876 try renderTypeSuffix(dg.pass, store.*, mod, w, cty_idx, .suffix, .{});
1932 try dg.writeName(w, name);
1933 try renderTypeSuffix(dg.pass, store.*, zcu, w, cty_idx, .suffix, .{});
18771934 }
18781935
18791936 fn declIsGlobal(dg: *DeclGen, val: Value) bool {
1880 const mod = dg.module;
1881 return switch (mod.intern_pool.indexToKey(val.ip_index)) {
1882 .variable => |variable| mod.decl_exports.contains(variable.decl),
1937 const zcu = dg.zcu;
1938 return switch (zcu.intern_pool.indexToKey(val.toIntern())) {
1939 .variable => |variable| zcu.decl_exports.contains(variable.decl),
18831940 .extern_func => true,
1884 .func => |func| mod.decl_exports.contains(func.owner_decl),
1941 .func => |func| zcu.decl_exports.contains(func.owner_decl),
18851942 else => unreachable,
18861943 };
18871944 }
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
18891956 fn writeCValue(dg: *DeclGen, w: anytype, c_value: CValue) !void {
18901957 switch (c_value) {
1891 .none => unreachable,
1892 .local, .new_local => |i| return w.print("t{d}", .{i}),
1893 .local_ref => |i| return w.print("&t{d}", .{i}),
1894 .constant => |val| return renderAnonDeclName(w, val),
1895 .arg => |i| return w.print("a{d}", .{i}),
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),
1958 .none, .new_local, .local, .local_ref => unreachable,
1959 .constant => |val| try renderAnonDeclName(w, val),
1960 .arg, .arg_array => unreachable,
1961 .field => |i| try w.print("f{d}", .{i}),
1962 .decl => |decl| try dg.renderDeclName(w, decl, 0),
18991963 .decl_ref => |decl| {
19001964 try w.writeByte('&');
1901 return dg.renderDeclName(w, decl, 0);
1965 try dg.renderDeclName(w, decl, 0);
19021966 },
1903 .undef => |ty| return dg.renderValue(w, ty, Value.undef, .Other),
1904 .identifier => |ident| return w.print("{ }", .{fmtIdent(ident)}),
1905 .payload_identifier => |ident| return w.print("{ }.{ }", .{
1967 .undef => |ty| try dg.renderUndefValue(w, ty, .Other),
1968 .identifier => |ident| try w.print("{ }", .{fmtIdent(ident)}),
1969 .payload_identifier => |ident| try w.print("{ }.{ }", .{
19061970 fmtIdent("payload"),
19071971 fmtIdent(ident),
19081972 }),
......@@ -1911,26 +1975,17 @@ pub const DeclGen = struct {
19111975
19121976 fn writeCValueDeref(dg: *DeclGen, w: anytype, c_value: CValue) !void {
19131977 switch (c_value) {
1914 .none => unreachable,
1915 .local, .new_local => |i| return w.print("(*t{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}),
1978 .none, .new_local, .local, .local_ref, .constant, .arg, .arg_array => unreachable,
1979 .field => |i| try w.print("f{d}", .{i}),
19251980 .decl => |decl| {
19261981 try w.writeAll("(*");
19271982 try dg.renderDeclName(w, decl, 0);
1928 return w.writeByte(')');
1983 try w.writeByte(')');
19291984 },
1930 .decl_ref => |decl| return dg.renderDeclName(w, decl, 0),
1985 .decl_ref => |decl| try dg.renderDeclName(w, decl, 0),
19311986 .undef => unreachable,
1932 .identifier => |ident| return w.print("(*{ })", .{fmtIdent(ident)}),
1933 .payload_identifier => |ident| return w.print("(*{ }.{ })", .{
1987 .identifier => |ident| try w.print("(*{ })", .{fmtIdent(ident)}),
1988 .payload_identifier => |ident| try w.print("(*{ }.{ })", .{
19341989 fmtIdent("payload"),
19351990 fmtIdent(ident),
19361991 }),
......@@ -1950,12 +2005,12 @@ pub const DeclGen = struct {
19502005
19512006 fn writeCValueDerefMember(dg: *DeclGen, writer: anytype, c_value: CValue, member: CValue) !void {
19522007 switch (c_value) {
1953 .none, .constant, .field, .undef => unreachable,
1954 .new_local, .local, .arg, .arg_array, .decl, .identifier, .payload_identifier => {
2008 .none, .new_local, .local, .local_ref, .constant, .field, .undef, .arg, .arg_array => unreachable,
2009 .decl, .identifier, .payload_identifier => {
19552010 try dg.writeCValue(writer, c_value);
19562011 try writer.writeAll("->");
19572012 },
1958 .local_ref, .decl_ref => {
2013 .decl_ref => {
19592014 try dg.writeCValueDeref(writer, c_value);
19602015 try writer.writeByte('.');
19612016 },
......@@ -1969,11 +2024,12 @@ pub const DeclGen = struct {
19692024 variable: InternPool.Key.Variable,
19702025 fwd_kind: enum { tentative, final },
19712026 ) !void {
1972 const decl = dg.module.declPtr(decl_index);
2027 const zcu = dg.zcu;
2028 const decl = zcu.declPtr(decl_index);
19732029 const fwd = dg.fwdDeclWriter();
19742030 const is_global = variable.is_extern or dg.declIsGlobal(decl.val);
19752031 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);
19772033 const export_weak_linkage = if (maybe_exports) |exports|
19782034 exports.items[0].opts.linkage == .weak
19792035 else
......@@ -1982,14 +2038,14 @@ pub const DeclGen = struct {
19822038 if (variable.is_threadlocal) try fwd.writeAll("zig_threadlocal ");
19832039 try dg.renderTypeAndName(
19842040 fwd,
1985 decl.typeOf(dg.module),
2041 decl.typeOf(zcu),
19862042 .{ .decl = decl_index },
19872043 CQualifiers.init(.{ .@"const" = variable.is_const }),
19882044 decl.alignment,
19892045 .complete,
19902046 );
19912047 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|
19932049 exports.items[0].opts.name
19942050 else if (variable.is_extern)
19952051 decl.name
......@@ -2007,23 +2063,23 @@ pub const DeclGen = struct {
20072063 }
20082064
20092065 fn renderDeclName(dg: *DeclGen, writer: anytype, decl_index: InternPool.DeclIndex, export_index: u32) !void {
2010 const mod = dg.module;
2011 const decl = mod.declPtr(decl_index);
2066 const zcu = dg.zcu;
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| {
20142070 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)),
20162072 });
2017 } else if (decl.getExternDecl(mod).unwrap()) |extern_decl_index| {
2073 } else if (decl.getExternDecl(zcu).unwrap()) |extern_decl_index| {
20182074 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)),
20202076 });
20212077 } else {
20222078 // MSVC has a limit of 4095 character token length limit, and fmtIdent can (worst case),
20232079 // expand to 3x the length of its input, but let's cut it off at a much shorter limit.
20242080 var name: [100]u8 = undefined;
20252081 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) {
20272083 error.NoSpaceLeft => {},
20282084 };
20292085 try writer.print("{}__{d}", .{
......@@ -2033,8 +2089,8 @@ pub const DeclGen = struct {
20332089 }
20342090 }
20352091
2036 fn renderAnonDeclName(writer: anytype, anon_decl_val: InternPool.Index) !void {
2037 return writer.print("__anon_{d}", .{@intFromEnum(anon_decl_val)});
2092 fn renderAnonDeclName(writer: anytype, anon_decl_val: Value) !void {
2093 try writer.print("__anon_{d}", .{@intFromEnum(anon_decl_val.toIntern())});
20382094 }
20392095
20402096 fn renderTypeForBuiltinFnName(dg: *DeclGen, writer: anytype, ty: Type) !void {
......@@ -2047,7 +2103,7 @@ pub const DeclGen = struct {
20472103 if (cty.isBool())
20482104 signAbbrev(.unsigned)
20492105 else if (cty.isInteger())
2050 signAbbrev(cty.signedness(dg.module.getTarget()))
2106 signAbbrev(cty.signedness(dg.mod))
20512107 else if (cty.isFloat())
20522108 @as(u8, 'f')
20532109 else if (cty.isPointer())
......@@ -2056,7 +2112,7 @@ pub const DeclGen = struct {
20562112 return dg.fail("TODO: CBE: implement renderTypeForBuiltinFnName for type {}", .{
20572113 cty.tag(),
20582114 }),
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,
20602116 }),
20612117 .array => try writer.writeAll("big"),
20622118 }
......@@ -2065,43 +2121,39 @@ pub const DeclGen = struct {
20652121 fn renderBuiltinInfo(dg: *DeclGen, writer: anytype, ty: Type, info: BuiltinInfo) !void {
20662122 const cty = try dg.typeToCType(ty, .complete);
20672123 const is_big = cty.tag() == .array;
2068
20692124 switch (info) {
20702125 .none => if (!is_big) return,
20712126 .bits => {},
20722127 }
20732128
2074 const mod = dg.module;
2075 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{
2129 const zcu = dg.zcu;
2130 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
20762131 .signedness = .unsigned,
2077 .bits = @as(u16, @intCast(ty.bitSize(mod))),
2132 .bits = @as(u16, @intCast(ty.bitSize(zcu))),
20782133 };
20792134
20802135 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});
2081
2082 const bits_ty = if (is_big) Type.u16 else Type.u8;
20832136 try writer.print(", {}", .{try dg.fmtIntLiteral(
2084 bits_ty,
2085 try mod.intValue(bits_ty, int_info.bits),
2137 try zcu.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
20862138 .FunctionArgument,
20872139 )});
20882140 }
20892141
20902142 fn fmtIntLiteral(
20912143 dg: *DeclGen,
2092 ty: Type,
20932144 val: Value,
20942145 loc: ValueRenderLocation,
20952146 ) !std.fmt.Formatter(formatIntLiteral) {
2096 const mod = dg.module;
2147 const zcu = dg.zcu;
20972148 const kind: CType.Kind = switch (loc) {
20982149 .FunctionArgument => .parameter,
20992150 .Initializer, .Other => .complete,
21002151 .StaticInitializer => .global,
21012152 };
2153 const ty = val.typeOf(zcu);
21022154 return std.fmt.Formatter(formatIntLiteral){ .data = .{
21032155 .dg = dg,
2104 .int_info = ty.intInfo(mod),
2156 .int_info = ty.intInfo(zcu),
21052157 .kind = kind,
21062158 .cty = try dg.typeToCType(ty, kind),
21072159 .val = val,
......@@ -2133,7 +2185,7 @@ const RenderCTypeTrailing = enum {
21332185 }
21342186};
21352187fn renderTypeName(
2136 mod: *Module,
2188 zcu: *Zcu,
21372189 w: anytype,
21382190 idx: CType.Index,
21392191 cty: CType,
......@@ -2157,7 +2209,7 @@ fn renderTypeName(
21572209 try w.print("{s} {s}{}__{d}", .{
21582210 @tagName(tag)["fwd_".len..],
21592211 attributes,
2160 fmtIdent(mod.intern_pool.stringToSlice(mod.declPtr(owner_decl).name)),
2212 fmtIdent(zcu.intern_pool.stringToSlice(zcu.declPtr(owner_decl).name)),
21612213 @intFromEnum(owner_decl),
21622214 });
21632215 },
......@@ -2166,7 +2218,7 @@ fn renderTypeName(
21662218fn renderTypePrefix(
21672219 pass: DeclGen.Pass,
21682220 store: CType.Store.Set,
2169 mod: *Module,
2221 zcu: *Zcu,
21702222 w: anytype,
21712223 idx: CType.Index,
21722224 parent_fix: CTypeFix,
......@@ -2224,7 +2276,7 @@ fn renderTypePrefix(
22242276 const child_trailing = try renderTypePrefix(
22252277 pass,
22262278 store,
2227 mod,
2279 zcu,
22282280 w,
22292281 child_idx,
22302282 .prefix,
......@@ -2247,7 +2299,7 @@ fn renderTypePrefix(
22472299 => {
22482300 const child_idx = cty.cast(CType.Payload.Sequence).?.data.elem_type;
22492301 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);
22512303 switch (parent_fix) {
22522304 .prefix => {
22532305 try w.print("{}(", .{child_trailing});
......@@ -2262,12 +2314,12 @@ fn renderTypePrefix(
22622314 => switch (pass) {
22632315 .decl => |decl_index| try w.print("decl__{d}_{d}", .{ @intFromEnum(decl_index), idx }),
22642316 .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, ""),
22662318 },
22672319
22682320 .fwd_struct,
22692321 .fwd_union,
2270 => try renderTypeName(mod, w, idx, cty, ""),
2322 => try renderTypeName(zcu, w, idx, cty, ""),
22712323
22722324 .unnamed_struct,
22732325 .unnamed_union,
......@@ -2278,7 +2330,7 @@ fn renderTypePrefix(
22782330 @tagName(tag)["unnamed_".len..],
22792331 if (cty.isPacked()) "zig_packed(" else "",
22802332 });
2281 try renderAggregateFields(mod, w, store, cty, 1);
2333 try renderAggregateFields(zcu, w, store, cty, 1);
22822334 if (cty.isPacked()) try w.writeByte(')');
22832335 },
22842336
......@@ -2291,7 +2343,7 @@ fn renderTypePrefix(
22912343 => return renderTypePrefix(
22922344 pass,
22932345 store,
2294 mod,
2346 zcu,
22952347 w,
22962348 cty.cast(CType.Payload.Aggregate).?.data.fwd_decl,
22972349 parent_fix,
......@@ -2304,7 +2356,7 @@ fn renderTypePrefix(
23042356 const child_trailing = try renderTypePrefix(
23052357 pass,
23062358 store,
2307 mod,
2359 zcu,
23082360 w,
23092361 cty.cast(CType.Payload.Function).?.data.return_type,
23102362 .suffix,
......@@ -2331,7 +2383,7 @@ fn renderTypePrefix(
23312383fn renderTypeSuffix(
23322384 pass: DeclGen.Pass,
23332385 store: CType.Store.Set,
2334 mod: *Module,
2386 zcu: *Zcu,
23352387 w: anytype,
23362388 idx: CType.Index,
23372389 parent_fix: CTypeFix,
......@@ -2385,7 +2437,7 @@ fn renderTypeSuffix(
23852437 => try renderTypeSuffix(
23862438 pass,
23872439 store,
2388 mod,
2440 zcu,
23892441 w,
23902442 cty.cast(CType.Payload.Child).?.data,
23912443 .prefix,
......@@ -2404,7 +2456,7 @@ fn renderTypeSuffix(
24042456 try renderTypeSuffix(
24052457 pass,
24062458 store,
2407 mod,
2459 zcu,
24082460 w,
24092461 cty.cast(CType.Payload.Sequence).?.data.elem_type,
24102462 .suffix,
......@@ -2444,9 +2496,9 @@ fn renderTypeSuffix(
24442496 if (need_comma) try w.writeAll(", ");
24452497 need_comma = true;
24462498 const trailing =
2447 try renderTypePrefix(pass, store, mod, w, param_type, .suffix, qualifiers);
2499 try renderTypePrefix(pass, store, zcu, w, param_type, .suffix, qualifiers);
24482500 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, .{});
24502502 }
24512503 switch (tag) {
24522504 .function => {},
......@@ -2460,12 +2512,12 @@ fn renderTypeSuffix(
24602512 if (!need_comma) try w.writeAll("void");
24612513 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, .{});
24642516 },
24652517 }
24662518}
24672519fn renderAggregateFields(
2468 mod: *Module,
2520 zcu: *Zcu,
24692521 writer: anytype,
24702522 store: CType.Store.Set,
24712523 cty: CType,
......@@ -2480,9 +2532,9 @@ fn renderAggregateFields(
24802532 .eq => {},
24812533 .gt => try writer.print("zig_align({}) ", .{field.alignas.toByteUnits()}),
24822534 }
2483 const trailing = try renderTypePrefix(.flush, store, mod, writer, field.type, .suffix, .{});
2535 const trailing = try renderTypePrefix(.flush, store, zcu, writer, field.type, .suffix, .{});
24842536 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, .{});
24862538 try writer.writeAll(";\n");
24872539 }
24882540 try writer.writeByteNTimes(' ', indent);
......@@ -2490,7 +2542,7 @@ fn renderAggregateFields(
24902542}
24912543
24922544pub fn genTypeDecl(
2493 mod: *Module,
2545 zcu: *Zcu,
24942546 writer: anytype,
24952547 global_store: CType.Store.Set,
24962548 global_idx: CType.Index,
......@@ -2503,9 +2555,9 @@ pub fn genTypeDecl(
25032555 switch (global_cty.tag()) {
25042556 .fwd_anon_struct => if (pass != .flush) {
25052557 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, .{});
25072559 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, .{});
25092561 try writer.writeAll(";\n");
25102562 },
25112563
......@@ -2526,14 +2578,14 @@ pub fn genTypeDecl(
25262578 _ = try renderTypePrefix(
25272579 .flush,
25282580 global_store,
2529 mod,
2581 zcu,
25302582 writer,
25312583 global_idx,
25322584 .suffix,
25332585 .{},
25342586 );
25352587 try writer.writeAll("; /* ");
2536 try mod.declPtr(owner_decl).renderFullyQualifiedName(mod, writer);
2588 try zcu.declPtr(owner_decl).renderFullyQualifiedName(zcu, writer);
25372589 try writer.writeAll(" */\n");
25382590 },
25392591
......@@ -2546,14 +2598,14 @@ pub fn genTypeDecl(
25462598 => {
25472599 const fwd_idx = global_cty.cast(CType.Payload.Aggregate).?.data.fwd_decl;
25482600 try renderTypeName(
2549 mod,
2601 zcu,
25502602 writer,
25512603 fwd_idx,
25522604 global_store.indexToCType(fwd_idx),
25532605 if (global_cty.isPacked()) "zig_packed(" else "",
25542606 );
25552607 try writer.writeByte(' ');
2556 try renderAggregateFields(mod, writer, global_store, global_cty, 0);
2608 try renderAggregateFields(zcu, writer, global_store, global_cty, 0);
25572609 if (global_cty.isPacked()) try writer.writeByte(')');
25582610 try writer.writeAll(";\n");
25592611 },
......@@ -2566,30 +2618,30 @@ pub fn genTypeDecl(
25662618 }
25672619}
25682620
2569pub fn genGlobalAsm(mod: *Module, writer: anytype) !void {
2570 for (mod.global_assembly.values()) |asm_source| {
2621pub fn genGlobalAsm(zcu: *Zcu, writer: anytype) !void {
2622 for (zcu.global_assembly.values()) |asm_source| {
25712623 try writer.print("__asm({s});\n", .{fmtStringLiteral(asm_source, null)});
25722624 }
25732625}
25742626
25752627pub fn genErrDecls(o: *Object) !void {
2576 const mod = o.dg.module;
2577 const ip = &mod.intern_pool;
2628 const zcu = o.dg.zcu;
2629 const ip = &zcu.intern_pool;
25782630 const writer = o.writer();
25792631
25802632 var max_name_len: usize = 0;
25812633 // 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) {
25832635 try writer.writeAll("enum {\n");
25842636 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| {
25862638 const name = ip.stringToSlice(name_nts);
25872639 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 = .{
25892641 .ty = .anyerror_type,
25902642 .name = name_nts,
25912643 } });
2592 try o.dg.renderValue(writer, Type.anyerror, Value.fromInterned(err_val), .Other);
2644 try o.dg.renderValue(writer, Value.fromInterned(err_val), .Other);
25932645 try writer.print(" = {d}u,\n", .{value});
25942646 }
25952647 o.indent_writer.popIndent();
......@@ -2601,44 +2653,56 @@ pub fn genErrDecls(o: *Object) !void {
26012653 defer o.dg.gpa.free(name_buf);
26022654
26032655 @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| {
26052657 const name = ip.stringToSlice(name_ip);
26062658 @memcpy(name_buf[name_prefix.len..][0..name.len], name);
26072659 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(.{
26102662 .len = name.len,
26112663 .child = .u8_type,
26122664 .sentinel = .zero_u8,
26132665 });
2614 const name_val = try mod.intern(.{ .aggregate = .{
2666 const name_val = try zcu.intern(.{ .aggregate = .{
26152667 .ty = name_ty.toIntern(),
26162668 .storage = .{ .bytes = name },
26172669 } });
26182670
26192671 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 );
26212680 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);
26232682 try writer.writeAll(";\n");
26242683 }
26252684
2626 const name_array_ty = try mod.arrayType(.{
2627 .len = mod.global_error_set.count(),
2685 const name_array_ty = try zcu.arrayType(.{
2686 .len = zcu.global_error_set.count(),
26282687 .child = .slice_const_u8_sentinel_0_type,
26292688 });
26302689
26312690 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 );
26332699 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| {
26352701 const name = ip.stringToSlice(name_nts);
26362702 if (value != 0) try writer.writeByte(',');
2637
2638 const len_val = try mod.intValue(Type.usize, name.len);
2639
26402703 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),
26422706 });
26432707 }
26442708 try writer.writeAll("};\n");
......@@ -2648,16 +2712,16 @@ fn genExports(o: *Object) !void {
26482712 const tracy = trace(@src());
26492713 defer tracy.end();
26502714
2651 const mod = o.dg.module;
2652 const ip = &mod.intern_pool;
2715 const zcu = o.dg.zcu;
2716 const ip = &zcu.intern_pool;
26532717 const decl_index = switch (o.dg.pass) {
26542718 .decl => |decl| decl,
26552719 .anon, .flush => return,
26562720 };
2657 const decl = mod.declPtr(decl_index);
2721 const decl = zcu.declPtr(decl_index);
26582722 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;
26612725 if (exports.items.len < 2) return;
26622726
26632727 const is_variable_const = switch (ip.indexToKey(decl.val.toIntern())) {
......@@ -2685,7 +2749,7 @@ fn genExports(o: *Object) !void {
26852749 const export_name = ip.stringToSlice(@"export".opts.name);
26862750 try o.dg.renderTypeAndName(
26872751 fwd,
2688 decl.typeOf(mod),
2752 decl.typeOf(zcu),
26892753 .{ .identifier = export_name },
26902754 CQualifiers.init(.{ .@"const" = is_variable_const }),
26912755 decl.alignment,
......@@ -2708,8 +2772,8 @@ fn genExports(o: *Object) !void {
27082772}
27092773
27102774pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {
2711 const mod = o.dg.module;
2712 const ip = &mod.intern_pool;
2775 const zcu = o.dg.zcu;
2776 const ip = &zcu.intern_pool;
27132777 const w = o.writer();
27142778 const key = lazy_fn.key_ptr.*;
27152779 const val = lazy_fn.value_ptr;
......@@ -2727,47 +2791,45 @@ pub fn genLazyFn(o: *Object, lazy_fn: LazyFnMap.Entry) !void {
27272791 try w.writeByte('(');
27282792 try o.dg.renderTypeAndName(w, enum_ty, .{ .identifier = "tag" }, Const, .none, .complete);
27292793 try w.writeAll(") {\n switch (tag) {\n");
2730 const tag_names = enum_ty.enumFields(mod);
2794 const tag_names = enum_ty.enumFields(zcu);
27312795 for (0..tag_names.len) |tag_index| {
27322796 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);
2736
2737 const name_ty = try mod.arrayType(.{
2799 const name_ty = try zcu.arrayType(.{
27382800 .len = tag_name.len,
27392801 .child = .u8_type,
27402802 .sentinel = .zero_u8,
27412803 });
2742 const name_val = try mod.intern(.{ .aggregate = .{
2804 const name_val = try zcu.intern(.{ .aggregate = .{
27432805 .ty = name_ty.toIntern(),
27442806 .storage = .{ .bytes = tag_name },
27452807 } });
2746 const len_val = try mod.intValue(Type.usize, tag_name.len);
27472808
27482809 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),
27502811 });
27512812 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);
27522813 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);
27542815 try w.writeAll(";\n return (");
27552816 try o.dg.renderType(w, name_slice_ty);
27562817 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),
27582820 });
27592821
27602822 try w.writeAll(" }\n");
27612823 }
27622824 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);
27642826 try w.writeAll(") ");
27652827 _ = try airBreakpoint(w);
27662828 try w.writeAll("}\n");
27672829 },
27682830 .never_tail, .never_inline => |fn_decl_index| {
2769 const fn_decl = mod.declPtr(fn_decl_index);
2770 const fn_cty = try o.dg.typeToCType(fn_decl.typeOf(mod), .complete);
2831 const fn_decl = zcu.declPtr(fn_decl_index);
2832 const fn_cty = try o.dg.typeToCType(fn_decl.typeOf(zcu), .complete);
27712833 const fn_info = fn_cty.cast(CType.Payload.Function).?.data;
27722834
27732835 const fwd_decl_writer = o.dg.fwdDeclWriter();
......@@ -2799,10 +2861,10 @@ pub fn genFunc(f: *Function) !void {
27992861 defer tracy.end();
28002862
28012863 const o = &f.object;
2802 const mod = o.dg.module;
2864 const zcu = o.dg.zcu;
28032865 const gpa = o.dg.gpa;
28042866 const decl_index = o.dg.pass.decl;
2805 const decl = mod.declPtr(decl_index);
2867 const decl = zcu.declPtr(decl_index);
28062868
28072869 o.code_header = std.ArrayList(u8).init(gpa);
28082870 defer o.code_header.deinit();
......@@ -2811,7 +2873,7 @@ pub fn genFunc(f: *Function) !void {
28112873 const fwd_decl_writer = o.dg.fwdDeclWriter();
28122874 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|
28152877 if (exports.items[0].opts.linkage == .weak) try fwd_decl_writer.writeAll("zig_weak_linkage_fn ");
28162878 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });
28172879 try fwd_decl_writer.writeAll(";\n");
......@@ -2819,6 +2881,8 @@ pub fn genFunc(f: *Function) !void {
28192881
28202882 try o.indent_writer.insertNewline();
28212883 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)});
28222886 try o.dg.renderFunctionSignature(o.writer(), decl_index, .complete, .{ .export_index = 0 });
28232887 try o.writer().writeByte(' ');
28242888
......@@ -2867,7 +2931,7 @@ pub fn genFunc(f: *Function) !void {
28672931 for (free_locals.values()) |list| {
28682932 for (list.keys()) |local_index| {
28692933 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);
28712935 try w.writeAll(";\n ");
28722936 }
28732937 }
......@@ -2884,43 +2948,41 @@ pub fn genDecl(o: *Object) !void {
28842948 const tracy = trace(@src());
28852949 defer tracy.end();
28862950
2887 const mod = o.dg.module;
2951 const zcu = o.dg.zcu;
28882952 const decl_index = o.dg.pass.decl;
2889 const decl = mod.declPtr(decl_index);
2890 const decl_val = decl.val;
2891 const decl_ty = decl_val.typeOf(mod);
2953 const decl = zcu.declPtr(decl_index);
2954 const decl_ty = decl.typeOf(zcu);
28922955
2893 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return;
2894 if (decl_val.getExternFunc(mod)) |_| {
2956 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return;
2957 if (decl.val.getExternFunc(zcu)) |_| {
28952958 const fwd_decl_writer = o.dg.fwdDeclWriter();
28962959 try fwd_decl_writer.writeAll("zig_extern ");
28972960 try o.dg.renderFunctionSignature(fwd_decl_writer, decl_index, .forward, .{ .export_index = 0 });
28982961 try fwd_decl_writer.writeAll(";\n");
28992962 try genExports(o);
2900 } else if (decl_val.getVariable(mod)) |variable| {
2963 } else if (decl.val.getVariable(zcu)) |variable| {
29012964 try o.dg.renderFwdDecl(decl_index, variable, .final);
29022965 try genExports(o);
29032966
29042967 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);
29072970 const w = o.writer();
29082971 if (!is_global) try w.writeAll("static ");
29092972 if (variable.is_weak_linkage) try w.writeAll("zig_weak_linkage ");
29102973 if (variable.is_threadlocal) try w.writeAll("zig_threadlocal ");
2911 if (mod.intern_pool.stringToSliceUnwrap(decl.@"linksection")) |s|
2912 try w.print("zig_linksection(\"{s}\", ", .{s});
2974 if (zcu.intern_pool.stringToSliceUnwrap(decl.@"linksection")) |s|
2975 try w.print("zig_linksection({s}) ", .{fmtStringLiteral(s, null)});
29132976 const decl_c_value = .{ .decl = decl_index };
29142977 try o.dg.renderTypeAndName(w, decl_ty, decl_c_value, .{}, decl.alignment, .complete);
2915 if (decl.@"linksection" != .none) try w.writeAll(", read, write)");
29162978 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);
29182980 try w.writeByte(';');
29192981 try o.indent_writer.insertNewline();
29202982 } 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);
29222984 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");
29242986 }
29252987}
29262988
......@@ -2930,19 +2992,19 @@ pub fn genDeclValue(
29302992 is_global: bool,
29312993 decl_c_value: CValue,
29322994 alignment: Alignment,
2933 link_section: InternPool.OptionalNullTerminatedString,
2995 @"linksection": InternPool.OptionalNullTerminatedString,
29342996) !void {
2935 const mod = o.dg.module;
2997 const zcu = o.dg.zcu;
29362998 const fwd_decl_writer = o.dg.fwdDeclWriter();
29372999
2938 const ty = val.typeOf(mod);
3000 const ty = val.typeOf(zcu);
29393001
29403002 try fwd_decl_writer.writeAll(if (is_global) "zig_extern " else "static ");
29413003 try o.dg.renderTypeAndName(fwd_decl_writer, ty, decl_c_value, Const, alignment, .complete);
29423004 switch (o.dg.pass) {
29433005 .decl => |decl_index| {
2944 if (mod.decl_exports.get(decl_index)) |exports| {
2945 const export_name = mod.intern_pool.stringToSlice(exports.items[0].opts.name);
3006 if (zcu.decl_exports.get(decl_index)) |exports| {
3007 const export_name = zcu.intern_pool.stringToSlice(exports.items[0].opts.name);
29463008 if (isMangledIdent(export_name, true)) {
29473009 try fwd_decl_writer.print(" zig_mangled_final({ }, {s})", .{
29483010 fmtIdent(export_name), fmtStringLiteral(export_name, null),
......@@ -2958,13 +3020,11 @@ pub fn genDeclValue(
29583020
29593021 const w = o.writer();
29603022 if (!is_global) try w.writeAll("static ");
2961
2962 if (mod.intern_pool.stringToSliceUnwrap(link_section)) |s|
2963 try w.print("zig_linksection(\"{s}\", ", .{s});
3023 if (zcu.intern_pool.stringToSliceUnwrap(@"linksection")) |s|
3024 try w.print("zig_linksection({s}) ", .{fmtStringLiteral(s, null)});
29643025 try o.dg.renderTypeAndName(w, ty, decl_c_value, Const, alignment, .complete);
2965 if (link_section != .none) try w.writeAll(", read)");
29663026 try w.writeAll(" = ");
2967 try o.dg.renderValue(w, ty, val, .StaticInitializer);
3027 try o.dg.renderValue(w, val, .StaticInitializer);
29683028 try w.writeAll(";\n");
29693029}
29703030
......@@ -2972,12 +3032,12 @@ pub fn genHeader(dg: *DeclGen) error{ AnalysisFail, OutOfMemory }!void {
29723032 const tracy = trace(@src());
29733033 defer tracy.end();
29743034
2975 const mod = dg.module;
3035 const zcu = dg.zcu;
29763036 const decl_index = dg.pass.decl;
2977 const decl = mod.declPtr(decl_index);
3037 const decl = zcu.declPtr(decl_index);
29783038 const writer = dg.fwdDeclWriter();
29793039
2980 switch (decl.val.typeOf(mod).zigTypeTag(mod)) {
3040 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
29813041 .Fn => if (dg.declIsGlobal(decl.val)) {
29823042 try writer.writeAll("zig_extern ");
29833043 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
30603120}
30613121
30623122fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfMemory }!void {
3063 const mod = f.object.dg.module;
3064 const ip = &mod.intern_pool;
3123 const zcu = f.object.dg.zcu;
3124 const ip = &zcu.intern_pool;
30653125 const air_tags = f.air.instructions.items(.tag);
30663126
30673127 for (body) |inst| {
......@@ -3096,10 +3156,10 @@ fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail,
30963156 .div_trunc, .div_exact => try airBinOp(f, inst, "/", "div_trunc", .none),
30973157 .rem => blk: {
30983158 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);
31003160 // For binary operations @TypeOf(lhs)==@TypeOf(rhs),
31013161 // so we only check one.
3102 break :blk if (lhs_scalar_ty.isInt(mod))
3162 break :blk if (lhs_scalar_ty.isInt(zcu))
31033163 try airBinOp(f, inst, "%", "rem", .none)
31043164 else
31053165 try airBinFloatOp(f, inst, "fmod");
......@@ -3359,10 +3419,10 @@ fn airSliceField(f: *Function, inst: Air.Inst.Index, is_ptr: bool, field_name: [
33593419}
33603420
33613421fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3362 const mod = f.object.dg.module;
3422 const zcu = f.object.dg.zcu;
33633423 const inst_ty = f.typeOfIndex(inst);
33643424 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3365 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3425 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
33663426 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
33673427 return .none;
33683428 }
......@@ -3385,14 +3445,17 @@ fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
33853445}
33863446
33873447fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3388 const mod = f.object.dg.module;
3448 const zcu = f.object.dg.zcu;
33893449 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
33903450 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
33913451
33923452 const inst_ty = f.typeOfIndex(inst);
33933453 const ptr_ty = f.typeOf(bin_op.lhs);
3394 const elem_ty = ptr_ty.childType(mod);
3395 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(mod);
3454 const ptr_align = ptr_ty.ptrAlignment(zcu);
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
33973460 const ptr = try f.resolveInst(bin_op.lhs);
33983461 const index = try f.resolveInst(bin_op.rhs);
......@@ -3407,13 +3470,22 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
34073470 try f.renderType(writer, inst_ty);
34083471 try writer.writeByte(')');
34093472 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) {
34113474 // It's a pointer to an array, so we need to de-reference.
34123475 try f.writeCValueDeref(writer, ptr);
34133476 } else try f.writeCValue(writer, ptr, .Other);
34143477 if (elem_has_bits) {
34153478 try writer.writeByte('[');
34163479 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 }
34173489 try writer.writeByte(']');
34183490 }
34193491 try a.end(f, writer);
......@@ -3421,10 +3493,10 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
34213493}
34223494
34233495fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3424 const mod = f.object.dg.module;
3496 const zcu = f.object.dg.zcu;
34253497 const inst_ty = f.typeOfIndex(inst);
34263498 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3427 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3499 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
34283500 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
34293501 return .none;
34303502 }
......@@ -3447,14 +3519,14 @@ fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
34473519}
34483520
34493521fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3450 const mod = f.object.dg.module;
3522 const zcu = f.object.dg.zcu;
34513523 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34523524 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34533525
34543526 const inst_ty = f.typeOfIndex(inst);
34553527 const slice_ty = f.typeOf(bin_op.lhs);
3456 const elem_ty = slice_ty.elemType2(mod);
3457 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(mod);
3528 const elem_ty = slice_ty.elemType2(zcu);
3529 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(zcu);
34583530
34593531 const slice = try f.resolveInst(bin_op.lhs);
34603532 const index = try f.resolveInst(bin_op.rhs);
......@@ -3477,10 +3549,10 @@ fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
34773549}
34783550
34793551fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3480 const mod = f.object.dg.module;
3552 const zcu = f.object.dg.zcu;
34813553 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34823554 const inst_ty = f.typeOfIndex(inst);
3483 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3555 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
34843556 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
34853557 return .none;
34863558 }
......@@ -3503,33 +3575,33 @@ fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
35033575}
35043576
35053577fn airAlloc(f: *Function, inst: Air.Inst.Index) !CValue {
3506 const mod = f.object.dg.module;
3578 const zcu = f.object.dg.zcu;
35073579 const inst_ty = f.typeOfIndex(inst);
3508 const elem_type = inst_ty.childType(mod);
3509 if (!elem_type.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .{ .undef = inst_ty };
3580 const elem_type = inst_ty.childType(zcu);
3581 if (!elem_type.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
35103582
35113583 const local = try f.allocLocalValue(
35123584 elem_type,
3513 inst_ty.ptrAlignment(mod),
3585 inst_ty.ptrAlignment(zcu),
35143586 );
35153587 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;
35173589 try f.allocs.put(gpa, local.new_local, true);
35183590 return .{ .local_ref = local.new_local };
35193591}
35203592
35213593fn airRetPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3522 const mod = f.object.dg.module;
3594 const zcu = f.object.dg.zcu;
35233595 const inst_ty = f.typeOfIndex(inst);
3524 const elem_ty = inst_ty.childType(mod);
3525 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .{ .undef = inst_ty };
3596 const elem_ty = inst_ty.childType(zcu);
3597 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
35263598
35273599 const local = try f.allocLocalValue(
35283600 elem_ty,
3529 inst_ty.ptrAlignment(mod),
3601 inst_ty.ptrAlignment(zcu),
35303602 );
35313603 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;
35333605 try f.allocs.put(gpa, local.new_local, true);
35343606 return .{ .local_ref = local.new_local };
35353607}
......@@ -3559,15 +3631,15 @@ fn airArg(f: *Function, inst: Air.Inst.Index) !CValue {
35593631}
35603632
35613633fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3562 const mod = f.object.dg.module;
3634 const zcu = f.object.dg.zcu;
35633635 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35643636
35653637 const ptr_ty = f.typeOf(ty_op.operand);
3566 const ptr_scalar_ty = ptr_ty.scalarType(mod);
3567 const ptr_info = ptr_scalar_ty.ptrInfo(mod);
3638 const ptr_scalar_ty = ptr_ty.scalarType(zcu);
3639 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
35683640 const src_ty = Type.fromInterned(ptr_info.child);
35693641
3570 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3642 if (!src_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
35713643 try reap(f, inst, &.{ty_op.operand});
35723644 return .none;
35733645 }
......@@ -3577,10 +3649,10 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
35773649 try reap(f, inst, &.{ty_op.operand});
35783650
35793651 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))
35813653 else
35823654 true;
3583 const is_array = lowersToArray(src_ty, mod);
3655 const is_array = lowersToArray(src_ty, zcu);
35843656 const need_memcpy = !is_aligned or is_array;
35853657
35863658 const writer = f.object.writer();
......@@ -3600,12 +3672,12 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36003672 try writer.writeAll("))");
36013673 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
36023674 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));
3606 const bit_offset_val = try mod.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3677 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
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
36103682 try f.writeCValue(writer, local, .Other);
36113683 try v.elem(f, writer);
......@@ -3616,9 +3688,9 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36163688 try writer.writeAll("((");
36173689 try f.renderType(writer, field_ty);
36183690 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;
36203692 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", .{});
36223694 try writer.writeAll("zig_lo_");
36233695 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
36243696 try writer.writeByte('(');
......@@ -3628,7 +3700,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36283700 try writer.writeByte('(');
36293701 try f.writeCValueDeref(writer, operand);
36303702 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)});
36323704 if (cant_cast) try writer.writeByte(')');
36333705 try f.object.dg.renderBuiltinInfo(writer, field_ty, .bits);
36343706 try writer.writeByte(')');
......@@ -3646,22 +3718,22 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36463718}
36473719
36483720fn 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;
36503722 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
36513723 const writer = f.object.writer();
36523724 const op_inst = un_op.toIndex();
36533725 const op_ty = f.typeOf(un_op);
3654 const ret_ty = if (is_ptr) op_ty.childType(mod) else op_ty;
3655 const lowered_ret_ty = try lowerFnRetTy(ret_ty, mod);
3726 const ret_ty = if (is_ptr) op_ty.childType(zcu) else op_ty;
3727 const lowered_ret_ty = try lowerFnRetTy(ret_ty, zcu);
36563728
36573729 if (op_inst != null and f.air.instructions.items(.tag)[@intFromEnum(op_inst.?)] == .call_always_tail) {
36583730 try reap(f, inst, &.{un_op});
36593731 _ = try airCall(f, op_inst.?, .always_tail);
3660 } else if (lowered_ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3732 } else if (lowered_ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
36613733 const operand = try f.resolveInst(un_op);
36623734 try reap(f, inst, &.{un_op});
36633735 var deref = is_ptr;
3664 const is_array = lowersToArray(ret_ty, mod);
3736 const is_array = lowersToArray(ret_ty, zcu);
36653737 const ret_val = if (is_array) ret_val: {
36663738 const array_local = try f.allocLocal(inst, lowered_ret_ty);
36673739 try writer.writeAll("memcpy(");
......@@ -3696,16 +3768,16 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
36963768}
36973769
36983770fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
3699 const mod = f.object.dg.module;
3771 const zcu = f.object.dg.zcu;
37003772 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37013773
37023774 const operand = try f.resolveInst(ty_op.operand);
37033775 try reap(f, inst, &.{ty_op.operand});
37043776
37053777 const inst_ty = f.typeOfIndex(inst);
3706 const inst_scalar_ty = inst_ty.scalarType(mod);
3778 const inst_scalar_ty = inst_ty.scalarType(zcu);
37073779 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
37103782 const writer = f.object.writer();
37113783 const local = try f.allocLocal(inst, inst_ty);
......@@ -3722,20 +3794,20 @@ fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
37223794}
37233795
37243796fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3725 const mod = f.object.dg.module;
3797 const zcu = f.object.dg.zcu;
37263798 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37273799
37283800 const operand = try f.resolveInst(ty_op.operand);
37293801 try reap(f, inst, &.{ty_op.operand});
37303802 const inst_ty = f.typeOfIndex(inst);
3731 const inst_scalar_ty = inst_ty.scalarType(mod);
3732 const dest_int_info = inst_scalar_ty.intInfo(mod);
3803 const inst_scalar_ty = inst_ty.scalarType(zcu);
3804 const dest_int_info = inst_scalar_ty.intInfo(zcu);
37333805 const dest_bits = dest_int_info.bits;
37343806 const dest_c_bits = toCIntBits(dest_int_info.bits) orelse
37353807 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
37363808 const operand_ty = f.typeOf(ty_op.operand);
3737 const scalar_ty = operand_ty.scalarType(mod);
3738 const scalar_int_info = scalar_ty.intInfo(mod);
3809 const scalar_ty = operand_ty.scalarType(zcu);
3810 const scalar_int_info = scalar_ty.intInfo(zcu);
37393811
37403812 const writer = f.object.writer();
37413813 const local = try f.allocLocal(inst, inst_ty);
......@@ -3763,18 +3835,19 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
37633835 try v.elem(f, writer);
37643836 } else switch (dest_int_info.signedness) {
37653837 .unsigned => {
3766 const mask_val = try inst_scalar_ty.maxIntScalar(mod, scalar_ty);
37673838 try writer.writeAll("zig_and_");
37683839 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
37693840 try writer.writeByte('(');
37703841 try f.writeCValue(writer, operand, .FunctionArgument);
37713842 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 });
37733846 },
37743847 .signed => {
37753848 const c_bits = toCIntBits(scalar_int_info.bits) orelse
37763849 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
37793852 try writer.writeAll("zig_shr_");
37803853 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
......@@ -3792,9 +3865,9 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
37923865 try f.writeCValue(writer, operand, .FunctionArgument);
37933866 try v.elem(f, writer);
37943867 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)});
37963869 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)});
37983871 },
37993872 }
38003873
......@@ -3821,18 +3894,18 @@ fn airIntFromBool(f: *Function, inst: Air.Inst.Index) !CValue {
38213894}
38223895
38233896fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3824 const mod = f.object.dg.module;
3897 const zcu = f.object.dg.zcu;
38253898 // *a = b;
38263899 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38273900
38283901 const ptr_ty = f.typeOf(bin_op.lhs);
3829 const ptr_scalar_ty = ptr_ty.scalarType(mod);
3830 const ptr_info = ptr_scalar_ty.ptrInfo(mod);
3902 const ptr_scalar_ty = ptr_ty.scalarType(zcu);
3903 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
38313904
38323905 const ptr_val = try f.resolveInst(bin_op.lhs);
38333906 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
38373910 if (val_is_undef) {
38383911 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 {
38483921 }
38493922
38503923 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))
38523925 else
38533926 true;
3854 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), mod);
3927 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), zcu);
38553928 const need_memcpy = !is_aligned or is_array;
38563929
38573930 const src_val = try f.resolveInst(bin_op.rhs);
......@@ -3863,7 +3936,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38633936 if (need_memcpy) {
38643937 // For this memcpy to safely work we need the rhs to have the same
38653938 // 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
38683941 // If the source is a constant, writeCValue will emit a brace initialization
38693942 // so work around this by initializing into new local.
......@@ -3893,12 +3966,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38933966 }
38943967 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
38953968 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));
3899 const bit_offset_val = try mod.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3971 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
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
39033976 const ExpectedContents = [BigInt.Managed.default_capacity]BigIntLimb;
39043977 var stack align(@alignOf(ExpectedContents)) =
......@@ -3911,7 +3984,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39113984 try mask.shiftLeft(&mask, ptr_info.packed_offset.bit_offset);
39123985 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
39163989 try f.writeCValueDeref(writer, ptr_val);
39173990 try v.elem(f, writer);
......@@ -3922,12 +3995,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39223995 try writer.writeByte('(');
39233996 try f.writeCValueDeref(writer, ptr_val);
39243997 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)});
39263999 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39274000 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;
39294002 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", .{});
39314004 try writer.writeAll("zig_make_");
39324005 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39334006 try writer.writeAll("(0, ");
......@@ -3937,7 +4010,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39374010 try writer.writeByte(')');
39384011 }
39394012
3940 if (src_ty.isPtrAtRuntime(mod)) {
4013 if (src_ty.isPtrAtRuntime(zcu)) {
39414014 try writer.writeByte('(');
39424015 try f.renderType(writer, Type.usize);
39434016 try writer.writeByte(')');
......@@ -3945,7 +4018,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39454018 try f.writeCValue(writer, src_val, .Other);
39464019 try v.elem(f, writer);
39474020 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)});
39494022 } else {
39504023 try f.writeCValueDeref(writer, ptr_val);
39514024 try v.elem(f, writer);
......@@ -3960,7 +4033,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39604033}
39614034
39624035fn 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;
39644037 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39654038 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:
39704043
39714044 const inst_ty = f.typeOfIndex(inst);
39724045 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
39754048 const w = f.object.writer();
39764049 const local = try f.allocLocal(inst, inst_ty);
......@@ -3998,11 +4071,11 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:
39984071}
39994072
40004073fn airNot(f: *Function, inst: Air.Inst.Index) !CValue {
4001 const mod = f.object.dg.module;
4074 const zcu = f.object.dg.zcu;
40024075 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
40034076 const operand_ty = f.typeOf(ty_op.operand);
4004 const scalar_ty = operand_ty.scalarType(mod);
4005 if (scalar_ty.ip_index != .bool_type) return try airUnBuiltinCall(f, inst, "not", .bits);
4077 const scalar_ty = operand_ty.scalarType(zcu);
4078 if (scalar_ty.toIntern() != .bool_type) return try airUnBuiltinCall(f, inst, "not", .bits);
40064079
40074080 const op = try f.resolveInst(ty_op.operand);
40084081 try reap(f, inst, &.{ty_op.operand});
......@@ -4031,11 +4104,11 @@ fn airBinOp(
40314104 operation: []const u8,
40324105 info: BuiltinInfo,
40334106) !CValue {
4034 const mod = f.object.dg.module;
4107 const zcu = f.object.dg.zcu;
40354108 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
40364109 const operand_ty = f.typeOf(bin_op.lhs);
4037 const scalar_ty = operand_ty.scalarType(mod);
4038 if ((scalar_ty.isInt(mod) and scalar_ty.bitSize(mod) > 64) or scalar_ty.isRuntimeFloat())
4110 const scalar_ty = operand_ty.scalarType(zcu);
4111 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(zcu) > 64) or scalar_ty.isRuntimeFloat())
40394112 return try airBinBuiltinCall(f, inst, operation, info);
40404113
40414114 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -4069,12 +4142,12 @@ fn airCmpOp(
40694142 data: anytype,
40704143 operator: std.math.CompareOperator,
40714144) !CValue {
4072 const mod = f.object.dg.module;
4145 const zcu = f.object.dg.zcu;
40734146 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);
4077 if (scalar_ty.isInt(mod) and scalar_bits > 64)
4149 const scalar_bits = scalar_ty.bitSize(zcu);
4150 if (scalar_ty.isInt(zcu) and scalar_bits > 64)
40784151 return airCmpBuiltinCall(
40794152 f,
40804153 inst,
......@@ -4092,7 +4165,7 @@ fn airCmpOp(
40924165 try reap(f, inst, &.{ data.lhs, data.rhs });
40934166
40944167 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);
40964169 const writer = f.object.writer();
40974170 const local = try f.allocLocal(inst, inst_ty);
40984171 const v = try Vectorize.start(f, inst, writer, lhs_ty);
......@@ -4117,12 +4190,12 @@ fn airEquality(
41174190 inst: Air.Inst.Index,
41184191 operator: std.math.CompareOperator,
41194192) !CValue {
4120 const mod = f.object.dg.module;
4193 const zcu = f.object.dg.zcu;
41214194 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
41224195
41234196 const operand_ty = f.typeOf(bin_op.lhs);
4124 const operand_bits = operand_ty.bitSize(mod);
4125 if (operand_ty.isInt(mod) and operand_bits > 64)
4197 const operand_bits = operand_ty.bitSize(zcu);
4198 if (operand_ty.isInt(zcu) and operand_bits > 64)
41264199 return airCmpBuiltinCall(
41274200 f,
41284201 inst,
......@@ -4145,7 +4218,7 @@ fn airEquality(
41454218 try f.writeCValue(writer, local, .Other);
41464219 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)) {
41494222 try f.writeCValueMember(writer, lhs, .{ .identifier = "is_null" });
41504223 try writer.writeAll(" || ");
41514224 try f.writeCValueMember(writer, rhs, .{ .identifier = "is_null" });
......@@ -4184,7 +4257,7 @@ fn airCmpLtErrorsLen(f: *Function, inst: Air.Inst.Index) !CValue {
41844257}
41854258
41864259fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4187 const mod = f.object.dg.module;
4260 const zcu = f.object.dg.zcu;
41884261 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
41894262 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 {
41934266 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
41944267
41954268 const inst_ty = f.typeOfIndex(inst);
4196 const inst_scalar_ty = inst_ty.scalarType(mod);
4197 const elem_ty = inst_scalar_ty.elemType2(mod);
4269 const inst_scalar_ty = inst_ty.scalarType(zcu);
4270 const elem_ty = inst_scalar_ty.elemType2(zcu);
41984271
41994272 const local = try f.allocLocal(inst, inst_ty);
42004273 const writer = f.object.writer();
......@@ -4203,7 +4276,7 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42034276 try v.elem(f, writer);
42044277 try writer.writeAll(" = ");
42054278
4206 if (elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4279 if (elem_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
42074280 // We must convert to and from integer types to prevent UB if the operation
42084281 // results in a NULL pointer, or if LHS is NULL. The operation is only UB
42094282 // if the result is NULL and then dereferenced.
......@@ -4232,13 +4305,13 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42324305}
42334306
42344307fn 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;
42364309 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
42374310
42384311 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)
42424315 return try airBinBuiltinCall(f, inst, operation[1..], .none);
42434316 if (inst_scalar_ty.isRuntimeFloat())
42444317 return try airBinFloatOp(f, inst, operation);
......@@ -4274,7 +4347,7 @@ fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []cons
42744347}
42754348
42764349fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4277 const mod = f.object.dg.module;
4350 const zcu = f.object.dg.zcu;
42784351 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
42794352 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 {
42834356 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
42844357
42854358 const inst_ty = f.typeOfIndex(inst);
4286 const ptr_ty = inst_ty.slicePtrFieldType(mod);
4359 const ptr_ty = inst_ty.slicePtrFieldType(zcu);
42874360
42884361 const writer = f.object.writer();
42894362 const local = try f.allocLocal(inst, inst_ty);
......@@ -4291,9 +4364,6 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
42914364 const a = try Assignment.start(f, writer, ptr_ty);
42924365 try f.writeCValueMember(writer, local, .{ .identifier = "ptr" });
42934366 try a.assign(f, writer);
4294 try writer.writeByte('(');
4295 try f.renderType(writer, ptr_ty);
4296 try writer.writeByte(')');
42974367 try f.writeCValue(writer, ptr, .Other);
42984368 try a.end(f, writer);
42994369 }
......@@ -4301,7 +4371,7 @@ fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
43014371 const a = try Assignment.start(f, writer, Type.usize);
43024372 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
43034373 try a.assign(f, writer);
4304 try f.writeCValue(writer, len, .Other);
4374 try f.writeCValue(writer, len, .Initializer);
43054375 try a.end(f, writer);
43064376 }
43074377 return local;
......@@ -4312,7 +4382,7 @@ fn airCall(
43124382 inst: Air.Inst.Index,
43134383 modifier: std.builtin.CallModifier,
43144384) !CValue {
4315 const mod = f.object.dg.module;
4385 const zcu = f.object.dg.zcu;
43164386 // Not even allowed to call panic in a naked function.
43174387 if (f.object.dg.is_naked_fn) return .none;
43184388
......@@ -4334,7 +4404,7 @@ fn airCall(
43344404 }
43354405 resolved_arg.* = try f.resolveInst(arg);
43364406 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
43394409 const array_local = try f.allocLocal(inst, lowered_arg_ty);
43404410 try writer.writeAll("memcpy(");
......@@ -4357,20 +4427,19 @@ fn airCall(
43574427 }
43584428
43594429 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)) {
43614431 .Fn => callee_ty,
4362 .Pointer => callee_ty.childType(mod),
4432 .Pointer => callee_ty.childType(zcu),
43634433 else => unreachable,
4364 };
4365
4366 const ret_ty = fn_ty.fnReturnType(mod);
4367 const lowered_ret_ty = try lowerFnRetTy(ret_ty, mod);
4434 }).?;
4435 const ret_ty = Type.fromInterned(fn_info.return_type);
4436 const lowered_ret_ty = try lowerFnRetTy(ret_ty, zcu);
43684437
43694438 const result_local = result: {
43704439 if (modifier == .always_tail) {
43714440 try writer.writeAll("zig_always_tail return ");
43724441 break :result .none;
4373 } else if (!lowered_ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4442 } else if (!lowered_ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
43744443 break :result .none;
43754444 } else if (f.liveness.isUnused(inst)) {
43764445 try writer.writeByte('(');
......@@ -4388,8 +4457,8 @@ fn airCall(
43884457 callee: {
43894458 known: {
43904459 const fn_decl = fn_decl: {
4391 const callee_val = (try f.air.value(pl_op.operand, mod)) orelse break :known;
4392 break :fn_decl switch (mod.intern_pool.indexToKey(callee_val.ip_index)) {
4460 const callee_val = (try f.air.value(pl_op.operand, zcu)) orelse break :known;
4461 break :fn_decl switch (zcu.intern_pool.indexToKey(callee_val.toIntern())) {
43934462 .extern_func => |extern_func| extern_func.decl,
43944463 .func => |func| func.owner_decl,
43954464 .ptr => |ptr| switch (ptr.addr) {
......@@ -4420,18 +4489,21 @@ fn airCall(
44204489 }
44214490
44224491 try writer.writeByte('(');
4423 var args_written: usize = 0;
4492 var need_comma = false;
44244493 for (resolved_args) |resolved_arg| {
44254494 if (resolved_arg == .none) continue;
4426 if (args_written != 0) try writer.writeAll(", ");
4495 if (need_comma) try writer.writeAll(", ");
4496 need_comma = true;
44274497 try f.writeCValue(writer, resolved_arg, .FunctionArgument);
4428 if (resolved_arg == .new_local) try freeLocal(f, inst, resolved_arg.new_local, null);
4429 args_written += 1;
4498 switch (resolved_arg) {
4499 .new_local => |local| try freeLocal(f, inst, local, null),
4500 else => {},
4501 }
44304502 }
44314503 try writer.writeAll(");\n");
44324504
44334505 const result = result: {
4434 if (result_local == .none or !lowersToArray(ret_ty, mod))
4506 if (result_local == .none or !lowersToArray(ret_ty, zcu))
44354507 break :result result_local;
44364508
44374509 const array_local = try f.allocLocal(inst, ret_ty);
......@@ -4465,22 +4537,22 @@ fn airDbgStmt(f: *Function, inst: Air.Inst.Index) !CValue {
44654537}
44664538
44674539fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
4468 const mod = f.object.dg.module;
4540 const zcu = f.object.dg.zcu;
44694541 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
44704542 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);
44724544 const writer = f.object.writer();
44734545 try writer.writeAll("/* ");
4474 try owner_decl.renderFullyQualifiedName(mod, writer);
4546 try owner_decl.renderFullyQualifiedName(zcu, writer);
44754547 try writer.writeAll(" */ ");
44764548 return lowerBlock(f, inst, @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]));
44774549}
44784550
44794551fn airDbgVar(f: *Function, inst: Air.Inst.Index) !CValue {
4480 const mod = f.object.dg.module;
4552 const zcu = f.object.dg.zcu;
44814553 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
44824554 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;
44844556 if (!operand_is_undef) _ = try f.resolveInst(pl_op.operand);
44854557
44864558 try reap(f, inst, &.{pl_op.operand});
......@@ -4496,7 +4568,7 @@ fn airBlock(f: *Function, inst: Air.Inst.Index) !CValue {
44964568}
44974569
44984570fn 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;
45004572 const liveness_block = f.liveness.getBlock(inst);
45014573
45024574 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)
45044576 const writer = f.object.writer();
45054577
45064578 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))
45084580 try f.allocLocal(inst, inst_ty)
45094581 else
45104582 .none;
......@@ -4526,7 +4598,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)
45264598 try f.object.indent_writer.insertNewline();
45274599
45284600 // 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)) {
45304602 // label must be followed by an expression, include an empty one.
45314603 try writer.print("zig_block_{d}:;\n", .{block_id});
45324604 }
......@@ -4543,11 +4615,11 @@ fn airTry(f: *Function, inst: Air.Inst.Index) !CValue {
45434615}
45444616
45454617fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {
4546 const mod = f.object.dg.module;
4618 const zcu = f.object.dg.zcu;
45474619 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
45484620 const extra = f.air.extraData(Air.TryPtr, ty_pl.payload);
45494621 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);
45514623 return lowerTry(f, inst, extra.data.ptr, body, err_union_ty, true);
45524624}
45534625
......@@ -4559,15 +4631,15 @@ fn lowerTry(
45594631 err_union_ty: Type,
45604632 is_ptr: bool,
45614633) !CValue {
4562 const mod = f.object.dg.module;
4634 const zcu = f.object.dg.zcu;
45634635 const err_union = try f.resolveInst(operand);
45644636 const inst_ty = f.typeOfIndex(inst);
45654637 const liveness_condbr = f.liveness.getCondBr(inst);
45664638 const writer = f.object.writer();
4567 const payload_ty = err_union_ty.errorUnionPayload(mod);
4568 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod);
4639 const payload_ty = err_union_ty.errorUnionPayload(zcu);
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)) {
45714643 try writer.writeAll("if (");
45724644 if (!payload_has_bits) {
45734645 if (is_ptr)
......@@ -4661,7 +4733,7 @@ const LocalResult = struct {
46614733 need_free: bool,
46624734
46634735 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
46664738 if (lr.need_free) {
46674739 // Move the freshly allocated local to be owned by this instruction,
......@@ -4673,7 +4745,7 @@ const LocalResult = struct {
46734745 try lr.free(f);
46744746 const writer = f.object.writer();
46754747 try f.writeCValue(writer, local, .Other);
4676 if (dest_ty.isAbiInt(mod)) {
4748 if (dest_ty.isAbiInt(zcu)) {
46774749 try writer.writeAll(" = ");
46784750 } else {
46794751 try writer.writeAll(" = (");
......@@ -4693,13 +4765,13 @@ const LocalResult = struct {
46934765};
46944766
46954767fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !LocalResult {
4696 const mod = f.object.dg.module;
4697 const target = mod.getTarget();
4768 const zcu = f.object.dg.zcu;
4769 const target = &f.object.dg.mod.resolved_target.result;
46984770 const writer = f.object.writer();
46994771
4700 if (operand_ty.isAbiInt(mod) and dest_ty.isAbiInt(mod)) {
4701 const src_info = dest_ty.intInfo(mod);
4702 const dest_info = operand_ty.intInfo(mod);
4772 if (operand_ty.isAbiInt(zcu) and dest_ty.isAbiInt(zcu)) {
4773 const src_info = dest_ty.intInfo(zcu);
4774 const dest_info = operand_ty.intInfo(zcu);
47034775 if (src_info.signedness == dest_info.signedness and
47044776 src_info.bits == dest_info.bits)
47054777 {
......@@ -4710,7 +4782,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
47104782 }
47114783 }
47124784
4713 if (dest_ty.isPtrAtRuntime(mod) and operand_ty.isPtrAtRuntime(mod)) {
4785 if (dest_ty.isPtrAtRuntime(zcu) and operand_ty.isPtrAtRuntime(zcu)) {
47144786 const local = try f.allocLocal(null, dest_ty);
47154787 try f.writeCValue(writer, local, .Other);
47164788 try writer.writeAll(" = (");
......@@ -4727,7 +4799,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
47274799 const operand_lval = if (operand == .constant) blk: {
47284800 const operand_local = try f.allocLocal(null, operand_ty);
47294801 try f.writeCValue(writer, operand_local, .Other);
4730 if (operand_ty.isAbiInt(mod)) {
4802 if (operand_ty.isAbiInt(zcu)) {
47314803 try writer.writeAll(" = ");
47324804 } else {
47334805 try writer.writeAll(" = (");
......@@ -4747,14 +4819,14 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
47474819 try writer.writeAll(", sizeof(");
47484820 try f.renderType(
47494821 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,
47514823 );
47524824 try writer.writeAll("));\n");
47534825
47544826 // Ensure padding bits have the expected value.
4755 if (dest_ty.isAbiInt(mod)) {
4827 if (dest_ty.isAbiInt(zcu)) {
47564828 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);
47584830 var bits: u16 = dest_info.bits;
47594831 var wrap_cty: ?CType = null;
47604832 var need_bitcasts = false;
......@@ -4779,7 +4851,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !Loca
47794851 try writer.writeByte('(');
47804852 }
47814853 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);
47834855 if (wrap_cty) |cty|
47844856 try f.object.dg.renderCTypeForBuiltinFnName(writer, cty)
47854857 else
......@@ -4912,7 +4984,7 @@ fn airCondBr(f: *Function, inst: Air.Inst.Index) !CValue {
49124984}
49134985
49144986fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4915 const mod = f.object.dg.module;
4987 const zcu = f.object.dg.zcu;
49164988 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
49174989 const condition = try f.resolveInst(pl_op.operand);
49184990 try reap(f, inst, &.{pl_op.operand});
......@@ -4921,11 +4993,11 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
49214993 const writer = f.object.writer();
49224994
49234995 try writer.writeAll("switch (");
4924 if (condition_ty.zigTypeTag(mod) == .Bool) {
4996 if (condition_ty.zigTypeTag(zcu) == .Bool) {
49254997 try writer.writeByte('(');
49264998 try f.renderType(writer, Type.u1);
49274999 try writer.writeByte(')');
4928 } else if (condition_ty.isPtrAtRuntime(mod)) {
5000 } else if (condition_ty.isPtrAtRuntime(zcu)) {
49295001 try writer.writeByte('(');
49305002 try f.renderType(writer, Type.usize);
49315003 try writer.writeByte(')');
......@@ -4952,12 +5024,12 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
49525024 for (items) |item| {
49535025 try f.object.indent_writer.insertNewline();
49545026 try writer.writeAll("case ");
4955 if (condition_ty.isPtrAtRuntime(mod)) {
5027 if (condition_ty.isPtrAtRuntime(zcu)) {
49565028 try writer.writeByte('(');
49575029 try f.renderType(writer, Type.usize);
49585030 try writer.writeByte(')');
49595031 }
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);
49615033 try writer.writeByte(':');
49625034 }
49635035 try writer.writeByte(' ');
......@@ -4994,13 +5066,13 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
49945066}
49955067
49965068fn 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;
49985070 return switch (constraint[0]) {
49995071 '{' => true,
50005072 'i', 'r' => false,
50015073 'I' => !target.cpu.arch.isArmOrThumb(),
50025074 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())) {
50045076 .ptr => |ptr| switch (ptr.addr) {
50055077 .decl => false,
50065078 else => true,
......@@ -5013,7 +5085,7 @@ fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool
50135085}
50145086
50155087fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
5016 const mod = f.object.dg.module;
5088 const zcu = f.object.dg.zcu;
50175089 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
50185090 const extra = f.air.extraData(Air.Asm, ty_pl.payload);
50195091 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;
......@@ -5028,7 +5100,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50285100 const result = result: {
50295101 const writer = f.object.writer();
50305102 const inst_ty = f.typeOfIndex(inst);
5031 const local = if (inst_ty.hasRuntimeBitsIgnoreComptime(mod)) local: {
5103 const local = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) local: {
50325104 const local = try f.allocLocal(inst, inst_ty);
50335105 if (f.wantSafety()) {
50345106 try f.writeCValue(writer, local, .Other);
......@@ -5057,7 +5129,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50575129
50585130 const is_reg = constraint[1] == '{';
50595131 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);
50615133 try writer.writeAll("register ");
50625134 const alignment: Alignment = .none;
50635135 const local_value = try f.allocLocalValue(output_ty, alignment);
......@@ -5275,7 +5347,7 @@ fn airIsNull(
52755347 operator: []const u8,
52765348 is_ptr: bool,
52775349) !CValue {
5278 const mod = f.object.dg.module;
5350 const zcu = f.object.dg.zcu;
52795351 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
52805352
52815353 const writer = f.object.writer();
......@@ -5292,22 +5364,22 @@ fn airIsNull(
52925364 }
52935365
52945366 const operand_ty = f.typeOf(un_op);
5295 const optional_ty = if (is_ptr) operand_ty.childType(mod) else operand_ty;
5296 const payload_ty = optional_ty.optionalChild(mod);
5297 const err_int_ty = try mod.errorIntType();
5367 const optional_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
5368 const payload_ty = optional_ty.optionalChild(zcu);
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))
53005372 Value.true
5301 else if (optional_ty.isPtrLikeOptional(mod))
5373 else if (optional_ty.isPtrLikeOptional(zcu))
53025374 // operand is a regular pointer, test `operand !=/== NULL`
5303 try mod.getCoerced(Value.null, optional_ty)
5304 else if (payload_ty.zigTypeTag(mod) == .ErrorSet)
5305 try mod.intValue(err_int_ty, 0)
5306 else if (payload_ty.isSlice(mod) and optional_ty.optionalReprIsPayload(mod)) rhs: {
5375 try zcu.getCoerced(Value.null, optional_ty)
5376 else if (payload_ty.zigTypeTag(zcu) == .ErrorSet)
5377 try zcu.intValue(err_int_ty, 0)
5378 else if (payload_ty.isSlice(zcu) and optional_ty.optionalReprIsPayload(zcu)) rhs: {
53075379 try writer.writeAll(".ptr");
5308 const slice_ptr_ty = payload_ty.slicePtrFieldType(mod);
5309 const opt_slice_ptr_ty = try mod.optionalType(slice_ptr_ty.toIntern());
5310 break :rhs try mod.nullValue(opt_slice_ptr_ty);
5380 const slice_ptr_ty = payload_ty.slicePtrFieldType(zcu);
5381 const opt_slice_ptr_ty = try zcu.optionalType(slice_ptr_ty.toIntern());
5382 break :rhs try zcu.nullValue(opt_slice_ptr_ty);
53115383 } else rhs: {
53125384 try writer.writeAll(".is_null");
53135385 break :rhs Value.true;
......@@ -5315,22 +5387,22 @@ fn airIsNull(
53155387 try writer.writeByte(' ');
53165388 try writer.writeAll(operator);
53175389 try writer.writeByte(' ');
5318 try f.object.dg.renderValue(writer, rhs.typeOf(mod), rhs, .Other);
5390 try f.object.dg.renderValue(writer, rhs, .Other);
53195391 try writer.writeAll(";\n");
53205392 return local;
53215393}
53225394
53235395fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
5324 const mod = f.object.dg.module;
5396 const zcu = f.object.dg.zcu;
53255397 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53265398
53275399 const operand = try f.resolveInst(ty_op.operand);
53285400 try reap(f, inst, &.{ty_op.operand});
53295401 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)) {
53345406 return .none;
53355407 }
53365408
......@@ -5338,7 +5410,7 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
53385410 const writer = f.object.writer();
53395411 const local = try f.allocLocal(inst, inst_ty);
53405412
5341 if (opt_ty.optionalReprIsPayload(mod)) {
5413 if (opt_ty.optionalReprIsPayload(zcu)) {
53425414 try f.writeCValue(writer, local, .Other);
53435415 try writer.writeAll(" = ");
53445416 try f.writeCValue(writer, operand, .Other);
......@@ -5355,24 +5427,24 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index) !CValue {
53555427}
53565428
53575429fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5358 const mod = f.object.dg.module;
5430 const zcu = f.object.dg.zcu;
53595431 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53605432
53615433 const writer = f.object.writer();
53625434 const operand = try f.resolveInst(ty_op.operand);
53635435 try reap(f, inst, &.{ty_op.operand});
53645436 const ptr_ty = f.typeOf(ty_op.operand);
5365 const opt_ty = ptr_ty.childType(mod);
5437 const opt_ty = ptr_ty.childType(zcu);
53665438 const inst_ty = f.typeOfIndex(inst);
53675439
5368 if (!inst_ty.childType(mod).hasRuntimeBitsIgnoreComptime(mod)) {
5440 if (!inst_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu)) {
53695441 return .{ .undef = inst_ty };
53705442 }
53715443
53725444 const local = try f.allocLocal(inst, inst_ty);
53735445 try f.writeCValue(writer, local, .Other);
53745446
5375 if (opt_ty.optionalReprIsPayload(mod)) {
5447 if (opt_ty.optionalReprIsPayload(zcu)) {
53765448 // the operand is just a regular pointer, no need to do anything special.
53775449 // *?*T -> **T and ?*T -> *T are **T -> **T and *T -> *T in C
53785450 try writer.writeAll(" = ");
......@@ -5386,18 +5458,18 @@ fn airOptionalPayloadPtr(f: *Function, inst: Air.Inst.Index) !CValue {
53865458}
53875459
53885460fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5389 const mod = f.object.dg.module;
5461 const zcu = f.object.dg.zcu;
53905462 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53915463 const writer = f.object.writer();
53925464 const operand = try f.resolveInst(ty_op.operand);
53935465 try reap(f, inst, &.{ty_op.operand});
53945466 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
53985470 const inst_ty = f.typeOfIndex(inst);
53995471
5400 if (opt_ty.optionalReprIsPayload(mod)) {
5472 if (opt_ty.optionalReprIsPayload(zcu)) {
54015473 if (f.liveness.isUnused(inst)) {
54025474 return .none;
54035475 }
......@@ -5412,7 +5484,7 @@ fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
54125484 } else {
54135485 try f.writeCValueDeref(writer, operand);
54145486 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);
54165488 try writer.writeAll(";\n");
54175489
54185490 if (f.liveness.isUnused(inst)) {
......@@ -5432,50 +5504,50 @@ fn fieldLocation(
54325504 container_ptr_ty: Type,
54335505 field_ptr_ty: Type,
54345506 field_index: u32,
5435 mod: *Module,
5507 zcu: *Zcu,
54365508) union(enum) {
54375509 begin: void,
54385510 field: CValue,
54395511 byte_offset: u32,
54405512 end: void,
54415513} {
5442 const ip = &mod.intern_pool;
5443 const container_ty = container_ptr_ty.childType(mod);
5444 return switch (container_ty.zigTypeTag(mod)) {
5514 const ip = &zcu.intern_pool;
5515 const container_ty = container_ptr_ty.childType(zcu);
5516 return switch (container_ty.zigTypeTag(zcu)) {
54455517 .Struct => blk: {
5446 if (mod.typeToPackedStruct(container_ty)) |struct_type| {
5447 if (field_ptr_ty.ptrInfo(mod).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) }
5518 if (zcu.typeToPackedStruct(container_ty)) |struct_type| {
5519 if (field_ptr_ty.ptrInfo(zcu).packed_offset.host_size == 0)
5520 break :blk .{ .byte_offset = @divExact(zcu.structPackedFieldBitOffset(struct_type, field_index) + container_ptr_ty.ptrInfo(zcu).packed_offset.bit_offset, 8) }
54495521 else
54505522 break :blk .begin;
54515523 }
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| {
54545526 const next_field_index: u32 = @intCast(next_field_index_usize);
5455 if (container_ty.structFieldIsComptime(next_field_index, mod)) continue;
5456 const field_ty = container_ty.structFieldType(next_field_index, mod);
5457 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
5527 if (container_ty.structFieldIsComptime(next_field_index, zcu)) continue;
5528 const field_ty = container_ty.structFieldType(next_field_index, zcu);
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))
54605532 .{ .field = next_field_index }
54615533 else
5462 .{ .identifier = ip.stringToSlice(container_ty.legacyStructFieldName(next_field_index, mod)) } };
5534 .{ .identifier = ip.stringToSlice(container_ty.legacyStructFieldName(next_field_index, zcu)) } };
54635535 }
5464 break :blk if (container_ty.hasRuntimeBitsIgnoreComptime(mod)) .end else .begin;
5536 break :blk if (container_ty.hasRuntimeBitsIgnoreComptime(zcu)) .end else .begin;
54655537 },
54665538 .Union => {
5467 const union_obj = mod.typeToUnion(container_ty).?;
5539 const union_obj = zcu.typeToUnion(container_ty).?;
54685540 return switch (union_obj.getLayout(ip)) {
54695541 .auto, .@"extern" => {
54705542 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
5471 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod))
5472 return if (container_ty.unionTagTypeSafety(mod) != null and
5473 !container_ty.unionHasAllZeroBitFieldTypes(mod))
5543 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu))
5544 return if (container_ty.unionTagTypeSafety(zcu) != null and
5545 !container_ty.unionHasAllZeroBitFieldTypes(zcu))
54745546 .{ .field = .{ .identifier = "payload" } }
54755547 else
54765548 .begin;
54775549 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)) |_|
54795551 .{ .payload_identifier = ip.stringToSlice(field_name) }
54805552 else
54815553 .{ .identifier = ip.stringToSlice(field_name) } };
......@@ -5483,7 +5555,7 @@ fn fieldLocation(
54835555 .@"packed" => .begin,
54845556 };
54855557 },
5486 .Pointer => switch (container_ty.ptrSize(mod)) {
5558 .Pointer => switch (container_ty.ptrSize(zcu)) {
54875559 .Slice => switch (field_index) {
54885560 0 => .{ .field = .{ .identifier = "ptr" } },
54895561 1 => .{ .field = .{ .identifier = "len" } },
......@@ -5515,12 +5587,12 @@ fn airStructFieldPtrIndex(f: *Function, inst: Air.Inst.Index, index: u8) !CValue
55155587}
55165588
55175589fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5518 const mod = f.object.dg.module;
5590 const zcu = f.object.dg.zcu;
55195591 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
55205592 const extra = f.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
55215593
55225594 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
55255597 const field_ptr_ty = f.typeOf(extra.field_ptr);
55265598 const field_ptr_val = try f.resolveInst(extra.field_ptr);
......@@ -5533,10 +5605,10 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55335605 try f.renderType(writer, container_ptr_ty);
55345606 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)) {
55375609 .begin => try f.writeCValue(writer, field_ptr_val, .Initializer),
55385610 .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
55415613 try writer.writeAll("((");
55425614 try f.renderType(writer, u8_ptr_ty);
......@@ -5549,19 +5621,19 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55495621 try writer.writeAll("))");
55505622 },
55515623 .byte_offset => |byte_offset| {
5552 const u8_ptr_ty = try mod.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5553
5554 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);
5624 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55555625
55565626 try writer.writeAll("((");
55575627 try f.renderType(writer, u8_ptr_ty);
55585628 try writer.writeByte(')');
55595629 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 });
55615633 },
55625634 .end => {
55635635 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))});
55655637 },
55665638 }
55675639
......@@ -5576,8 +5648,8 @@ fn fieldPtr(
55765648 container_ptr_val: CValue,
55775649 field_index: u32,
55785650) !CValue {
5579 const mod = f.object.dg.module;
5580 const container_ty = container_ptr_ty.childType(mod);
5651 const zcu = f.object.dg.zcu;
5652 const container_ty = container_ptr_ty.childType(zcu);
55815653 const field_ptr_ty = f.typeOfIndex(inst);
55825654
55835655 // Ensure complete type definition is visible before accessing fields.
......@@ -5590,27 +5662,27 @@ fn fieldPtr(
55905662 try f.renderType(writer, field_ptr_ty);
55915663 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)) {
55945666 .begin => try f.writeCValue(writer, container_ptr_val, .Initializer),
55955667 .field => |field| {
55965668 try writer.writeByte('&');
55975669 try f.writeCValueDerefMember(writer, container_ptr_val, field);
55985670 },
55995671 .byte_offset => |byte_offset| {
5600 const u8_ptr_ty = try mod.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5601
5602 const byte_offset_val = try mod.intValue(Type.usize, byte_offset);
5672 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
56035673
56045674 try writer.writeAll("((");
56055675 try f.renderType(writer, u8_ptr_ty);
56065676 try writer.writeByte(')');
56075677 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 });
56095681 },
56105682 .end => {
56115683 try writer.writeByte('(');
56125684 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))});
56145686 },
56155687 }
56165688
......@@ -5619,13 +5691,13 @@ fn fieldPtr(
56195691}
56205692
56215693fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5622 const mod = f.object.dg.module;
5623 const ip = &mod.intern_pool;
5694 const zcu = f.object.dg.zcu;
5695 const ip = &zcu.intern_pool;
56245696 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
56255697 const extra = f.air.extraData(Air.StructField, ty_pl.payload).data;
56265698
56275699 const inst_ty = f.typeOfIndex(inst);
5628 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5700 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
56295701 try reap(f, inst, &.{extra.struct_operand});
56305702 return .none;
56315703 }
......@@ -5638,26 +5710,25 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56385710 // Ensure complete type definition is visible before accessing fields.
56395711 _ = try f.typeToIndex(struct_ty, .complete);
56405712
5641 const field_name: CValue = switch (mod.intern_pool.indexToKey(struct_ty.ip_index)) {
5642 .struct_type => switch (struct_ty.containerLayout(mod)) {
5643 .auto, .@"extern" => if (struct_ty.isSimpleTuple(mod))
5713 const field_name: CValue = switch (zcu.intern_pool.indexToKey(struct_ty.toIntern())) {
5714 .struct_type => switch (struct_ty.containerLayout(zcu)) {
5715 .auto, .@"extern" => if (struct_ty.isSimpleTuple(zcu))
56445716 .{ .field = extra.field_index }
56455717 else
5646 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, mod)) },
5718 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, zcu)) },
56475719 .@"packed" => {
5648 const struct_type = mod.typeToStruct(struct_ty).?;
5649 const int_info = struct_ty.intInfo(mod);
5720 const struct_type = zcu.typeToStruct(struct_ty).?;
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);
5654 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);
5725 const bit_offset = zcu.structPackedFieldBitOffset(struct_type, extra.field_index);
56555726
5656 const field_int_signedness = if (inst_ty.isAbiInt(mod))
5657 inst_ty.intInfo(mod).signedness
5727 const field_int_signedness = if (inst_ty.isAbiInt(zcu))
5728 inst_ty.intInfo(zcu).signedness
56585729 else
56595730 .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
56625733 const temp_local = try f.allocLocal(inst, field_int_ty);
56635734 try f.writeCValue(writer, temp_local, .Other);
......@@ -5668,7 +5739,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56685739 try writer.writeByte(')');
56695740 const cant_cast = int_info.bits > 64;
56705741 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", .{});
56725743 try writer.writeAll("zig_lo_");
56735744 try f.object.dg.renderTypeForBuiltinFnName(writer, struct_ty);
56745745 try writer.writeByte('(');
......@@ -5681,13 +5752,13 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56815752 try f.writeCValue(writer, struct_byval, .Other);
56825753 if (bit_offset > 0) {
56835754 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);
56855756 try writer.writeByte(')');
56865757 }
56875758 if (cant_cast) try writer.writeByte(')');
56885759 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);
56895760 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
56925763 const local = try f.allocLocal(inst, inst_ty);
56935764 try writer.writeAll("memcpy(");
......@@ -5705,7 +5776,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57055776 .anon_struct_type => |anon_struct_type| if (anon_struct_type.names.len == 0)
57065777 .{ .field = extra.field_index }
57075778 else
5708 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, mod)) },
5779 .{ .identifier = ip.stringToSlice(struct_ty.legacyStructFieldName(extra.field_index, zcu)) },
57095780
57105781 .union_type => field_name: {
57115782 const union_obj = ip.loadUnionType(struct_ty.toIntern());
......@@ -5757,7 +5828,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57575828/// *(E!T) -> E
57585829/// Note that the result is never a pointer.
57595830fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5760 const mod = f.object.dg.module;
5831 const zcu = f.object.dg.zcu;
57615832 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57625833
57635834 const inst_ty = f.typeOfIndex(inst);
......@@ -5765,13 +5836,13 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
57655836 const operand_ty = f.typeOf(ty_op.operand);
57665837 try reap(f, inst, &.{ty_op.operand});
57675838
5768 const operand_is_ptr = operand_ty.zigTypeTag(mod) == .Pointer;
5769 const error_union_ty = if (operand_is_ptr) operand_ty.childType(mod) else operand_ty;
5770 const error_ty = error_union_ty.errorUnionSet(mod);
5771 const payload_ty = error_union_ty.errorUnionPayload(mod);
5839 const operand_is_ptr = operand_ty.zigTypeTag(zcu) == .Pointer;
5840 const error_union_ty = if (operand_is_ptr) operand_ty.childType(zcu) else operand_ty;
5841 const error_ty = error_union_ty.errorUnionSet(zcu);
5842 const payload_ty = error_union_ty.errorUnionPayload(zcu);
57725843 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) {
57755846 // The store will be 'x = x'; elide it.
57765847 return local;
57775848 }
......@@ -5780,35 +5851,32 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
57805851 try f.writeCValue(writer, local, .Other);
57815852 try writer.writeAll(" = ");
57825853
5783 if (!payload_ty.hasRuntimeBits(mod)) {
5784 try f.writeCValue(writer, operand, .Other);
5785 } else {
5786 if (!error_ty.errorSetIsEmpty(mod))
5787 if (operand_is_ptr)
5788 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
5789 else
5790 try f.writeCValueMember(writer, operand, .{ .identifier = "error" })
5791 else {
5792 const err_int_ty = try mod.errorIntType();
5793 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Initializer);
5794 }
5795 }
5854 if (!payload_ty.hasRuntimeBits(zcu))
5855 try f.writeCValue(writer, operand, .Other)
5856 else if (error_ty.errorSetIsEmpty(zcu))
5857 try writer.print("{}", .{
5858 try f.fmtIntLiteral(try zcu.intValue(try zcu.errorIntType(), 0)),
5859 })
5860 else if (operand_is_ptr)
5861 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
5862 else
5863 try f.writeCValueMember(writer, operand, .{ .identifier = "error" });
57965864 try writer.writeAll(";\n");
57975865 return local;
57985866}
57995867
58005868fn 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;
58025870 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58035871
58045872 const inst_ty = f.typeOfIndex(inst);
58055873 const operand = try f.resolveInst(ty_op.operand);
58065874 try reap(f, inst, &.{ty_op.operand});
58075875 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
58105878 const writer = f.object.writer();
5811 if (!error_union_ty.errorUnionPayload(mod).hasRuntimeBits(mod)) {
5879 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(zcu)) {
58125880 if (!is_ptr) return .none;
58135881
58145882 const local = try f.allocLocal(inst, inst_ty);
......@@ -5834,11 +5902,11 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValu
58345902}
58355903
58365904fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
5837 const mod = f.object.dg.module;
5905 const zcu = f.object.dg.zcu;
58385906 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58395907
58405908 const inst_ty = f.typeOfIndex(inst);
5841 const repr_is_payload = inst_ty.optionalReprIsPayload(mod);
5909 const repr_is_payload = inst_ty.optionalReprIsPayload(zcu);
58425910 const payload_ty = f.typeOf(ty_op.operand);
58435911 const payload = try f.resolveInst(ty_op.operand);
58445912 try reap(f, inst, &.{ty_op.operand});
......@@ -5859,20 +5927,20 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
58595927 const a = try Assignment.start(f, writer, Type.bool);
58605928 try f.writeCValueMember(writer, local, .{ .identifier = "is_null" });
58615929 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);
58635931 try a.end(f, writer);
58645932 }
58655933 return local;
58665934}
58675935
58685936fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5869 const mod = f.object.dg.module;
5937 const zcu = f.object.dg.zcu;
58705938 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58715939
58725940 const inst_ty = f.typeOfIndex(inst);
5873 const payload_ty = inst_ty.errorUnionPayload(mod);
5874 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(mod);
5875 const err_ty = inst_ty.errorUnionSet(mod);
5941 const payload_ty = inst_ty.errorUnionPayload(zcu);
5942 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
5943 const err_ty = inst_ty.errorUnionSet(zcu);
58765944 const err = try f.resolveInst(ty_op.operand);
58775945 try reap(f, inst, &.{ty_op.operand});
58785946
......@@ -5888,7 +5956,7 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
58885956 const a = try Assignment.start(f, writer, payload_ty);
58895957 try f.writeCValueMember(writer, local, .{ .identifier = "payload" });
58905958 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);
58925960 try a.end(f, writer);
58935961 }
58945962 {
......@@ -5905,29 +5973,25 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
59055973}
59065974
59075975fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5908 const mod = f.object.dg.module;
5976 const zcu = f.object.dg.zcu;
59095977 const writer = f.object.writer();
59105978 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59115979 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);
5915 const err_int_ty = try mod.errorIntType();
5982 const payload_ty = error_union_ty.errorUnionPayload(zcu);
5983 const err_int_ty = try zcu.errorIntType();
5984 const no_err = try zcu.intValue(err_int_ty, 0);
59165985
59175986 // First, set the non-error value.
5918 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5987 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
59195988 try f.writeCValueDeref(writer, operand);
5920 try writer.writeAll(" = ");
5921 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
5922 try writer.writeAll(";\n ");
5923
5989 try writer.print(" = {};\n", .{try f.fmtIntLiteral(no_err)});
59245990 return operand;
59255991 }
59265992 try reap(f, inst, &.{ty_op.operand});
59275993 try f.writeCValueDeref(writer, operand);
5928 try writer.writeAll(".error = ");
5929 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
5930 try writer.writeAll(";\n");
5994 try writer.print(".error = {};\n", .{try f.fmtIntLiteral(no_err)});
59315995
59325996 // Then return the payload pointer (only if it is used)
59335997 if (f.liveness.isUnused(inst)) return .none;
......@@ -5956,14 +6020,14 @@ fn airSaveErrReturnTraceIndex(f: *Function, inst: Air.Inst.Index) !CValue {
59566020}
59576021
59586022fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
5959 const mod = f.object.dg.module;
6023 const zcu = f.object.dg.zcu;
59606024 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59616025
59626026 const inst_ty = f.typeOfIndex(inst);
5963 const payload_ty = inst_ty.errorUnionPayload(mod);
6027 const payload_ty = inst_ty.errorUnionPayload(zcu);
59646028 const payload = try f.resolveInst(ty_op.operand);
5965 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(mod);
5966 const err_ty = inst_ty.errorUnionSet(mod);
6029 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
6030 const err_ty = inst_ty.errorUnionSet(zcu);
59676031 try reap(f, inst, &.{ty_op.operand});
59686032
59696033 const writer = f.object.writer();
......@@ -5982,15 +6046,14 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
59826046 else
59836047 try f.writeCValueMember(writer, local, .{ .identifier = "error" });
59846048 try a.assign(f, writer);
5985 const err_int_ty = try mod.errorIntType();
5986 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
6049 try f.object.dg.renderValue(writer, try zcu.intValue(try zcu.errorIntType(), 0), .Other);
59876050 try a.end(f, writer);
59886051 }
59896052 return local;
59906053}
59916054
59926055fn 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;
59946057 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
59956058
59966059 const writer = f.object.writer();
......@@ -5998,16 +6061,16 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
59986061 try reap(f, inst, &.{un_op});
59996062 const operand_ty = f.typeOf(un_op);
60006063 const local = try f.allocLocal(inst, Type.bool);
6001 const err_union_ty = if (is_ptr) operand_ty.childType(mod) else operand_ty;
6002 const payload_ty = err_union_ty.errorUnionPayload(mod);
6003 const error_ty = err_union_ty.errorUnionSet(mod);
6064 const err_union_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
6065 const payload_ty = err_union_ty.errorUnionPayload(zcu);
6066 const error_ty = err_union_ty.errorUnionSet(zcu);
60046067
6068 const a = try Assignment.start(f, writer, Type.bool);
60056069 try f.writeCValue(writer, local, .Other);
6006 try writer.writeAll(" = ");
6007
6008 const err_int_ty = try mod.errorIntType();
6009 if (!error_ty.errorSetIsEmpty(mod))
6010 if (payload_ty.hasRuntimeBits(mod))
6070 try a.assign(f, writer);
6071 const err_int_ty = try zcu.errorIntType();
6072 if (!error_ty.errorSetIsEmpty(zcu))
6073 if (payload_ty.hasRuntimeBits(zcu))
60116074 if (is_ptr)
60126075 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
60136076 else
......@@ -6015,63 +6078,84 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
60156078 else
60166079 try f.writeCValue(writer, operand, .Other)
60176080 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);
60196082 try writer.writeByte(' ');
60206083 try writer.writeAll(operator);
60216084 try writer.writeByte(' ');
6022 try f.object.dg.renderValue(writer, err_int_ty, try mod.intValue(err_int_ty, 0), .Other);
6023 try writer.writeAll(";\n");
6085 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6086 try a.end(f, writer);
60246087 return local;
60256088}
60266089
60276090fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
6028 const mod = f.object.dg.module;
6091 const zcu = f.object.dg.zcu;
60296092 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60306093
60316094 const operand = try f.resolveInst(ty_op.operand);
60326095 try reap(f, inst, &.{ty_op.operand});
60336096 const inst_ty = f.typeOfIndex(inst);
6097 const ptr_ty = inst_ty.slicePtrFieldType(zcu);
60346098 const writer = f.object.writer();
60356099 const local = try f.allocLocal(inst, inst_ty);
6036 const array_ty = f.typeOf(ty_op.operand).childType(mod);
6037
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("; ");
6100 const operand_ty = f.typeOf(ty_op.operand);
6101 const array_ty = operand_ty.childType(zcu);
60506102
6051 const len_val = try mod.intValue(Type.usize, array_ty.arrayLen(mod));
6052 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
6053 try writer.print(" = {};\n", .{try f.fmtIntLiteral(Type.usize, len_val)});
6103 {
6104 const a = try Assignment.start(f, writer, ptr_ty);
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
60556139 return local;
60566140}
60576141
60586142fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6059 const mod = f.object.dg.module;
6143 const zcu = f.object.dg.zcu;
60606144 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60616145
60626146 const inst_ty = f.typeOfIndex(inst);
6063 const inst_scalar_ty = inst_ty.scalarType(mod);
6147 const inst_scalar_ty = inst_ty.scalarType(zcu);
60646148 const operand = try f.resolveInst(ty_op.operand);
60656149 try reap(f, inst, &.{ty_op.operand});
60666150 const operand_ty = f.typeOf(ty_op.operand);
6067 const scalar_ty = operand_ty.scalarType(mod);
6068 const target = f.object.dg.module.getTarget();
6151 const scalar_ty = operand_ty.scalarType(zcu);
6152 const target = &f.object.dg.mod.resolved_target.result;
60696153 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"
6071 else if (inst_scalar_ty.isInt(mod) and scalar_ty.isRuntimeFloat())
6072 if (inst_scalar_ty.isSignedInt(mod)) "fix" else "fixuns"
6073 else if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isInt(mod))
6074 if (scalar_ty.isSignedInt(mod)) "float" else "floatun"
6154 if (inst_scalar_ty.floatBits(target.*) < scalar_ty.floatBits(target.*)) "trunc" else "extend"
6155 else if (inst_scalar_ty.isInt(zcu) and scalar_ty.isRuntimeFloat())
6156 if (inst_scalar_ty.isSignedInt(zcu)) "fix" else "fixuns"
6157 else if (inst_scalar_ty.isRuntimeFloat() and scalar_ty.isInt(zcu))
6158 if (scalar_ty.isSignedInt(zcu)) "float" else "floatun"
60756159 else
60766160 unreachable;
60776161
......@@ -6082,20 +6166,20 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
60826166 try f.writeCValue(writer, local, .Other);
60836167 try v.elem(f, writer);
60846168 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()) {
60866170 try writer.writeAll("zig_wrap_");
60876171 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_scalar_ty);
60886172 try writer.writeByte('(');
60896173 }
60906174 try writer.writeAll("zig_");
60916175 try writer.writeAll(operation);
6092 try writer.writeAll(compilerRtAbbrev(scalar_ty, mod));
6093 try writer.writeAll(compilerRtAbbrev(inst_scalar_ty, mod));
6176 try writer.writeAll(compilerRtAbbrev(scalar_ty, zcu, target.*));
6177 try writer.writeAll(compilerRtAbbrev(inst_scalar_ty, zcu, target.*));
60946178 try writer.writeByte('(');
60956179 try f.writeCValue(writer, operand, .FunctionArgument);
60966180 try v.elem(f, writer);
60976181 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()) {
60996183 try f.object.dg.renderBuiltinInfo(writer, inst_scalar_ty, .bits);
61006184 try writer.writeByte(')');
61016185 }
......@@ -6106,7 +6190,7 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
61066190}
61076191
61086192fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
6109 const mod = f.object.dg.module;
6193 const zcu = f.object.dg.zcu;
61106194 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61116195
61126196 const operand = try f.resolveInst(un_op);
......@@ -6120,7 +6204,7 @@ fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
61206204 try writer.writeAll(" = (");
61216205 try f.renderType(writer, inst_ty);
61226206 try writer.writeByte(')');
6123 if (operand_ty.isSlice(mod)) {
6207 if (operand_ty.isSlice(zcu)) {
61246208 try f.writeCValueMember(writer, operand, .{ .identifier = "ptr" });
61256209 } else {
61266210 try f.writeCValue(writer, operand, .Other);
......@@ -6135,15 +6219,15 @@ fn airUnBuiltinCall(
61356219 operation: []const u8,
61366220 info: BuiltinInfo,
61376221) !CValue {
6138 const mod = f.object.dg.module;
6222 const zcu = f.object.dg.zcu;
61396223 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61406224
61416225 const operand = try f.resolveInst(ty_op.operand);
61426226 try reap(f, inst, &.{ty_op.operand});
61436227 const inst_ty = f.typeOfIndex(inst);
6144 const inst_scalar_ty = inst_ty.scalarType(mod);
6228 const inst_scalar_ty = inst_ty.scalarType(zcu);
61456229 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
61486232 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
61496233 const ref_ret = inst_scalar_cty.tag() == .array;
......@@ -6179,7 +6263,7 @@ fn airBinBuiltinCall(
61796263 operation: []const u8,
61806264 info: BuiltinInfo,
61816265) !CValue {
6182 const mod = f.object.dg.module;
6266 const zcu = f.object.dg.zcu;
61836267 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
61846268
61856269 const operand_ty = f.typeOf(bin_op.lhs);
......@@ -6191,8 +6275,8 @@ fn airBinBuiltinCall(
61916275 if (!is_big) try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
61926276
61936277 const inst_ty = f.typeOfIndex(inst);
6194 const inst_scalar_ty = inst_ty.scalarType(mod);
6195 const scalar_ty = operand_ty.scalarType(mod);
6278 const inst_scalar_ty = inst_ty.scalarType(zcu);
6279 const scalar_ty = operand_ty.scalarType(zcu);
61966280
61976281 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
61986282 const ref_ret = inst_scalar_cty.tag() == .array;
......@@ -6234,15 +6318,15 @@ fn airCmpBuiltinCall(
62346318 operation: enum { cmp, operator },
62356319 info: BuiltinInfo,
62366320) !CValue {
6237 const mod = f.object.dg.module;
6321 const zcu = f.object.dg.zcu;
62386322 const lhs = try f.resolveInst(data.lhs);
62396323 const rhs = try f.resolveInst(data.rhs);
62406324 try reap(f, inst, &.{ data.lhs, data.rhs });
62416325
62426326 const inst_ty = f.typeOfIndex(inst);
6243 const inst_scalar_ty = inst_ty.scalarType(mod);
6327 const inst_scalar_ty = inst_ty.scalarType(zcu);
62446328 const operand_ty = f.typeOf(data.lhs);
6245 const scalar_ty = operand_ty.scalarType(mod);
6329 const scalar_ty = operand_ty.scalarType(zcu);
62466330
62476331 const inst_scalar_cty = try f.typeToCType(inst_scalar_ty, .complete);
62486332 const ref_ret = inst_scalar_cty.tag() == .array;
......@@ -6275,7 +6359,7 @@ fn airCmpBuiltinCall(
62756359 try writer.writeByte(')');
62766360 if (!ref_ret) try writer.print("{s}{}", .{
62776361 compareOperatorC(operator),
6278 try f.fmtIntLiteral(Type.i32, try mod.intValue(Type.i32, 0)),
6362 try f.fmtIntLiteral(try zcu.intValue(Type.i32, 0)),
62796363 });
62806364 try writer.writeAll(";\n");
62816365 try v.end(f, inst, writer);
......@@ -6284,7 +6368,7 @@ fn airCmpBuiltinCall(
62846368}
62856369
62866370fn 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;
62886372 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
62896373 const extra = f.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
62906374 const inst_ty = f.typeOfIndex(inst);
......@@ -6292,19 +6376,19 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
62926376 const expected_value = try f.resolveInst(extra.expected_value);
62936377 const new_value = try f.resolveInst(extra.new_value);
62946378 const ptr_ty = f.typeOf(extra.ptr);
6295 const ty = ptr_ty.childType(mod);
6379 const ty = ptr_ty.childType(zcu);
62966380
62976381 const writer = f.object.writer();
62986382 const new_value_mat = try Materialize.start(f, inst, writer, ty, new_value);
62996383 try reap(f, inst, &.{ extra.ptr, extra.expected_value, extra.new_value });
63006384
63016385 const repr_ty = if (ty.isRuntimeFloat())
6302 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable
6386 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
63036387 else
63046388 ty;
63056389
63066390 const local = try f.allocLocal(inst, inst_ty);
6307 if (inst_ty.isPtrLikeOptional(mod)) {
6391 if (inst_ty.isPtrLikeOptional(zcu)) {
63086392 {
63096393 const a = try Assignment.start(f, writer, ty);
63106394 try f.writeCValue(writer, local, .Other);
......@@ -6317,7 +6401,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63176401 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});
63186402 try f.renderType(writer, ty);
63196403 try writer.writeByte(')');
6320 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");
6404 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
63216405 try writer.writeAll(" *)");
63226406 try f.writeCValue(writer, ptr, .Other);
63236407 try writer.writeAll(", ");
......@@ -6331,7 +6415,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63316415 try writer.writeAll(", ");
63326416 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
63336417 try writer.writeAll(", ");
6334 try f.object.dg.renderType(writer, repr_ty);
6418 try f.renderType(writer, repr_ty);
63356419 try writer.writeByte(')');
63366420 try writer.writeAll(") {\n");
63376421 f.object.indent_writer.pushIndent();
......@@ -6359,7 +6443,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63596443 try writer.print("zig_cmpxchg_{s}((zig_atomic(", .{flavor});
63606444 try f.renderType(writer, ty);
63616445 try writer.writeByte(')');
6362 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");
6446 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
63636447 try writer.writeAll(" *)");
63646448 try f.writeCValue(writer, ptr, .Other);
63656449 try writer.writeAll(", ");
......@@ -6373,7 +6457,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63736457 try writer.writeAll(", ");
63746458 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
63756459 try writer.writeAll(", ");
6376 try f.object.dg.renderType(writer, repr_ty);
6460 try f.renderType(writer, repr_ty);
63776461 try writer.writeByte(')');
63786462 try a.end(f, writer);
63796463 }
......@@ -6389,12 +6473,12 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63896473}
63906474
63916475fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6392 const mod = f.object.dg.module;
6476 const zcu = f.object.dg.zcu;
63936477 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
63946478 const extra = f.air.extraData(Air.AtomicRmw, pl_op.payload).data;
63956479 const inst_ty = f.typeOfIndex(inst);
63966480 const ptr_ty = f.typeOf(pl_op.operand);
6397 const ty = ptr_ty.childType(mod);
6481 const ty = ptr_ty.childType(zcu);
63986482 const ptr = try f.resolveInst(pl_op.operand);
63996483 const operand = try f.resolveInst(extra.operand);
64006484
......@@ -6402,10 +6486,10 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64026486 const operand_mat = try Materialize.start(f, inst, writer, ty, operand);
64036487 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));
64066490 const is_float = ty.isRuntimeFloat();
64076491 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
64106494 const local = try f.allocLocal(inst, inst_ty);
64116495 try writer.print("zig_atomicrmw_{s}", .{toAtomicRmwSuffix(extra.op())});
......@@ -6421,7 +6505,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64216505 if (use_atomic) try writer.writeAll("zig_atomic(");
64226506 try f.renderType(writer, ty);
64236507 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");
64256509 try writer.writeAll(" *)");
64266510 try f.writeCValue(writer, ptr, .Other);
64276511 try writer.writeAll(", ");
......@@ -6431,7 +6515,7 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64316515 try writer.writeAll(", ");
64326516 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
64336517 try writer.writeAll(", ");
6434 try f.object.dg.renderType(writer, repr_ty);
6518 try f.renderType(writer, repr_ty);
64356519 try writer.writeAll(");\n");
64366520 try operand_mat.end(f, inst);
64376521
......@@ -6444,15 +6528,15 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64446528}
64456529
64466530fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6447 const mod = f.object.dg.module;
6531 const zcu = f.object.dg.zcu;
64486532 const atomic_load = f.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
64496533 const ptr = try f.resolveInst(atomic_load.ptr);
64506534 try reap(f, inst, &.{atomic_load.ptr});
64516535 const ptr_ty = f.typeOf(atomic_load.ptr);
6452 const ty = ptr_ty.childType(mod);
6536 const ty = ptr_ty.childType(zcu);
64536537
64546538 const repr_ty = if (ty.isRuntimeFloat())
6455 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable
6539 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
64566540 else
64576541 ty;
64586542
......@@ -6465,7 +6549,7 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
64656549 try writer.writeAll(", (zig_atomic(");
64666550 try f.renderType(writer, ty);
64676551 try writer.writeByte(')');
6468 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");
6552 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
64696553 try writer.writeAll(" *)");
64706554 try f.writeCValue(writer, ptr, .Other);
64716555 try writer.writeAll(", ");
......@@ -6473,17 +6557,17 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
64736557 try writer.writeAll(", ");
64746558 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
64756559 try writer.writeAll(", ");
6476 try f.object.dg.renderType(writer, repr_ty);
6560 try f.renderType(writer, repr_ty);
64776561 try writer.writeAll(");\n");
64786562
64796563 return local;
64806564}
64816565
64826566fn 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;
64846568 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
64856569 const ptr_ty = f.typeOf(bin_op.lhs);
6486 const ty = ptr_ty.childType(mod);
6570 const ty = ptr_ty.childType(zcu);
64876571 const ptr = try f.resolveInst(bin_op.lhs);
64886572 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
64926576 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
64936577
64946578 const repr_ty = if (ty.isRuntimeFloat())
6495 mod.intType(.unsigned, @as(u16, @intCast(ty.abiSize(mod) * 8))) catch unreachable
6579 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
64966580 else
64976581 ty;
64986582
64996583 try writer.writeAll("zig_atomic_store((zig_atomic(");
65006584 try f.renderType(writer, ty);
65016585 try writer.writeByte(')');
6502 if (ptr_ty.isVolatilePtr(mod)) try writer.writeAll(" volatile");
6586 if (ptr_ty.isVolatilePtr(zcu)) try writer.writeAll(" volatile");
65036587 try writer.writeAll(" *)");
65046588 try f.writeCValue(writer, ptr, .Other);
65056589 try writer.writeAll(", ");
......@@ -6507,7 +6591,7 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65076591 try writer.print(", {s}, ", .{order});
65086592 try f.object.dg.renderTypeForBuiltinFnName(writer, ty);
65096593 try writer.writeAll(", ");
6510 try f.object.dg.renderType(writer, repr_ty);
6594 try f.renderType(writer, repr_ty);
65116595 try writer.writeAll(");\n");
65126596 try element_mat.end(f, inst);
65136597
......@@ -6515,8 +6599,8 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65156599}
65166600
65176601fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !void {
6518 const mod = f.object.dg.module;
6519 if (ptr_ty.isSlice(mod)) {
6602 const zcu = f.object.dg.zcu;
6603 if (ptr_ty.isSlice(zcu)) {
65206604 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" });
65216605 } else {
65226606 try f.writeCValue(writer, ptr, .FunctionArgument);
......@@ -6524,14 +6608,14 @@ fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !vo
65246608}
65256609
65266610fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6527 const mod = f.object.dg.module;
6611 const zcu = f.object.dg.zcu;
65286612 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
65296613 const dest_ty = f.typeOf(bin_op.lhs);
65306614 const dest_slice = try f.resolveInst(bin_op.lhs);
65316615 const value = try f.resolveInst(bin_op.rhs);
65326616 const elem_ty = f.typeOf(bin_op.rhs);
6533 const elem_abi_size = elem_ty.abiSize(mod);
6534 const val_is_undef = if (try f.air.value(bin_op.rhs, mod)) |val| val.isUndefDeep(mod) else false;
6617 const elem_abi_size = elem_ty.abiSize(zcu);
6618 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |val| val.isUndefDeep(zcu) else false;
65356619 const writer = f.object.writer();
65366620
65376621 if (val_is_undef) {
......@@ -6541,7 +6625,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
65416625 }
65426626
65436627 try writer.writeAll("memset(");
6544 switch (dest_ty.ptrSize(mod)) {
6628 switch (dest_ty.ptrSize(zcu)) {
65456629 .Slice => {
65466630 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });
65476631 try writer.writeAll(", 0xaa, ");
......@@ -6553,8 +6637,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
65536637 }
65546638 },
65556639 .One => {
6556 const array_ty = dest_ty.childType(mod);
6557 const len = array_ty.arrayLen(mod) * elem_abi_size;
6640 const array_ty = dest_ty.childType(zcu);
6641 const len = array_ty.arrayLen(zcu) * elem_abi_size;
65586642
65596643 try f.writeCValue(writer, dest_slice, .FunctionArgument);
65606644 try writer.print(", 0xaa, {d});\n", .{len});
......@@ -6565,12 +6649,12 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
65656649 return .none;
65666650 }
65676651
6568 if (elem_abi_size > 1 or dest_ty.isVolatilePtr(mod)) {
6652 if (elem_abi_size > 1 or dest_ty.isVolatilePtr(zcu)) {
65696653 // For the assignment in this loop, the array pointer needs to get
65706654 // casted to a regular pointer, otherwise an error like this occurs:
65716655 // error: array type 'uint32_t[20]' (aka 'unsigned int[20]') is not assignable
6572 const elem_ptr_ty = try mod.ptrType(.{
6573 .child = elem_ty.ip_index,
6656 const elem_ptr_ty = try zcu.ptrType(.{
6657 .child = elem_ty.toIntern(),
65746658 .flags = .{
65756659 .size = .C,
65766660 },
......@@ -6581,17 +6665,17 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
65816665 try writer.writeAll("for (");
65826666 try f.writeCValue(writer, index, .Other);
65836667 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);
65856669 try writer.writeAll("; ");
65866670 try f.writeCValue(writer, index, .Other);
65876671 try writer.writeAll(" != ");
6588 switch (dest_ty.ptrSize(mod)) {
6672 switch (dest_ty.ptrSize(zcu)) {
65896673 .Slice => {
65906674 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "len" });
65916675 },
65926676 .One => {
6593 const array_ty = dest_ty.childType(mod);
6594 try writer.print("{d}", .{array_ty.arrayLen(mod)});
6677 const array_ty = dest_ty.childType(zcu);
6678 try writer.print("{d}", .{array_ty.arrayLen(zcu)});
65956679 },
65966680 .Many, .C => unreachable,
65976681 }
......@@ -6620,7 +6704,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66206704 const bitcasted = try bitcast(f, Type.u8, value, elem_ty);
66216705
66226706 try writer.writeAll("memset(");
6623 switch (dest_ty.ptrSize(mod)) {
6707 switch (dest_ty.ptrSize(zcu)) {
66246708 .Slice => {
66256709 try f.writeCValueMember(writer, dest_slice, .{ .identifier = "ptr" });
66266710 try writer.writeAll(", ");
......@@ -6630,8 +6714,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66306714 try writer.writeAll(");\n");
66316715 },
66326716 .One => {
6633 const array_ty = dest_ty.childType(mod);
6634 const len = array_ty.arrayLen(mod) * elem_abi_size;
6717 const array_ty = dest_ty.childType(zcu);
6718 const len = array_ty.arrayLen(zcu) * elem_abi_size;
66356719
66366720 try f.writeCValue(writer, dest_slice, .FunctionArgument);
66376721 try writer.writeAll(", ");
......@@ -6646,7 +6730,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66466730}
66476731
66486732fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6649 const mod = f.object.dg.module;
6733 const zcu = f.object.dg.zcu;
66506734 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
66516735 const dest_ptr = try f.resolveInst(bin_op.lhs);
66526736 const src_ptr = try f.resolveInst(bin_op.rhs);
......@@ -6659,10 +6743,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
66596743 try writer.writeAll(", ");
66606744 try writeSliceOrPtr(f, writer, src_ptr, src_ty);
66616745 try writer.writeAll(", ");
6662 switch (dest_ty.ptrSize(mod)) {
6746 switch (dest_ty.ptrSize(zcu)) {
66636747 .Slice => {
6664 const elem_ty = dest_ty.childType(mod);
6665 const elem_abi_size = elem_ty.abiSize(mod);
6748 const elem_ty = dest_ty.childType(zcu);
6749 const elem_abi_size = elem_ty.abiSize(zcu);
66666750 try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" });
66676751 if (elem_abi_size > 1) {
66686752 try writer.print(" * {d});\n", .{elem_abi_size});
......@@ -6671,10 +6755,10 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
66716755 }
66726756 },
66736757 .One => {
6674 const array_ty = dest_ty.childType(mod);
6675 const elem_ty = array_ty.childType(mod);
6676 const elem_abi_size = elem_ty.abiSize(mod);
6677 const len = array_ty.arrayLen(mod) * elem_abi_size;
6758 const array_ty = dest_ty.childType(zcu);
6759 const elem_ty = array_ty.childType(zcu);
6760 const elem_abi_size = elem_ty.abiSize(zcu);
6761 const len = array_ty.arrayLen(zcu) * elem_abi_size;
66786762 try writer.print("{d});\n", .{len});
66796763 },
66806764 .Many, .C => unreachable,
......@@ -6685,16 +6769,16 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
66856769}
66866770
66876771fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6688 const mod = f.object.dg.module;
6772 const zcu = f.object.dg.zcu;
66896773 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
66906774 const union_ptr = try f.resolveInst(bin_op.lhs);
66916775 const new_tag = try f.resolveInst(bin_op.rhs);
66926776 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
66936777
6694 const union_ty = f.typeOf(bin_op.lhs).childType(mod);
6695 const layout = union_ty.unionGetLayout(mod);
6778 const union_ty = f.typeOf(bin_op.lhs).childType(zcu);
6779 const layout = union_ty.unionGetLayout(zcu);
66966780 if (layout.tag_size == 0) return .none;
6697 const tag_ty = union_ty.unionTagTypeSafety(mod).?;
6781 const tag_ty = union_ty.unionTagTypeSafety(zcu).?;
66986782
66996783 const writer = f.object.writer();
67006784 const a = try Assignment.start(f, writer, tag_ty);
......@@ -6706,14 +6790,14 @@ fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67066790}
67076791
67086792fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6709 const mod = f.object.dg.module;
6793 const zcu = f.object.dg.zcu;
67106794 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67116795
67126796 const operand = try f.resolveInst(ty_op.operand);
67136797 try reap(f, inst, &.{ty_op.operand});
67146798
67156799 const union_ty = f.typeOf(ty_op.operand);
6716 const layout = union_ty.unionGetLayout(mod);
6800 const layout = union_ty.unionGetLayout(zcu);
67176801 if (layout.tag_size == 0) return .none;
67186802
67196803 const inst_ty = f.typeOfIndex(inst);
......@@ -6728,7 +6812,7 @@ fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67286812}
67296813
67306814fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
6731 const mod = f.object.dg.module;
6815 const zcu = f.object.dg.zcu;
67326816 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
67336817
67346818 const inst_ty = f.typeOfIndex(inst);
......@@ -6740,7 +6824,7 @@ fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
67406824 const local = try f.allocLocal(inst, inst_ty);
67416825 try f.writeCValue(writer, local, .Other);
67426826 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 }),
67446828 });
67456829 try f.writeCValue(writer, operand, .Other);
67466830 try writer.writeAll(");\n");
......@@ -6765,14 +6849,14 @@ fn airErrorName(f: *Function, inst: Air.Inst.Index) !CValue {
67656849}
67666850
67676851fn airSplat(f: *Function, inst: Air.Inst.Index) !CValue {
6768 const mod = f.object.dg.module;
6852 const zcu = f.object.dg.zcu;
67696853 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67706854
67716855 const operand = try f.resolveInst(ty_op.operand);
67726856 try reap(f, inst, &.{ty_op.operand});
67736857
67746858 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
67776861 const writer = f.object.writer();
67786862 const local = try f.allocLocal(inst, inst_ty);
......@@ -6820,7 +6904,7 @@ fn airSelect(f: *Function, inst: Air.Inst.Index) !CValue {
68206904}
68216905
68226906fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6823 const mod = f.object.dg.module;
6907 const zcu = f.object.dg.zcu;
68246908 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
68256909 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 {
68366920 for (0..extra.mask_len) |index| {
68376921 try f.writeCValue(writer, local, .Other);
68386922 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);
68406924 try writer.writeAll("] = ");
68416925
6842 const mask_elem = (try mask.elemValue(mod, index)).toSignedInt(mod);
6843 const src_val = try mod.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
6926 const mask_elem = (try mask.elemValue(zcu, index)).toSignedInt(zcu);
6927 const src_val = try zcu.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
68446928
68456929 try f.writeCValue(writer, if (mask_elem >= 0) lhs else rhs, .Other);
68466930 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);
68486932 try writer.writeAll("];\n");
68496933 }
68506934
......@@ -6852,7 +6936,7 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
68526936}
68536937
68546938fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6855 const mod = f.object.dg.module;
6939 const zcu = f.object.dg.zcu;
68566940 const reduce = f.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
68576941
68586942 const scalar_ty = f.typeOfIndex(inst);
......@@ -6861,7 +6945,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
68616945 const operand_ty = f.typeOf(reduce.operand);
68626946 const writer = f.object.writer();
68636947
6864 const use_operator = scalar_ty.bitSize(mod) <= 64;
6948 const use_operator = scalar_ty.bitSize(zcu) <= 64;
68656949 const op: union(enum) {
68666950 const Func = struct { operation: []const u8, info: BuiltinInfo = .none };
68676951 float_op: Func,
......@@ -6872,28 +6956,28 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
68726956 .And => if (use_operator) .{ .infix = " &= " } else .{ .builtin = .{ .operation = "and" } },
68736957 .Or => if (use_operator) .{ .infix = " |= " } else .{ .builtin = .{ .operation = "or" } },
68746958 .Xor => if (use_operator) .{ .infix = " ^= " } else .{ .builtin = .{ .operation = "xor" } },
6875 .Min => switch (scalar_ty.zigTypeTag(mod)) {
6959 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
68766960 .Int => if (use_operator) .{ .ternary = " < " } else .{
68776961 .builtin = .{ .operation = "min" },
68786962 },
68796963 .Float => .{ .float_op = .{ .operation = "fmin" } },
68806964 else => unreachable,
68816965 },
6882 .Max => switch (scalar_ty.zigTypeTag(mod)) {
6966 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
68836967 .Int => if (use_operator) .{ .ternary = " > " } else .{
68846968 .builtin = .{ .operation = "max" },
68856969 },
68866970 .Float => .{ .float_op = .{ .operation = "fmax" } },
68876971 else => unreachable,
68886972 },
6889 .Add => switch (scalar_ty.zigTypeTag(mod)) {
6973 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
68906974 .Int => if (use_operator) .{ .infix = " += " } else .{
68916975 .builtin = .{ .operation = "addw", .info = .bits },
68926976 },
68936977 .Float => .{ .builtin = .{ .operation = "add" } },
68946978 else => unreachable,
68956979 },
6896 .Mul => switch (scalar_ty.zigTypeTag(mod)) {
6980 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
68976981 .Int => if (use_operator) .{ .infix = " *= " } else .{
68986982 .builtin = .{ .operation = "mulw", .info = .bits },
68996983 },
......@@ -6908,7 +6992,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69086992 // Equivalent to:
69096993 // reduce: {
69106994 // var accum: T = init;
6911 // for (vec) : (elem) {
6995 // for (vec) |elem| {
69126996 // accum = func(accum, elem);
69136997 // }
69146998 // break :reduce accum;
......@@ -6918,40 +7002,40 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69187002 try f.writeCValue(writer, accum, .Other);
69197003 try writer.writeAll(" = ");
69207004
6921 try f.object.dg.renderValue(writer, scalar_ty, switch (reduce.operation) {
6922 .Or, .Xor => switch (scalar_ty.zigTypeTag(mod)) {
7005 try f.object.dg.renderValue(writer, switch (reduce.operation) {
7006 .Or, .Xor => switch (scalar_ty.zigTypeTag(zcu)) {
69237007 .Bool => Value.false,
6924 .Int => try mod.intValue(scalar_ty, 0),
7008 .Int => try zcu.intValue(scalar_ty, 0),
69257009 else => unreachable,
69267010 },
6927 .And => switch (scalar_ty.zigTypeTag(mod)) {
7011 .And => switch (scalar_ty.zigTypeTag(zcu)) {
69287012 .Bool => Value.true,
6929 .Int => switch (scalar_ty.intInfo(mod).signedness) {
6930 .unsigned => try scalar_ty.maxIntScalar(mod, scalar_ty),
6931 .signed => try mod.intValue(scalar_ty, -1),
7013 .Int => switch (scalar_ty.intInfo(zcu).signedness) {
7014 .unsigned => try scalar_ty.maxIntScalar(zcu, scalar_ty),
7015 .signed => try zcu.intValue(scalar_ty, -1),
69327016 },
69337017 else => unreachable,
69347018 },
6935 .Add => switch (scalar_ty.zigTypeTag(mod)) {
6936 .Int => try mod.intValue(scalar_ty, 0),
6937 .Float => try mod.floatValue(scalar_ty, 0.0),
7019 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
7020 .Int => try zcu.intValue(scalar_ty, 0),
7021 .Float => try zcu.floatValue(scalar_ty, 0.0),
69387022 else => unreachable,
69397023 },
6940 .Mul => switch (scalar_ty.zigTypeTag(mod)) {
6941 .Int => try mod.intValue(scalar_ty, 1),
6942 .Float => try mod.floatValue(scalar_ty, 1.0),
7024 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
7025 .Int => try zcu.intValue(scalar_ty, 1),
7026 .Float => try zcu.floatValue(scalar_ty, 1.0),
69437027 else => unreachable,
69447028 },
6945 .Min => switch (scalar_ty.zigTypeTag(mod)) {
7029 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
69467030 .Bool => Value.true,
6947 .Int => try scalar_ty.maxIntScalar(mod, scalar_ty),
6948 .Float => try mod.floatValue(scalar_ty, std.math.nan(f128)),
7031 .Int => try scalar_ty.maxIntScalar(zcu, scalar_ty),
7032 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
69497033 else => unreachable,
69507034 },
6951 .Max => switch (scalar_ty.zigTypeTag(mod)) {
7035 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
69527036 .Bool => Value.false,
6953 .Int => try scalar_ty.minIntScalar(mod, scalar_ty),
6954 .Float => try mod.floatValue(scalar_ty, std.math.nan(f128)),
7037 .Int => try scalar_ty.minIntScalar(zcu, scalar_ty),
7038 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
69557039 else => unreachable,
69567040 },
69577041 }, .Initializer);
......@@ -7007,11 +7091,11 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
70077091}
70087092
70097093fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7010 const mod = f.object.dg.module;
7011 const ip = &mod.intern_pool;
7094 const zcu = f.object.dg.zcu;
7095 const ip = &zcu.intern_pool;
70127096 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
70137097 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)));
70157099 const elements = @as([]const Air.Inst.Ref, @ptrCast(f.air.extra[ty_pl.payload..][0..len]));
70167100 const gpa = f.object.dg.gpa;
70177101 const resolved_elements = try gpa.alloc(CValue, elements.len);
......@@ -7028,10 +7112,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70287112
70297113 const writer = f.object.writer();
70307114 const local = try f.allocLocal(inst, inst_ty);
7031 switch (inst_ty.zigTypeTag(mod)) {
7115 switch (inst_ty.zigTypeTag(zcu)) {
70327116 .Array, .Vector => {
7033 const elem_ty = inst_ty.childType(mod);
7034 const a = try Assignment.init(f, elem_ty);
7117 const a = try Assignment.init(f, inst_ty.childType(zcu));
70357118 for (resolved_elements, 0..) |element, i| {
70367119 try a.restart(f, writer);
70377120 try f.writeCValue(writer, local, .Other);
......@@ -7040,26 +7123,26 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70407123 try f.writeCValue(writer, element, .Other);
70417124 try a.end(f, writer);
70427125 }
7043 if (inst_ty.sentinel(mod)) |sentinel| {
7126 if (inst_ty.sentinel(zcu)) |sentinel| {
70447127 try a.restart(f, writer);
70457128 try f.writeCValue(writer, local, .Other);
70467129 try writer.print("[{d}]", .{resolved_elements.len});
70477130 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);
70497132 try a.end(f, writer);
70507133 }
70517134 },
7052 .Struct => switch (inst_ty.containerLayout(mod)) {
7135 .Struct => switch (inst_ty.containerLayout(zcu)) {
70537136 .auto, .@"extern" => for (resolved_elements, 0..) |element, field_index| {
7054 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;
7055 const field_ty = inst_ty.structFieldType(field_index, mod);
7056 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
7137 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7138 const field_ty = inst_ty.structFieldType(field_index, zcu);
7139 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70577140
70587141 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))
70607143 .{ .field = field_index }
70617144 else
7062 .{ .identifier = ip.stringToSlice(inst_ty.legacyStructFieldName(@intCast(field_index), mod)) });
7145 .{ .identifier = ip.stringToSlice(inst_ty.legacyStructFieldName(@intCast(field_index), zcu)) });
70637146 try a.assign(f, writer);
70647147 try f.writeCValue(writer, element, .Other);
70657148 try a.end(f, writer);
......@@ -7067,17 +7150,17 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70677150 .@"packed" => {
70687151 try f.writeCValue(writer, local, .Other);
70697152 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
70747157 var bit_offset: u64 = 0;
70757158
70767159 var empty = true;
70777160 for (0..elements.len) |field_index| {
7078 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;
7079 const field_ty = inst_ty.structFieldType(field_index, mod);
7080 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
7161 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7162 const field_ty = inst_ty.structFieldType(field_index, zcu);
7163 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70817164
70827165 if (!empty) {
70837166 try writer.writeAll("zig_or_");
......@@ -7088,9 +7171,9 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70887171 }
70897172 empty = true;
70907173 for (resolved_elements, 0..) |element, field_index| {
7091 if (inst_ty.structFieldIsComptime(field_index, mod)) continue;
7092 const field_ty = inst_ty.structFieldType(field_index, mod);
7093 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
7174 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
7175 const field_ty = inst_ty.structFieldType(field_index, zcu);
7176 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
70947177
70957178 if (!empty) try writer.writeAll(", ");
70967179 // TODO: Skip this entire shift if val is 0?
......@@ -7098,13 +7181,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70987181 try f.object.dg.renderTypeForBuiltinFnName(writer, inst_ty);
70997182 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))) {
71027185 try f.renderIntCast(writer, inst_ty, element, .{}, field_ty, .FunctionArgument);
71037186 } else {
71047187 try writer.writeByte('(');
71057188 try f.renderType(writer, inst_ty);
71067189 try writer.writeByte(')');
7107 if (field_ty.isPtrAtRuntime(mod)) {
7190 if (field_ty.isPtrAtRuntime(zcu)) {
71087191 try writer.writeByte('(');
71097192 try f.renderType(writer, switch (int_info.signedness) {
71107193 .unsigned => Type.usize,
......@@ -7115,14 +7198,14 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71157198 try f.writeCValue(writer, element, .Other);
71167199 }
71177200
7118 try writer.writeAll(", ");
7119 const bit_offset_val = try mod.intValue(bit_offset_ty, bit_offset);
7120 try f.object.dg.renderValue(writer, bit_offset_ty, bit_offset_val, .FunctionArgument);
7201 try writer.print(", {}", .{
7202 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
7203 });
71217204 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);
71227205 try writer.writeByte(')');
71237206 if (!empty) try writer.writeByte(')');
71247207
7125 bit_offset += field_ty.bitSize(mod);
7208 bit_offset += field_ty.bitSize(zcu);
71267209 empty = false;
71277210 }
71287211
......@@ -7136,13 +7219,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71367219}
71377220
71387221fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7139 const mod = f.object.dg.module;
7140 const ip = &mod.intern_pool;
7222 const zcu = f.object.dg.zcu;
7223 const ip = &zcu.intern_pool;
71417224 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
71427225 const extra = f.air.extraData(Air.UnionInit, ty_pl.payload).data;
71437226
71447227 const union_ty = f.typeOfIndex(inst);
7145 const union_obj = mod.typeToUnion(union_ty).?;
7228 const union_obj = zcu.typeToUnion(union_ty).?;
71467229 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
71477230 const payload_ty = f.typeOf(extra.init);
71487231 const payload = try f.resolveInst(extra.init);
......@@ -7158,19 +7241,16 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
71587241 return local;
71597242 }
71607243
7161 const field: CValue = if (union_ty.unionTagTypeSafety(mod)) |tag_ty| field: {
7162 const layout = union_ty.unionGetLayout(mod);
7244 const field: CValue = if (union_ty.unionTagTypeSafety(zcu)) |tag_ty| field: {
7245 const layout = union_ty.unionGetLayout(zcu);
71637246 if (layout.tag_size != 0) {
7164 const field_index = tag_ty.enumFieldIndex(field_name, mod).?;
7165
7166 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
7167
7168 const int_val = try tag_val.intFromEnum(tag_ty, mod);
7247 const field_index = tag_ty.enumFieldIndex(field_name, zcu).?;
7248 const tag_val = try zcu.enumValueFieldIndex(tag_ty, field_index);
71697249
71707250 const a = try Assignment.start(f, writer, tag_ty);
71717251 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });
71727252 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))});
71747254 try a.end(f, writer);
71757255 }
71767256 break :field .{ .payload_identifier = ip.stringToSlice(field_name) };
......@@ -7185,7 +7265,7 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
71857265}
71867266
71877267fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
7188 const mod = f.object.dg.module;
7268 const zcu = f.object.dg.zcu;
71897269 const prefetch = f.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
71907270
71917271 const ptr_ty = f.typeOf(prefetch.ptr);
......@@ -7196,7 +7276,7 @@ fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
71967276 switch (prefetch.cache) {
71977277 .data => {
71987278 try writer.writeAll("zig_prefetch(");
7199 if (ptr_ty.isSlice(mod))
7279 if (ptr_ty.isSlice(zcu))
72007280 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" })
72017281 else
72027282 try f.writeCValue(writer, ptr, .FunctionArgument);
......@@ -7242,14 +7322,14 @@ fn airWasmMemoryGrow(f: *Function, inst: Air.Inst.Index) !CValue {
72427322}
72437323
72447324fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {
7245 const mod = f.object.dg.module;
7325 const zcu = f.object.dg.zcu;
72467326 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72477327
72487328 const operand = try f.resolveInst(un_op);
72497329 try reap(f, inst, &.{un_op});
72507330
72517331 const operand_ty = f.typeOf(un_op);
7252 const scalar_ty = operand_ty.scalarType(mod);
7332 const scalar_ty = operand_ty.scalarType(zcu);
72537333
72547334 const writer = f.object.writer();
72557335 const local = try f.allocLocal(inst, operand_ty);
......@@ -7268,15 +7348,15 @@ fn airFloatNeg(f: *Function, inst: Air.Inst.Index) !CValue {
72687348}
72697349
72707350fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {
7271 const mod = f.object.dg.module;
7351 const zcu = f.object.dg.zcu;
72727352 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
72737353 const operand = try f.resolveInst(ty_op.operand);
72747354 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)) {
7278 .Int => if (ty.zigTypeTag(mod) == .Vector) {
7279 return f.fail("TODO implement airAbs for '{}'", .{ty.fmt(mod)});
7357 switch (scalar_ty.zigTypeTag(zcu)) {
7358 .Int => if (ty.zigTypeTag(zcu) == .Vector) {
7359 return f.fail("TODO implement airAbs for '{}'", .{ty.fmt(zcu)});
72807360 } else {
72817361 return airUnBuiltinCall(f, inst, "abs", .none);
72827362 },
......@@ -7286,8 +7366,8 @@ fn airAbs(f: *Function, inst: Air.Inst.Index) !CValue {
72867366}
72877367
72887368fn unFloatOp(f: *Function, inst: Air.Inst.Index, operand: CValue, ty: Type, operation: []const u8) !CValue {
7289 const mod = f.object.dg.module;
7290 const scalar_ty = ty.scalarType(mod);
7369 const zcu = f.object.dg.zcu;
7370 const scalar_ty = ty.scalarType(zcu);
72917371
72927372 const writer = f.object.writer();
72937373 const local = try f.allocLocal(inst, ty);
......@@ -7316,7 +7396,7 @@ fn airUnFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVal
73167396}
73177397
73187398fn 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;
73207400 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
73217401
73227402 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -7324,7 +7404,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa
73247404 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
73257405
73267406 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
73297409 const writer = f.object.writer();
73307410 const local = try f.allocLocal(inst, inst_ty);
......@@ -7346,7 +7426,7 @@ fn airBinFloatOp(f: *Function, inst: Air.Inst.Index, operation: []const u8) !CVa
73467426}
73477427
73487428fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7349 const mod = f.object.dg.module;
7429 const zcu = f.object.dg.zcu;
73507430 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
73517431 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 {
73567436 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs, pl_op.operand });
73577437
73587438 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
73617441 const writer = f.object.writer();
73627442 const local = try f.allocLocal(inst, inst_ty);
......@@ -7381,11 +7461,11 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
73817461}
73827462
73837463fn airCVaStart(f: *Function, inst: Air.Inst.Index) !CValue {
7384 const mod = f.object.dg.module;
7464 const zcu = f.object.dg.zcu;
73857465 const inst_ty = f.typeOfIndex(inst);
73867466 const decl_index = f.object.dg.pass.decl;
7387 const decl = mod.declPtr(decl_index);
7388 const fn_cty = try f.typeToCType(decl.typeOf(mod), .complete);
7467 const decl = zcu.declPtr(decl_index);
7468 const fn_cty = try f.typeToCType(decl.typeOf(zcu), .complete);
73897469 const param_len = fn_cty.castTag(.varargs_function).?.data.param_types.len;
73907470
73917471 const writer = f.object.writer();
......@@ -7589,9 +7669,8 @@ fn signAbbrev(signedness: std.builtin.Signedness) u8 {
75897669 };
75907670}
75917671
7592fn compilerRtAbbrev(ty: Type, mod: *Module) []const u8 {
7593 const target = mod.getTarget();
7594 return if (ty.isInt(mod)) switch (ty.intInfo(mod).bits) {
7672fn compilerRtAbbrev(ty: Type, zcu: *Zcu, target: std.Target) []const u8 {
7673 return if (ty.isInt(zcu)) switch (ty.intInfo(zcu).bits) {
75957674 1...32 => "si",
75967675 33...64 => "di",
75977676 65...128 => "ti",
......@@ -7753,8 +7832,8 @@ fn formatIntLiteral(
77537832 options: std.fmt.FormatOptions,
77547833 writer: anytype,
77557834) @TypeOf(writer).Error!void {
7756 const mod = data.dg.module;
7757 const target = mod.getTarget();
7835 const zcu = data.dg.zcu;
7836 const target = &data.dg.mod.resolved_target.result;
77587837
77597838 const ExpectedContents = struct {
77607839 const base = 10;
......@@ -7774,7 +7853,7 @@ fn formatIntLiteral(
77747853 defer allocator.free(undef_limbs);
77757854
77767855 var int_buf: Value.BigIntSpace = undefined;
7777 const int = if (data.val.isUndefDeep(mod)) blk: {
7856 const int = if (data.val.isUndefDeep(zcu)) blk: {
77787857 undef_limbs = try allocator.alloc(BigIntLimb, BigInt.calcTwosCompLimbCount(data.int_info.bits));
77797858 @memset(undef_limbs, undefPattern(BigIntLimb));
77807859
......@@ -7785,10 +7864,10 @@ fn formatIntLiteral(
77857864 };
77867865 undef_int.truncate(undef_int.toConst(), data.int_info.signedness, data.int_info.bits);
77877866 break :blk undef_int.toConst();
7788 } else data.val.toBigInt(&int_buf, mod);
7867 } else data.val.toBigInt(&int_buf, zcu);
77897868 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);
77927871 var one_limbs: [BigInt.calcLimbLen(1)]BigIntLimb = undefined;
77937872 const one = BigInt.Mutable.init(&one_limbs, 1).toConst();
77947873
......@@ -7919,7 +7998,7 @@ fn formatIntLiteral(
79197998 .int_info = c_limb_int_info,
79207999 .kind = data.kind,
79218000 .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()),
79238002 }, fmt, options, writer);
79248003 }
79258004 }
......@@ -8016,21 +8095,17 @@ const Vectorize = struct {
80168095 index: CValue = .none,
80178096
80188097 pub fn start(f: *Function, inst: Air.Inst.Index, writer: anytype, ty: Type) !Vectorize {
8019 const mod = f.object.dg.module;
8020 return if (ty.zigTypeTag(mod) == .Vector) index: {
8021 const len_val = try mod.intValue(Type.usize, ty.vectorLen(mod));
8022
8098 const zcu = f.object.dg.zcu;
8099 return if (ty.zigTypeTag(zcu) == .Vector) index: {
80238100 const local = try f.allocLocal(inst, Type.usize);
80248101
80258102 try writer.writeAll("for (");
80268103 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))});
80288105 try f.writeCValue(writer, local, .Other);
8029 try writer.print(" < {d}; ", .{
8030 try f.fmtIntLiteral(Type.usize, len_val),
8031 });
8106 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, ty.vectorLen(zcu)))});
80328107 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))});
80348109 f.object.indent_writer.pushIndent();
80358110
80368111 break :index .{ .index = local };
......@@ -8054,16 +8129,16 @@ const Vectorize = struct {
80548129 }
80558130};
80568131
8057fn lowerFnRetTy(ret_ty: Type, mod: *Module) !Type {
8058 if (ret_ty.ip_index == .noreturn_type) return Type.noreturn;
8132fn lowerFnRetTy(ret_ty: Type, zcu: *Zcu) !Type {
8133 if (ret_ty.toIntern() == .noreturn_type) return Type.noreturn;
80598134
8060 if (lowersToArray(ret_ty, mod)) {
8061 const gpa = mod.gpa;
8062 const ip = &mod.intern_pool;
8135 if (lowersToArray(ret_ty, zcu)) {
8136 const gpa = zcu.gpa;
8137 const ip = &zcu.intern_pool;
80638138 const names = [1]InternPool.NullTerminatedString{
80648139 try ip.getOrPutString(gpa, "array"),
80658140 };
8066 const types = [1]InternPool.Index{ret_ty.ip_index};
8141 const types = [1]InternPool.Index{ret_ty.toIntern()};
80678142 const values = [1]InternPool.Index{.none};
80688143 const interned = try ip.getAnonStructType(gpa, .{
80698144 .names = &names,
......@@ -8073,13 +8148,13 @@ fn lowerFnRetTy(ret_ty: Type, mod: *Module) !Type {
80738148 return Type.fromInterned(interned);
80748149 }
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;
80778152}
80788153
8079fn lowersToArray(ty: Type, mod: *Module) bool {
8080 return switch (ty.zigTypeTag(mod)) {
8154fn lowersToArray(ty: Type, zcu: *Zcu) bool {
8155 return switch (ty.zigTypeTag(zcu)) {
80818156 .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,
80838158 };
80848159}
80858160
......@@ -8098,7 +8173,7 @@ fn die(f: *Function, inst: Air.Inst.Index, ref: Air.Inst.Ref) !void {
80988173 const ref_inst = ref.toIndex() orelse return;
80998174 const c_value = (f.value_map.fetchRemove(ref) orelse return).value;
81008175 const local_index = switch (c_value) {
8101 .local, .new_local => |l| l,
8176 .new_local, .local => |l| l,
81028177 else => return,
81038178 };
81048179 try freeLocal(f, inst, local_index, ref_inst);
src/codegen/c/type.zig+156-142
......@@ -3,10 +3,10 @@ const mem = std.mem;
33const Allocator = mem.Allocator;
44const assert = std.debug.assert;
55const autoHash = std.hash.autoHash;
6const Target = std.Target;
76
87const Alignment = @import("../../InternPool.zig").Alignment;
9const Module = @import("../../Module.zig");
8const Zcu = @import("../../Module.zig");
9const Module = @import("../../Package/Module.zig");
1010const InternPool = @import("../../InternPool.zig");
1111const Type = @import("../../type.zig").Type;
1212
......@@ -280,7 +280,7 @@ pub const CType = extern union {
280280 };
281281 };
282282
283 pub const AlignAs = struct {
283 pub const AlignAs = packed struct {
284284 @"align": Alignment,
285285 abi: Alignment,
286286
......@@ -298,19 +298,19 @@ pub const CType = extern union {
298298 Alignment.fromNonzeroByteUnits(abi_alignment),
299299 );
300300 }
301 pub fn abiAlign(ty: Type, mod: *Module) AlignAs {
302 const abi_align = ty.abiAlignment(mod);
301 pub fn abiAlign(ty: Type, zcu: *Zcu) AlignAs {
302 const abi_align = ty.abiAlignment(zcu);
303303 return init(abi_align, abi_align);
304304 }
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 {
306306 return init(
307 struct_ty.structFieldAlign(field_i, mod),
308 struct_ty.structFieldType(field_i, mod).abiAlignment(mod),
307 struct_ty.structFieldAlign(field_i, zcu),
308 struct_ty.structFieldType(field_i, zcu).abiAlignment(zcu),
309309 );
310310 }
311 pub fn unionPayloadAlign(union_ty: Type, mod: *Module) AlignAs {
312 const union_obj = mod.typeToUnion(union_ty).?;
313 const union_payload_align = mod.unionAbiAlignment(union_obj);
311 pub fn unionPayloadAlign(union_ty: Type, zcu: *Zcu) AlignAs {
312 const union_obj = zcu.typeToUnion(union_ty).?;
313 const union_payload_align = zcu.unionAbiAlignment(union_obj);
314314 return init(union_payload_align, union_payload_align);
315315 }
316316
......@@ -356,8 +356,8 @@ pub const CType = extern union {
356356 return self.map.entries.items(.hash)[index - Tag.no_payload_count];
357357 }
358358
359 pub fn typeToIndex(self: Set, ty: Type, mod: *Module, kind: Kind) ?Index {
360 const lookup = Convert.Lookup{ .imm = .{ .set = &self, .mod = mod } };
359 pub fn typeToIndex(self: Set, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) ?Index {
360 const lookup = Convert.Lookup{ .imm = .{ .set = &self, .zcu = zcu, .mod = mod } };
361361
362362 var convert: Convert = undefined;
363363 convert.initType(ty, kind, lookup) catch unreachable;
......@@ -398,10 +398,11 @@ pub const CType = extern union {
398398 pub fn typeToIndex(
399399 self: *Promoted,
400400 ty: Type,
401 zcu: *Zcu,
401402 mod: *Module,
402403 kind: Kind,
403404 ) 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
406407 var convert: Convert = undefined;
407408 try convert.initType(ty, kind, lookup);
......@@ -417,7 +418,7 @@ pub const CType = extern union {
417418 );
418419 if (!gop.found_existing) {
419420 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);
421422 }
422423 if (std.debug.runtime_safety) {
423424 const adapter = TypeAdapter64{
......@@ -457,15 +458,15 @@ pub const CType = extern union {
457458 return promoted.cTypeToIndex(cty);
458459 }
459460
460 pub fn typeToCType(self: *Store, gpa: Allocator, ty: Type, mod: *Module, kind: Kind) !CType {
461 const idx = try self.typeToIndex(gpa, ty, mod, kind);
461 pub fn typeToCType(self: *Store, gpa: Allocator, ty: Type, zcu: *Zcu, mod: *Module, kind: Kind) !CType {
462 const idx = try self.typeToIndex(gpa, ty, zcu, mod, kind);
462463 return self.indexToCType(idx);
463464 }
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 {
466467 var promoted = self.promote(gpa);
467468 defer self.demote(promoted);
468 return promoted.typeToIndex(ty, mod, kind);
469 return promoted.typeToIndex(ty, zcu, mod, kind);
469470 }
470471
471472 pub fn clearRetainingCapacity(self: *Store, gpa: Allocator) void {
......@@ -549,9 +550,9 @@ pub const CType = extern union {
549550 };
550551 }
551552
552 pub fn signedness(self: CType, target: std.Target) std.builtin.Signedness {
553 pub fn signedness(self: CType, mod: *Module) std.builtin.Signedness {
553554 return switch (self.tag()) {
554 .char => target.charSignedness(),
555 .char => mod.resolved_target.result.charSignedness(),
555556 .@"signed char",
556557 .short,
557558 .int,
......@@ -854,7 +855,8 @@ pub const CType = extern union {
854855 }
855856 }
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;
858860 return switch (self.tag()) {
859861 .float => target.c_type_bit_size(.float),
860862 .double => target.c_type_bit_size(.double),
......@@ -868,7 +870,8 @@ pub const CType = extern union {
868870 };
869871 }
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;
872875 return switch (self.tag()) {
873876 .void => 0,
874877 .char, .@"signed char", ._Bool, .@"unsigned char", .bool, .uint8_t, .int8_t => 1,
......@@ -906,7 +909,7 @@ pub const CType = extern union {
906909 .vector,
907910 => {
908911 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);
910913 },
911914
912915 .fwd_anon_struct,
......@@ -1248,13 +1251,18 @@ pub const CType = extern union {
12481251 }
12491252
12501253 pub const Lookup = union(enum) {
1251 fail: *Module,
1254 fail: struct {
1255 zcu: *Zcu,
1256 mod: *Module,
1257 },
12521258 imm: struct {
12531259 set: *const Store.Set,
1260 zcu: *Zcu,
12541261 mod: *Module,
12551262 },
12561263 mut: struct {
12571264 promoted: *Store.Promoted,
1265 zcu: *Zcu,
12581266 mod: *Module,
12591267 },
12601268
......@@ -1265,15 +1273,15 @@ pub const CType = extern union {
12651273 };
12661274 }
12671275
1268 pub fn getTarget(self: @This()) Target {
1269 return self.getModule().getTarget();
1276 pub fn getZcu(self: @This()) *Zcu {
1277 return switch (self) {
1278 inline else => |pl| pl.zcu,
1279 };
12701280 }
12711281
12721282 pub fn getModule(self: @This()) *Module {
12731283 return switch (self) {
1274 .fail => |mod| mod,
1275 .imm => |imm| imm.mod,
1276 .mut => |mut| mut.mod,
1284 inline else => |pl| pl.mod,
12771285 };
12781286 }
12791287
......@@ -1288,8 +1296,8 @@ pub const CType = extern union {
12881296 pub fn typeToIndex(self: @This(), ty: Type, kind: Kind) !?Index {
12891297 return switch (self) {
12901298 .fail => null,
1291 .imm => |imm| imm.set.typeToIndex(ty, imm.mod, kind),
1292 .mut => |mut| try mut.promoted.typeToIndex(ty, mut.mod, kind),
1299 .imm => |imm| imm.set.typeToIndex(ty, imm.zcu, imm.mod, kind),
1300 .mut => |mut| try mut.promoted.typeToIndex(ty, mut.zcu, mut.mod, kind),
12931301 };
12941302 }
12951303
......@@ -1300,7 +1308,7 @@ pub const CType = extern union {
13001308 pub fn freeze(self: @This()) @This() {
13011309 return switch (self) {
13021310 .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 } },
13041312 };
13051313 }
13061314 };
......@@ -1354,7 +1362,7 @@ pub const CType = extern union {
13541362 self.storage.anon.fields[0] = .{
13551363 .name = "array",
13561364 .type = array_idx,
1357 .alignas = AlignAs.abiAlign(ty, lookup.getModule()),
1365 .alignas = AlignAs.abiAlign(ty, lookup.getZcu()),
13581366 };
13591367 self.initAnon(kind, fwd_idx, 1);
13601368 } else self.init(switch (kind) {
......@@ -1366,13 +1374,13 @@ pub const CType = extern union {
13661374 }
13671375
13681376 pub fn initType(self: *@This(), ty: Type, kind: Kind, lookup: Lookup) !void {
1369 const mod = lookup.getModule();
1370 const ip = &mod.intern_pool;
1377 const zcu = lookup.getZcu();
1378 const ip = &zcu.intern_pool;
13711379
13721380 self.* = undefined;
1373 if (!ty.isFnOrHasRuntimeBitsIgnoreComptime(mod))
1381 if (!ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu))
13741382 self.init(.void)
1375 else if (ty.isAbiInt(mod)) switch (ty.ip_index) {
1383 else if (ty.isAbiInt(zcu)) switch (ty.ip_index) {
13761384 .usize_type => self.init(.uintptr_t),
13771385 .isize_type => self.init(.intptr_t),
13781386 .c_char_type => self.init(.char),
......@@ -1384,13 +1392,13 @@ pub const CType = extern union {
13841392 .c_ulong_type => self.init(.@"unsigned long"),
13851393 .c_longlong_type => self.init(.@"long long"),
13861394 .c_ulonglong_type => self.init(.@"unsigned long long"),
1387 else => switch (tagFromIntInfo(ty.intInfo(mod))) {
1395 else => switch (tagFromIntInfo(ty.intInfo(zcu))) {
13881396 .void => unreachable,
13891397 else => |t| self.init(t),
13901398 .array => switch (kind) {
13911399 .forward, .complete, .global => {
1392 const abi_size = ty.abiSize(mod);
1393 const abi_align = ty.abiAlignment(mod).toByteUnits(0);
1400 const abi_size = ty.abiSize(zcu);
1401 const abi_align = ty.abiAlignment(zcu).toByteUnits(0);
13941402 self.storage = .{ .seq = .{ .base = .{ .tag = .array }, .data = .{
13951403 .len = @divExact(abi_size, abi_align),
13961404 .elem_type = tagFromIntInfo(.{
......@@ -1406,7 +1414,7 @@ pub const CType = extern union {
14061414 .payload => unreachable,
14071415 },
14081416 },
1409 } else switch (ty.zigTypeTag(mod)) {
1417 } else switch (ty.zigTypeTag(zcu)) {
14101418 .Frame => unreachable,
14111419 .AnyFrame => unreachable,
14121420
......@@ -1436,7 +1444,7 @@ pub const CType = extern union {
14361444 }),
14371445
14381446 .Pointer => {
1439 const info = ty.ptrInfo(mod);
1447 const info = ty.ptrInfo(zcu);
14401448 switch (info.flags.size) {
14411449 .Slice => {
14421450 if (switch (kind) {
......@@ -1444,18 +1452,18 @@ pub const CType = extern union {
14441452 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),
14451453 .payload => unreachable,
14461454 }) |fwd_idx| {
1447 const ptr_ty = ty.slicePtrFieldType(mod);
1455 const ptr_ty = ty.slicePtrFieldType(zcu);
14481456 if (try lookup.typeToIndex(ptr_ty, kind)) |ptr_idx| {
14491457 self.storage = .{ .anon = undefined };
14501458 self.storage.anon.fields[0] = .{
14511459 .name = "ptr",
14521460 .type = ptr_idx,
1453 .alignas = AlignAs.abiAlign(ptr_ty, mod),
1461 .alignas = AlignAs.abiAlign(ptr_ty, zcu),
14541462 };
14551463 self.storage.anon.fields[1] = .{
14561464 .name = "len",
14571465 .type = Tag.uintptr_t.toIndex(),
1458 .alignas = AlignAs.abiAlign(Type.usize, mod),
1466 .alignas = AlignAs.abiAlign(Type.usize, zcu),
14591467 };
14601468 self.initAnon(kind, fwd_idx, 2);
14611469 } else self.init(switch (kind) {
......@@ -1478,11 +1486,16 @@ pub const CType = extern union {
14781486 },
14791487 };
14801488
1481 const pointee_ty = if (info.packed_offset.host_size > 0 and
1482 info.flags.vector_index == .none)
1483 try mod.intType(.unsigned, info.packed_offset.host_size * 8)
1489 const pointee_ty = if (info.packed_offset.host_size > 0 and info.flags.vector_index == .none)
1490 try zcu.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)
14841494 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
14871500 if (try lookup.typeToIndex(pointee_ty, .forward)) |child_idx| {
14881501 self.storage = .{ .child = .{
......@@ -1495,24 +1508,24 @@ pub const CType = extern union {
14951508 }
14961509 },
14971510
1498 .Struct, .Union => |zig_ty_tag| if (ty.containerLayout(mod) == .@"packed") {
1499 if (mod.typeToPackedStruct(ty)) |packed_struct| {
1511 .Struct, .Union => |zig_ty_tag| if (ty.containerLayout(zcu) == .@"packed") {
1512 if (zcu.typeToPackedStruct(ty)) |packed_struct| {
15001513 try self.initType(Type.fromInterned(packed_struct.backingIntType(ip).*), kind, lookup);
15011514 } else {
1502 const bits: u16 = @intCast(ty.bitSize(mod));
1503 const int_ty = try mod.intType(.unsigned, bits);
1515 const bits: u16 = @intCast(ty.bitSize(zcu));
1516 const int_ty = try zcu.intType(.unsigned, bits);
15041517 try self.initType(int_ty, kind, lookup);
15051518 }
1506 } else if (ty.isTupleOrAnonStruct(mod)) {
1519 } else if (ty.isTupleOrAnonStruct(zcu)) {
15071520 if (lookup.isMutable()) {
15081521 for (0..switch (zig_ty_tag) {
1509 .Struct => ty.structFieldCount(mod),
1510 .Union => mod.typeToUnion(ty).?.field_types.len,
1522 .Struct => ty.structFieldCount(zcu),
1523 .Union => zcu.typeToUnion(ty).?.field_types.len,
15111524 else => unreachable,
15121525 }) |field_i| {
1513 const field_ty = ty.structFieldType(field_i, mod);
1514 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or
1515 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1526 const field_ty = ty.structFieldType(field_i, zcu);
1527 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1528 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
15161529 _ = try lookup.typeToIndex(field_ty, switch (kind) {
15171530 .forward, .forward_parameter => .forward,
15181531 .complete, .parameter => .complete,
......@@ -1540,14 +1553,14 @@ pub const CType = extern union {
15401553 .payload => unreachable,
15411554 });
15421555 } else {
1543 const tag_ty = ty.unionTagTypeSafety(mod);
1556 const tag_ty = ty.unionTagTypeSafety(zcu);
15441557 const is_tagged_union_wrapper = kind != .payload and tag_ty != null;
15451558 const is_struct = zig_ty_tag == .Struct or is_tagged_union_wrapper;
15461559 switch (kind) {
15471560 .forward, .forward_parameter => {
15481561 self.storage = .{ .fwd = .{
15491562 .base = .{ .tag = if (is_struct) .fwd_struct else .fwd_union },
1550 .data = ty.getOwnerDecl(mod),
1563 .data = ty.getOwnerDecl(zcu),
15511564 } };
15521565 self.value = .{ .cty = initPayload(&self.storage.fwd) };
15531566 },
......@@ -1562,7 +1575,7 @@ pub const CType = extern union {
15621575 self.storage.anon.fields[field_count] = .{
15631576 .name = "payload",
15641577 .type = payload_idx.?,
1565 .alignas = AlignAs.unionPayloadAlign(ty, mod),
1578 .alignas = AlignAs.unionPayloadAlign(ty, zcu),
15661579 };
15671580 field_count += 1;
15681581 }
......@@ -1570,7 +1583,7 @@ pub const CType = extern union {
15701583 self.storage.anon.fields[field_count] = .{
15711584 .name = "tag",
15721585 .type = tag_idx.?,
1573 .alignas = AlignAs.abiAlign(tag_ty.?, mod),
1586 .alignas = AlignAs.abiAlign(tag_ty.?, zcu),
15741587 };
15751588 field_count += 1;
15761589 }
......@@ -1583,19 +1596,19 @@ pub const CType = extern union {
15831596 } };
15841597 self.value = .{ .cty = initPayload(&self.storage.anon.pl.complete) };
15851598 } else self.init(.@"struct");
1586 } else if (kind == .payload and ty.unionHasAllZeroBitFieldTypes(mod)) {
1599 } else if (kind == .payload and ty.unionHasAllZeroBitFieldTypes(zcu)) {
15871600 self.init(.void);
15881601 } else {
15891602 var is_packed = false;
15901603 for (0..switch (zig_ty_tag) {
1591 .Struct => ty.structFieldCount(mod),
1592 .Union => mod.typeToUnion(ty).?.field_types.len,
1604 .Struct => ty.structFieldCount(zcu),
1605 .Union => zcu.typeToUnion(ty).?.field_types.len,
15931606 else => unreachable,
15941607 }) |field_i| {
1595 const field_ty = ty.structFieldType(field_i, mod);
1596 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1608 const field_ty = ty.structFieldType(field_i, zcu);
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);
15991612 if (field_align.abiOrder().compare(.lt)) {
16001613 is_packed = true;
16011614 if (!lookup.isMutable()) break;
......@@ -1634,9 +1647,9 @@ pub const CType = extern union {
16341647 .Vector => .vector,
16351648 else => unreachable,
16361649 };
1637 if (try lookup.typeToIndex(ty.childType(mod), kind)) |child_idx| {
1650 if (try lookup.typeToIndex(ty.childType(zcu), kind)) |child_idx| {
16381651 self.storage = .{ .seq = .{ .base = .{ .tag = t }, .data = .{
1639 .len = ty.arrayLenIncludingSentinel(mod),
1652 .len = ty.arrayLenIncludingSentinel(zcu),
16401653 .elem_type = child_idx,
16411654 } } };
16421655 self.value = .{ .cty = initPayload(&self.storage.seq) };
......@@ -1648,9 +1661,9 @@ pub const CType = extern union {
16481661 },
16491662
16501663 .Optional => {
1651 const payload_ty = ty.optionalChild(mod);
1652 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1653 if (ty.optionalReprIsPayload(mod)) {
1664 const payload_ty = ty.optionalChild(zcu);
1665 if (payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1666 if (ty.optionalReprIsPayload(zcu)) {
16541667 try self.initType(payload_ty, kind, lookup);
16551668 } else if (switch (kind) {
16561669 .forward, .forward_parameter => @as(Index, undefined),
......@@ -1667,12 +1680,12 @@ pub const CType = extern union {
16671680 self.storage.anon.fields[0] = .{
16681681 .name = "payload",
16691682 .type = payload_idx,
1670 .alignas = AlignAs.abiAlign(payload_ty, mod),
1683 .alignas = AlignAs.abiAlign(payload_ty, zcu),
16711684 };
16721685 self.storage.anon.fields[1] = .{
16731686 .name = "is_null",
16741687 .type = Tag.bool.toIndex(),
1675 .alignas = AlignAs.abiAlign(Type.bool, mod),
1688 .alignas = AlignAs.abiAlign(Type.bool, zcu),
16761689 };
16771690 self.initAnon(kind, fwd_idx, 2);
16781691 } else self.init(switch (kind) {
......@@ -1690,14 +1703,14 @@ pub const CType = extern union {
16901703 .complete, .parameter, .global => try lookup.typeToIndex(ty, .forward),
16911704 .payload => unreachable,
16921705 }) |fwd_idx| {
1693 const payload_ty = ty.errorUnionPayload(mod);
1706 const payload_ty = ty.errorUnionPayload(zcu);
16941707 if (try lookup.typeToIndex(payload_ty, switch (kind) {
16951708 .forward, .forward_parameter => .forward,
16961709 .complete, .parameter => .complete,
16971710 .global => .global,
16981711 .payload => unreachable,
16991712 })) |payload_idx| {
1700 const error_ty = ty.errorUnionSet(mod);
1713 const error_ty = ty.errorUnionSet(zcu);
17011714 if (payload_idx == Tag.void.toIndex()) {
17021715 try self.initType(error_ty, kind, lookup);
17031716 } else if (try lookup.typeToIndex(error_ty, kind)) |error_idx| {
......@@ -1705,12 +1718,12 @@ pub const CType = extern union {
17051718 self.storage.anon.fields[0] = .{
17061719 .name = "payload",
17071720 .type = payload_idx,
1708 .alignas = AlignAs.abiAlign(payload_ty, mod),
1721 .alignas = AlignAs.abiAlign(payload_ty, zcu),
17091722 };
17101723 self.storage.anon.fields[1] = .{
17111724 .name = "error",
17121725 .type = error_idx,
1713 .alignas = AlignAs.abiAlign(error_ty, mod),
1726 .alignas = AlignAs.abiAlign(error_ty, zcu),
17141727 };
17151728 self.initAnon(kind, fwd_idx, 2);
17161729 } else self.init(switch (kind) {
......@@ -1729,7 +1742,7 @@ pub const CType = extern union {
17291742 .Opaque => self.init(.void),
17301743
17311744 .Fn => {
1732 const info = mod.typeToFunc(ty).?;
1745 const info = zcu.typeToFunc(ty).?;
17331746 if (!info.is_generic) {
17341747 if (lookup.isMutable()) {
17351748 const param_kind: Kind = switch (kind) {
......@@ -1739,7 +1752,7 @@ pub const CType = extern union {
17391752 };
17401753 _ = try lookup.typeToIndex(Type.fromInterned(info.return_type), param_kind);
17411754 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;
17431756 _ = try lookup.typeToIndex(Type.fromInterned(param_type), param_kind);
17441757 }
17451758 }
......@@ -1906,20 +1919,21 @@ pub const CType = extern union {
19061919 }
19071920 }
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 {
19101923 var convert: Convert = undefined;
1911 try convert.initType(ty, kind, .{ .imm = .{ .set = &store.set, .mod = mod } });
1912 return createFromConvert(store, ty, mod, kind, &convert);
1924 try convert.initType(ty, kind, .{ .imm = .{ .set = &store.set, .zcu = zcu } });
1925 return createFromConvert(store, ty, zcu, mod, kind, &convert);
19131926 }
19141927
19151928 fn createFromConvert(
19161929 store: *Store.Promoted,
19171930 ty: Type,
1931 zcu: *Zcu,
19181932 mod: *Module,
19191933 kind: Kind,
19201934 convert: Convert,
19211935 ) !CType {
1922 const ip = &mod.intern_pool;
1936 const ip = &zcu.intern_pool;
19231937 const arena = store.arena.allocator();
19241938 switch (convert.value) {
19251939 .cty => |c| return c.copy(arena),
......@@ -1937,18 +1951,18 @@ pub const CType = extern union {
19371951 .packed_struct,
19381952 .packed_union,
19391953 => {
1940 const zig_ty_tag = ty.zigTypeTag(mod);
1954 const zig_ty_tag = ty.zigTypeTag(zcu);
19411955 const fields_len = switch (zig_ty_tag) {
1942 .Struct => ty.structFieldCount(mod),
1943 .Union => mod.typeToUnion(ty).?.field_types.len,
1956 .Struct => ty.structFieldCount(zcu),
1957 .Union => zcu.typeToUnion(ty).?.field_types.len,
19441958 else => unreachable,
19451959 };
19461960
19471961 var c_fields_len: usize = 0;
19481962 for (0..fields_len) |field_i| {
1949 const field_ty = ty.structFieldType(field_i, mod);
1950 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or
1951 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1963 const field_ty = ty.structFieldType(field_i, zcu);
1964 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1965 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
19521966 c_fields_len += 1;
19531967 }
19541968
......@@ -1956,26 +1970,26 @@ pub const CType = extern union {
19561970 var c_field_i: usize = 0;
19571971 for (0..fields_len) |field_i_usize| {
19581972 const field_i: u32 = @intCast(field_i_usize);
1959 const field_ty = ty.structFieldType(field_i, mod);
1960 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or
1961 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1973 const field_ty = ty.structFieldType(field_i, zcu);
1974 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
1975 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
19621976
19631977 defer c_field_i += 1;
19641978 fields_pl[c_field_i] = .{
1965 .name = try if (ty.isSimpleTuple(mod))
1979 .name = try if (ty.isSimpleTuple(zcu))
19661980 std.fmt.allocPrintZ(arena, "f{}", .{field_i})
19671981 else
19681982 arena.dupeZ(u8, ip.stringToSlice(switch (zig_ty_tag) {
1969 .Struct => ty.legacyStructFieldName(field_i, mod),
1983 .Struct => ty.legacyStructFieldName(field_i, zcu),
19701984 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
19711985 else => unreachable,
19721986 })),
1973 .type = store.set.typeToIndex(field_ty, mod, switch (kind) {
1987 .type = store.set.typeToIndex(field_ty, zcu, mod, switch (kind) {
19741988 .forward, .forward_parameter => .forward,
19751989 .complete, .parameter, .payload => .complete,
19761990 .global => .global,
19771991 }).?,
1978 .alignas = AlignAs.fieldAlign(ty, field_i, mod),
1992 .alignas = AlignAs.fieldAlign(ty, field_i, zcu),
19791993 };
19801994 }
19811995
......@@ -1996,8 +2010,8 @@ pub const CType = extern union {
19962010 const unnamed_pl = try arena.create(Payload.Unnamed);
19972011 unnamed_pl.* = .{ .base = .{ .tag = t }, .data = .{
19982012 .fields = fields_pl,
1999 .owner_decl = ty.getOwnerDecl(mod),
2000 .id = if (ty.unionTagTypeSafety(mod)) |_| 0 else unreachable,
2013 .owner_decl = ty.getOwnerDecl(zcu),
2014 .id = if (ty.unionTagTypeSafety(zcu)) |_| 0 else unreachable,
20012015 } };
20022016 return initPayload(unnamed_pl);
20032017 },
......@@ -2012,7 +2026,7 @@ pub const CType = extern union {
20122026 const struct_pl = try arena.create(Payload.Aggregate);
20132027 struct_pl.* = .{ .base = .{ .tag = t }, .data = .{
20142028 .fields = fields_pl,
2015 .fwd_decl = store.set.typeToIndex(ty, mod, .forward).?,
2029 .fwd_decl = store.set.typeToIndex(ty, zcu, mod, .forward).?,
20162030 } };
20172031 return initPayload(struct_pl);
20182032 },
......@@ -2024,7 +2038,7 @@ pub const CType = extern union {
20242038 .function,
20252039 .varargs_function,
20262040 => {
2027 const info = mod.typeToFunc(ty).?;
2041 const info = zcu.typeToFunc(ty).?;
20282042 assert(!info.is_generic);
20292043 const param_kind: Kind = switch (kind) {
20302044 .forward, .forward_parameter => .forward_parameter,
......@@ -2034,21 +2048,21 @@ pub const CType = extern union {
20342048
20352049 var c_params_len: usize = 0;
20362050 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;
20382052 c_params_len += 1;
20392053 }
20402054
20412055 const params_pl = try arena.alloc(Index, c_params_len);
20422056 var c_param_i: usize = 0;
20432057 for (info.param_types.get(ip)) |param_type| {
2044 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(mod)) continue;
2045 params_pl[c_param_i] = store.set.typeToIndex(Type.fromInterned(param_type), mod, param_kind).?;
2058 if (!Type.fromInterned(param_type).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2059 params_pl[c_param_i] = store.set.typeToIndex(Type.fromInterned(param_type), zcu, mod, param_kind).?;
20462060 c_param_i += 1;
20472061 }
20482062
20492063 const fn_pl = try arena.create(Payload.Function);
20502064 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).?,
20522066 .param_types = params_pl,
20532067 } };
20542068 return initPayload(fn_pl);
......@@ -2075,8 +2089,8 @@ pub const CType = extern union {
20752089 }
20762090
20772091 pub fn eql(self: @This(), ty: Type, cty: CType) bool {
2078 const mod = self.lookup.getModule();
2079 const ip = &mod.intern_pool;
2092 const zcu = self.lookup.getZcu();
2093 const ip = &zcu.intern_pool;
20802094 switch (self.convert.value) {
20812095 .cty => |c| return c.eql(cty),
20822096 .tag => |t| {
......@@ -2086,24 +2100,24 @@ pub const CType = extern union {
20862100 .fwd_anon_struct,
20872101 .fwd_anon_union,
20882102 => {
2089 if (!ty.isTupleOrAnonStruct(mod)) return false;
2103 if (!ty.isTupleOrAnonStruct(zcu)) return false;
20902104
20912105 var name_buf: [
20922106 std.fmt.count("f{}", .{std.math.maxInt(usize)})
20932107 ]u8 = undefined;
20942108 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);
20972111 var c_field_i: usize = 0;
20982112 for (0..switch (zig_ty_tag) {
2099 .Struct => ty.structFieldCount(mod),
2100 .Union => mod.typeToUnion(ty).?.field_types.len,
2113 .Struct => ty.structFieldCount(zcu),
2114 .Union => zcu.typeToUnion(ty).?.field_types.len,
21012115 else => unreachable,
21022116 }) |field_i_usize| {
21032117 const field_i: u32 = @intCast(field_i_usize);
2104 const field_ty = ty.structFieldType(field_i, mod);
2105 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or
2106 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2118 const field_ty = ty.structFieldType(field_i, zcu);
2119 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
2120 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
21072121
21082122 defer c_field_i += 1;
21092123 const c_field = &c_fields[c_field_i];
......@@ -2115,16 +2129,16 @@ pub const CType = extern union {
21152129 .payload => unreachable,
21162130 }) or !mem.eql(
21172131 u8,
2118 if (ty.isSimpleTuple(mod))
2132 if (ty.isSimpleTuple(zcu))
21192133 std.fmt.bufPrintZ(&name_buf, "f{}", .{field_i}) catch unreachable
21202134 else
21212135 ip.stringToSlice(switch (zig_ty_tag) {
2122 .Struct => ty.legacyStructFieldName(field_i, mod),
2136 .Struct => ty.legacyStructFieldName(field_i, zcu),
21232137 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
21242138 else => unreachable,
21252139 }),
21262140 mem.span(c_field.name),
2127 ) or AlignAs.fieldAlign(ty, field_i, mod).@"align" !=
2141 ) or AlignAs.fieldAlign(ty, field_i, zcu).@"align" !=
21282142 c_field.alignas.@"align") return false;
21292143 }
21302144 return true;
......@@ -2136,9 +2150,9 @@ pub const CType = extern union {
21362150 .packed_unnamed_union,
21372151 => switch (self.kind) {
21382152 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,
2139 .payload => if (ty.unionTagTypeSafety(mod)) |_| {
2153 .payload => if (ty.unionTagTypeSafety(zcu)) |_| {
21402154 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;
21422156 } else unreachable,
21432157 },
21442158
......@@ -2157,9 +2171,9 @@ pub const CType = extern union {
21572171 .function,
21582172 .varargs_function,
21592173 => {
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).?;
21632177 assert(!info.is_generic);
21642178 const data = cty.cast(Payload.Function).?.data;
21652179 const param_kind: Kind = switch (self.kind) {
......@@ -2173,7 +2187,7 @@ pub const CType = extern union {
21732187
21742188 var c_param_i: usize = 0;
21752189 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
21782192 if (c_param_i >= data.param_types.len) return false;
21792193 const param_cty = data.param_types[c_param_i];
......@@ -2213,8 +2227,8 @@ pub const CType = extern union {
22132227 .tag => |t| {
22142228 autoHash(hasher, t);
22152229
2216 const mod = self.lookup.getModule();
2217 const ip = &mod.intern_pool;
2230 const zcu = self.lookup.getZcu();
2231 const ip = &zcu.intern_pool;
22182232 switch (t) {
22192233 .fwd_anon_struct,
22202234 .fwd_anon_union,
......@@ -2223,16 +2237,16 @@ pub const CType = extern union {
22232237 std.fmt.count("f{}", .{std.math.maxInt(usize)})
22242238 ]u8 = undefined;
22252239
2226 const zig_ty_tag = ty.zigTypeTag(mod);
2227 for (0..switch (ty.zigTypeTag(mod)) {
2228 .Struct => ty.structFieldCount(mod),
2229 .Union => mod.typeToUnion(ty).?.field_types.len,
2240 const zig_ty_tag = ty.zigTypeTag(zcu);
2241 for (0..switch (ty.zigTypeTag(zcu)) {
2242 .Struct => ty.structFieldCount(zcu),
2243 .Union => zcu.typeToUnion(ty).?.field_types.len,
22302244 else => unreachable,
22312245 }) |field_i_usize| {
22322246 const field_i: u32 = @intCast(field_i_usize);
2233 const field_ty = ty.structFieldType(field_i, mod);
2234 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, mod)) or
2235 !field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2247 const field_ty = ty.structFieldType(field_i, zcu);
2248 if ((zig_ty_tag == .Struct and ty.structFieldIsComptime(field_i, zcu)) or
2249 !field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
22362250
22372251 self.updateHasherRecurse(hasher, field_ty, switch (self.kind) {
22382252 .forward, .forward_parameter => .forward,
......@@ -2240,15 +2254,15 @@ pub const CType = extern union {
22402254 .global => .global,
22412255 .payload => unreachable,
22422256 });
2243 hasher.update(if (ty.isSimpleTuple(mod))
2257 hasher.update(if (ty.isSimpleTuple(zcu))
22442258 std.fmt.bufPrint(&name_buf, "f{}", .{field_i}) catch unreachable
22452259 else
2246 mod.intern_pool.stringToSlice(switch (zig_ty_tag) {
2247 .Struct => ty.legacyStructFieldName(field_i, mod),
2260 zcu.intern_pool.stringToSlice(switch (zig_ty_tag) {
2261 .Struct => ty.legacyStructFieldName(field_i, zcu),
22482262 .Union => ip.loadUnionType(ty.toIntern()).loadTagType(ip).names.get(ip)[field_i],
22492263 else => unreachable,
22502264 }));
2251 autoHash(hasher, AlignAs.fieldAlign(ty, field_i, mod).@"align");
2265 autoHash(hasher, AlignAs.fieldAlign(ty, field_i, zcu).@"align");
22522266 }
22532267 },
22542268
......@@ -2258,8 +2272,8 @@ pub const CType = extern union {
22582272 .packed_unnamed_union,
22592273 => switch (self.kind) {
22602274 .forward, .forward_parameter, .complete, .parameter, .global => unreachable,
2261 .payload => if (ty.unionTagTypeSafety(mod)) |_| {
2262 autoHash(hasher, ty.getOwnerDecl(mod));
2275 .payload => if (ty.unionTagTypeSafety(zcu)) |_| {
2276 autoHash(hasher, ty.getOwnerDecl(zcu));
22632277 autoHash(hasher, @as(u32, 0));
22642278 } else unreachable,
22652279 },
......@@ -2275,7 +2289,7 @@ pub const CType = extern union {
22752289 .function,
22762290 .varargs_function,
22772291 => {
2278 const info = mod.typeToFunc(ty).?;
2292 const info = zcu.typeToFunc(ty).?;
22792293 assert(!info.is_generic);
22802294 const param_kind: Kind = switch (self.kind) {
22812295 .forward, .forward_parameter => .forward_parameter,
......@@ -2285,7 +2299,7 @@ pub const CType = extern union {
22852299
22862300 self.updateHasherRecurse(hasher, Type.fromInterned(info.return_type), param_kind);
22872301 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;
22892303 self.updateHasherRecurse(hasher, Type.fromInterned(param_type), param_kind);
22902304 }
22912305 },
src/link/C.zig+66-48
......@@ -6,7 +6,8 @@ const fs = std.fs;
66
77const C = @This();
88const build_options = @import("build_options");
9const Module = @import("../Module.zig");
9const Zcu = @import("../Module.zig");
10const Module = @import("../Package/Module.zig");
1011const InternPool = @import("../InternPool.zig");
1112const Alignment = InternPool.Alignment;
1213const Compilation = @import("../Compilation.zig");
......@@ -177,16 +178,16 @@ pub fn freeDecl(self: *C, decl_index: InternPool.DeclIndex) void {
177178
178179pub fn updateFunc(
179180 self: *C,
180 module: *Module,
181 zcu: *Zcu,
181182 func_index: InternPool.Index,
182183 air: Air,
183184 liveness: Liveness,
184185) !void {
185186 const gpa = self.base.comp.gpa;
186187
187 const func = module.funcInfo(func_index);
188 const func = zcu.funcInfo(func_index);
188189 const decl_index = func.owner_decl;
189 const decl = module.declPtr(decl_index);
190 const decl = zcu.declPtr(decl_index);
190191 const gop = try self.decl_table.getOrPut(gpa, decl_index);
191192 if (!gop.found_existing) gop.value_ptr.* = .{};
192193 const ctypes = &gop.value_ptr.ctypes;
......@@ -206,10 +207,11 @@ pub fn updateFunc(
206207 .object = .{
207208 .dg = .{
208209 .gpa = gpa,
209 .module = module,
210 .zcu = zcu,
211 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
210212 .error_msg = null,
211213 .pass = .{ .decl = decl_index },
212 .is_naked_fn = decl.typeOf(module).fnCallingConvention(module) == .Naked,
214 .is_naked_fn = decl.typeOf(zcu).fnCallingConvention(zcu) == .Naked,
213215 .fwd_decl = fwd_decl.toManaged(gpa),
214216 .ctypes = ctypes.*,
215217 .anon_decl_deps = self.anon_decls,
......@@ -232,7 +234,7 @@ pub fn updateFunc(
232234
233235 codegen.genFunc(&function) catch |err| switch (err) {
234236 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.?);
236238 return;
237239 },
238240 else => |e| return e,
......@@ -249,7 +251,7 @@ pub fn updateFunc(
249251 gop.value_ptr.fwd_decl = try self.addString(function.object.dg.fwd_decl.items);
250252}
251253
252fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
254fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
253255 const gpa = self.base.comp.gpa;
254256 const anon_decl = self.anon_decls.keys()[i];
255257
......@@ -261,7 +263,8 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
261263 var object: codegen.Object = .{
262264 .dg = .{
263265 .gpa = gpa,
264 .module = module,
266 .zcu = zcu,
267 .mod = zcu.root_mod,
265268 .error_msg = null,
266269 .pass = .{ .anon = anon_decl },
267270 .is_naked_fn = false,
......@@ -283,12 +286,12 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
283286 code.* = object.code.moveToUnmanaged();
284287 }
285288
286 const c_value: codegen.CValue = .{ .constant = anon_decl };
289 const c_value: codegen.CValue = .{ .constant = Value.fromInterned(anon_decl) };
287290 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) {
289292 error.AnalysisFail => {
290293 @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.?);
292295 //return;
293296 },
294297 else => |e| return e,
......@@ -304,12 +307,13 @@ fn updateAnonDecl(self: *C, module: *Module, i: usize) !void {
304307 };
305308}
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 {
308311 const tracy = trace(@src());
309312 defer tracy.end();
310313
311314 const gpa = self.base.comp.gpa;
312315
316 const decl = zcu.declPtr(decl_index);
313317 const gop = try self.decl_table.getOrPut(gpa, decl_index);
314318 if (!gop.found_existing) {
315319 gop.value_ptr.* = .{};
......@@ -324,7 +328,8 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
324328 var object: codegen.Object = .{
325329 .dg = .{
326330 .gpa = gpa,
327 .module = module,
331 .zcu = zcu,
332 .mod = zcu.namespacePtr(decl.src_namespace).file_scope.mod,
328333 .error_msg = null,
329334 .pass = .{ .decl = decl_index },
330335 .is_naked_fn = false,
......@@ -347,7 +352,7 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
347352
348353 codegen.genDecl(&object) catch |err| switch (err) {
349354 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.?);
351356 return;
352357 },
353358 else => |e| return e,
......@@ -362,11 +367,11 @@ pub fn updateDecl(self: *C, module: *Module, decl_index: InternPool.DeclIndex) !
362367 gop.value_ptr.fwd_decl = try self.addString(object.dg.fwd_decl.items);
363368}
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 {
366371 // The C backend does not have the ability to fix line numbers without re-generating
367372 // the entire Decl.
368373 _ = self;
369 _ = module;
374 _ = zcu;
370375 _ = decl_index;
371376}
372377
......@@ -399,12 +404,12 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
399404
400405 const comp = self.base.comp;
401406 const gpa = comp.gpa;
402 const module = self.base.comp.module.?;
407 const zcu = self.base.comp.module.?;
403408
404409 {
405410 var i: usize = 0;
406411 while (i < self.anon_decls.count()) : (i += 1) {
407 try updateAnonDecl(self, module, i);
412 try updateAnonDecl(self, zcu, i);
408413 }
409414 }
410415
......@@ -414,7 +419,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
414419 var f: Flush = .{};
415420 defer f.deinit(gpa);
416421
417 const abi_defines = try self.abiDefines(module.getTarget());
422 const abi_defines = try self.abiDefines(zcu.getTarget());
418423 defer abi_defines.deinit();
419424
420425 // 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
429434 {
430435 var asm_buf = f.asm_buf.toManaged(gpa);
431436 defer f.asm_buf = asm_buf.moveToUnmanaged();
432 try codegen.genGlobalAsm(module, asm_buf.writer());
437 try codegen.genGlobalAsm(zcu, asm_buf.writer());
433438 f.appendBufAssumeCapacity(asm_buf.items);
434439 }
435440
......@@ -438,7 +443,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
438443
439444 self.lazy_fwd_decl_buf.clearRetainingCapacity();
440445 self.lazy_code_buf.clearRetainingCapacity();
441 try self.flushErrDecls(&f.lazy_ctypes);
446 try self.flushErrDecls(zcu, &f.lazy_ctypes);
442447
443448 // Unlike other backends, the .c code we are emitting has order-dependent decls.
444449 // `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
446451 {
447452 var export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
448453 defer export_names.deinit(gpa);
449 try export_names.ensureTotalCapacity(gpa, @intCast(module.decl_exports.entries.len));
450 for (module.decl_exports.values()) |exports| for (exports.items) |@"export"|
454 try export_names.ensureTotalCapacity(gpa, @intCast(zcu.decl_exports.entries.len));
455 for (zcu.decl_exports.values()) |exports| for (exports.items) |@"export"|
451456 try export_names.put(gpa, @"export".opts.name, {});
452457
453458 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);
455460 }
456461
457462 for (self.decl_table.keys(), self.decl_table.values()) |decl_index, *decl_block| {
458 assert(module.declPtr(decl_index).has_tv);
459 const decl = module.declPtr(decl_index);
460 const extern_symbol_name = if (decl.isExtern(module)) decl.name.toOptional() else .none;
461 try self.flushDeclBlock(&f, decl_block, export_names, extern_symbol_name);
463 const decl = zcu.declPtr(decl_index);
464 assert(decl.has_tv);
465 const extern_symbol_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;
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);
462468 }
463469 }
464470
......@@ -466,14 +472,14 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: *std.Progress.Node) !v
466472 // We need to flush lazy ctypes after flushing all decls but before flushing any decl ctypes.
467473 // This ensures that every lazy CType.Index exactly matches the global CType.Index.
468474 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
471477 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);
473479 }
474480
475481 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);
477483 }
478484 }
479485
......@@ -543,12 +549,12 @@ const FlushDeclError = error{
543549
544550fn flushCTypes(
545551 self: *C,
552 zcu: *Zcu,
546553 f: *Flush,
547554 pass: codegen.DeclGen.Pass,
548555 decl_ctypes: codegen.CType.Store,
549556) FlushDeclError!void {
550557 const gpa = self.base.comp.gpa;
551 const mod = self.base.comp.module.?;
552558
553559 const decl_ctypes_len = decl_ctypes.count();
554560 f.ctypes_map.clearRetainingCapacity();
......@@ -615,7 +621,7 @@ fn flushCTypes(
615621 assert(decl_cty.hash(decl_ctypes.set) == global_cty.hash(global_ctypes.set));
616622 }
617623 try codegen.genTypeDecl(
618 mod,
624 zcu,
619625 writer,
620626 global_ctypes.set,
621627 global_idx,
......@@ -627,7 +633,7 @@ fn flushCTypes(
627633 }
628634}
629635
630fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {
636fn flushErrDecls(self: *C, zcu: *Zcu, ctypes: *codegen.CType.Store) FlushDeclError!void {
631637 const gpa = self.base.comp.gpa;
632638
633639 const fwd_decl = &self.lazy_fwd_decl_buf;
......@@ -636,7 +642,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {
636642 var object = codegen.Object{
637643 .dg = .{
638644 .gpa = gpa,
639 .module = self.base.comp.module.?,
645 .zcu = zcu,
646 .mod = zcu.root_mod,
640647 .error_msg = null,
641648 .pass = .flush,
642649 .is_naked_fn = false,
......@@ -667,6 +674,8 @@ fn flushErrDecls(self: *C, ctypes: *codegen.CType.Store) FlushDeclError!void {
667674
668675fn flushLazyFn(
669676 self: *C,
677 zcu: *Zcu,
678 mod: *Module,
670679 ctypes: *codegen.CType.Store,
671680 lazy_fn: codegen.LazyFnMap.Entry,
672681) FlushDeclError!void {
......@@ -678,7 +687,8 @@ fn flushLazyFn(
678687 var object = codegen.Object{
679688 .dg = .{
680689 .gpa = gpa,
681 .module = self.base.comp.module.?,
690 .zcu = zcu,
691 .mod = mod,
682692 .error_msg = null,
683693 .pass = .flush,
684694 .is_naked_fn = false,
......@@ -709,7 +719,13 @@ fn flushLazyFn(
709719 ctypes.* = object.dg.ctypes.move();
710720}
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 {
713729 const gpa = self.base.comp.gpa;
714730 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
718734 const gop = f.lazy_fns.getOrPutAssumeCapacity(entry.key_ptr.*);
719735 if (gop.found_existing) continue;
720736 gop.value_ptr.* = {};
721 try self.flushLazyFn(&f.lazy_ctypes, entry);
737 try self.flushLazyFn(zcu, mod, &f.lazy_ctypes, entry);
722738 }
723739}
724740
725741fn flushDeclBlock(
726742 self: *C,
743 zcu: *Zcu,
744 mod: *Module,
727745 f: *Flush,
728746 decl_block: *DeclBlock,
729747 export_names: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void),
730748 extern_symbol_name: InternPool.OptionalNullTerminatedString,
731749) FlushDeclError!void {
732750 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);
734752 try f.all_buffers.ensureUnusedCapacity(gpa, 1);
735753 fwd_decl: {
736754 if (extern_symbol_name.unwrap()) |name| {
......@@ -740,15 +758,15 @@ fn flushDeclBlock(
740758 }
741759}
742760
743pub fn flushEmitH(module: *Module) !void {
761pub fn flushEmitH(zcu: *Zcu) !void {
744762 const tracy = trace(@src());
745763 defer tracy.end();
746764
747 const emit_h = module.emit_h orelse return;
765 const emit_h = zcu.emit_h orelse return;
748766
749767 // We collect a list of buffers to write, and write them all at once with pwritev 😎
750768 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);
752770 defer all_buffers.deinit();
753771
754772 var file_size: u64 = zig_h.len;
......@@ -771,7 +789,7 @@ pub fn flushEmitH(module: *Module) !void {
771789 }
772790 }
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;
775793 const file = try directory.handle.createFile(emit_h.loc.basename, .{
776794 // We set the end position explicitly below; by not truncating the file, we possibly
777795 // make it easier on the file system by doing 1 reallocation instead of two.
......@@ -785,12 +803,12 @@ pub fn flushEmitH(module: *Module) !void {
785803
786804pub fn updateExports(
787805 self: *C,
788 module: *Module,
789 exported: Module.Exported,
790 exports: []const *Module.Export,
806 zcu: *Zcu,
807 exported: Zcu.Exported,
808 exports: []const *Zcu.Export,
791809) !void {
792810 _ = exports;
793811 _ = exported;
794 _ = module;
812 _ = zcu;
795813 _ = self;
796814}