authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-29 02:29:46-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-29 02:29:46-07:00
logb3b00ec62f518875a486b4da532f74e304c3aba2
tree5ae6f6dd8afba7cacd3d5b1532d4c25b3661189d
parent4fdfaf69c8c55ebac4c5b3c00025c0ac51281b5b
parent8899e6e334758f2e101399075d0456195035c372

Merge branch 'more-stage2-locals'


12 files changed, 916 insertions(+), 238 deletions(-)

lib/std/fmt.zig+2
......@@ -88,6 +88,8 @@ pub fn format(
8888 if (args.len > ArgSetType.bit_count) {
8989 @compileError("32 arguments max are supported per format call");
9090 }
91 if (args.len == 0)
92 return writer.writeAll(fmt);
9193
9294 const State = enum {
9395 Start,
src-self-hosted/Module.zig+66-19
......@@ -47,7 +47,6 @@ export_owners: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
4747/// Maps fully qualified namespaced names to the Decl struct for them.
4848decl_table: std.HashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
4949
50optimize_mode: std.builtin.Mode,
5150link_error_flags: link.File.ErrorFlags = .{},
5251
5352work_queue: std.fifo.LinearFifo(WorkItem, .Dynamic),
......@@ -385,18 +384,6 @@ pub const Scope = struct {
385384 };
386385 }
387386
388 pub fn dumpInst(self: *Scope, inst: *Inst) void {
389 const zir_module = self.namespace();
390 const loc = std.zig.findLineColumn(zir_module.source.bytes, inst.src);
391 std.debug.warn("{}:{}:{}: {}: ty={}\n", .{
392 zir_module.sub_file_path,
393 loc.line + 1,
394 loc.column + 1,
395 @tagName(inst.tag),
396 inst.ty,
397 });
398 }
399
400387 /// Asserts the scope has a parent which is a ZIRModule or File and
401388 /// returns the sub_file_path field.
402389 pub fn subFilePath(base: *Scope) []const u8 {
......@@ -802,6 +789,7 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
802789 .output_mode = options.output_mode,
803790 .link_mode = options.link_mode orelse .Static,
804791 .object_format = options.object_format orelse options.target.getObjectFormat(),
792 .optimize_mode = options.optimize_mode,
805793 });
806794 errdefer bin_file.destroy();
807795
......@@ -838,7 +826,6 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
838826 .bin_file_dir = bin_file_dir,
839827 .bin_file_path = options.bin_file_path,
840828 .bin_file = bin_file,
841 .optimize_mode = options.optimize_mode,
842829 .work_queue = std.fifo.LinearFifo(WorkItem, .Dynamic).init(gpa),
843830 .keep_source_files_loaded = options.keep_source_files_loaded,
844831 };
......@@ -894,7 +881,11 @@ fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
894881}
895882
896883pub fn target(self: Module) std.Target {
897 return self.bin_file.options().target;
884 return self.bin_file.options.target;
885}
886
887pub fn optimizeMode(self: Module) std.builtin.Mode {
888 return self.bin_file.options.optimize_mode;
898889}
899890
900891/// Detect changes to source files, perform semantic analysis, and update the output files.
......@@ -1991,14 +1982,14 @@ pub fn constType(self: *Module, scope: *Scope, src: usize, ty: Type) !*Inst {
19911982pub fn constVoid(self: *Module, scope: *Scope, src: usize) !*Inst {
19921983 return self.constInst(scope, src, .{
19931984 .ty = Type.initTag(.void),
1994 .val = Value.initTag(.the_one_possible_value),
1985 .val = Value.initTag(.void_value),
19951986 });
19961987}
19971988
19981989pub fn constNoReturn(self: *Module, scope: *Scope, src: usize) !*Inst {
19991990 return self.constInst(scope, src, .{
20001991 .ty = Type.initTag(.noreturn),
2001 .val = Value.initTag(.the_one_possible_value),
1992 .val = Value.initTag(.unreachable_value),
20021993 });
20031994}
20041995
......@@ -2151,7 +2142,8 @@ pub fn analyzeDeref(self: *Module, scope: *Scope, src: usize, ptr: *Inst, ptr_sr
21512142 });
21522143 }
21532144
2154 return self.fail(scope, src, "TODO implement runtime deref", .{});
2145 const b = try self.requireRuntimeBlock(scope, src);
2146 return self.addUnOp(b, src, elem_ty, .load, ptr);
21552147}
21562148
21572149pub fn analyzeDeclRefByName(self: *Module, scope: *Scope, src: usize, decl_name: []const u8) InnerError!*Inst {
......@@ -2161,7 +2153,8 @@ pub fn analyzeDeclRefByName(self: *Module, scope: *Scope, src: usize, decl_name:
21612153}
21622154
21632155pub fn wantSafety(self: *Module, scope: *Scope) bool {
2164 return switch (self.optimize_mode) {
2156 // TODO take into account scope's safety overrides
2157 return switch (self.optimizeMode()) {
21652158 .Debug => true,
21662159 .ReleaseSafe => true,
21672160 .ReleaseFast => false,
......@@ -2504,6 +2497,22 @@ pub fn coerce(self: *Module, scope: *Scope, dest_type: Type, inst: *Inst) !*Inst
25042497 return self.fail(scope, inst.src, "TODO implement type coercion from {} to {}", .{ inst.ty, dest_type });
25052498}
25062499
2500pub fn storePtr(self: *Module, scope: *Scope, src: usize, ptr: *Inst, uncasted_value: *Inst) !*Inst {
2501 if (ptr.ty.isConstPtr())
2502 return self.fail(scope, src, "cannot assign to constant", .{});
2503
2504 const elem_ty = ptr.ty.elemType();
2505 const value = try self.coerce(scope, elem_ty, uncasted_value);
2506 if (elem_ty.onePossibleValue() != null)
2507 return self.constVoid(scope, src);
2508
2509 // TODO handle comptime pointer writes
2510 // TODO handle if the element type requires comptime
2511
2512 const b = try self.requireRuntimeBlock(scope, src);
2513 return self.addBinOp(b, src, Type.initTag(.void), .store, ptr, value);
2514}
2515
25072516pub fn bitcast(self: *Module, scope: *Scope, dest_type: Type, inst: *Inst) !*Inst {
25082517 if (inst.value()) |val| {
25092518 // Keep the comptime Value representation; take the new type.
......@@ -2780,3 +2789,41 @@ pub fn singleMutPtrType(self: *Module, scope: *Scope, src: usize, elem_ty: Type)
27802789 type_payload.* = .{ .pointee_type = elem_ty };
27812790 return Type.initPayload(&type_payload.base);
27822791}
2792
2793pub fn singleConstPtrType(self: *Module, scope: *Scope, src: usize, elem_ty: Type) error{OutOfMemory}!Type {
2794 const type_payload = try scope.arena().create(Type.Payload.SingleConstPointer);
2795 type_payload.* = .{ .pointee_type = elem_ty };
2796 return Type.initPayload(&type_payload.base);
2797}
2798
2799pub fn dumpInst(self: *Module, scope: *Scope, inst: *Inst) void {
2800 const zir_module = scope.namespace();
2801 const source = zir_module.getSource(self) catch @panic("dumpInst failed to get source");
2802 const loc = std.zig.findLineColumn(source, inst.src);
2803 if (inst.tag == .constant) {
2804 std.debug.warn("constant ty={} val={} src={}:{}:{}\n", .{
2805 inst.ty,
2806 inst.castTag(.constant).?.val,
2807 zir_module.subFilePath(),
2808 loc.line + 1,
2809 loc.column + 1,
2810 });
2811 } else if (inst.deaths == 0) {
2812 std.debug.warn("{} ty={} src={}:{}:{}\n", .{
2813 @tagName(inst.tag),
2814 inst.ty,
2815 zir_module.subFilePath(),
2816 loc.line + 1,
2817 loc.column + 1,
2818 });
2819 } else {
2820 std.debug.warn("{} ty={} deaths={b} src={}:{}:{}\n", .{
2821 @tagName(inst.tag),
2822 inst.ty,
2823 inst.deaths,
2824 zir_module.subFilePath(),
2825 loc.line + 1,
2826 loc.column + 1,
2827 });
2828 }
2829}
src-self-hosted/astgen.zig+23-14
......@@ -87,7 +87,7 @@ pub fn expr(mod: *Module, scope: *Scope, rl: ResultLoc, node: *ast.Node) InnerEr
8787 .ArrayCat => return simpleBinOp(mod, scope, rl, node.castTag(.ArrayCat).?, .array_cat),
8888 .ArrayMult => return simpleBinOp(mod, scope, rl, node.castTag(.ArrayMult).?, .array_mul),
8989
90 .Identifier => return rlWrap(mod, scope, rl, try identifier(mod, scope, node.castTag(.Identifier).?)),
90 .Identifier => return try identifier(mod, scope, rl, node.castTag(.Identifier).?),
9191 .Asm => return rlWrap(mod, scope, rl, try assembly(mod, scope, node.castTag(.Asm).?)),
9292 .StringLiteral => return rlWrap(mod, scope, rl, try stringLiteral(mod, scope, node.castTag(.StringLiteral).?)),
9393 .IntegerLiteral => return rlWrap(mod, scope, rl, try integerLiteral(mod, scope, node.castTag(.IntegerLiteral).?)),
......@@ -145,8 +145,10 @@ pub fn blockExpr(mod: *Module, parent_scope: *Scope, block_node: *ast.Node.Block
145145
146146 else => {
147147 const possibly_unused_result = try expr(mod, scope, .none, statement);
148 const src = scope.tree().token_locs[statement.firstToken()].start;
149 _ = try addZIRUnOp(mod, scope, src, .ensure_result_used, possibly_unused_result);
148 if (!possibly_unused_result.tag.isNoReturn()) {
149 const src = scope.tree().token_locs[statement.firstToken()].start;
150 _ = try addZIRUnOp(mod, scope, src, .ensure_result_used, possibly_unused_result);
151 }
150152 },
151153 }
152154 }
......@@ -469,7 +471,7 @@ fn ret(mod: *Module, scope: *Scope, cfe: *ast.Node.ControlFlowExpression) InnerE
469471 }
470472}
471473
472fn identifier(mod: *Module, scope: *Scope, ident: *ast.Node.OneToken) InnerError!*zir.Inst {
474fn identifier(mod: *Module, scope: *Scope, rl: ResultLoc, ident: *ast.Node.OneToken) InnerError!*zir.Inst {
473475 const tracy = trace(@src());
474476 defer tracy.end();
475477
......@@ -481,7 +483,8 @@ fn identifier(mod: *Module, scope: *Scope, ident: *ast.Node.OneToken) InnerError
481483 }
482484
483485 if (getSimplePrimitiveValue(ident_name)) |typed_value| {
484 return addZIRInstConst(mod, scope, src, typed_value);
486 const result = try addZIRInstConst(mod, scope, src, typed_value);
487 return rlWrap(mod, scope, rl, result);
485488 }
486489
487490 if (ident_name.len >= 2) integer: {
......@@ -505,16 +508,18 @@ fn identifier(mod: *Module, scope: *Scope, ident: *ast.Node.OneToken) InnerError
505508 else => {
506509 const int_type_payload = try scope.arena().create(Value.Payload.IntType);
507510 int_type_payload.* = .{ .signed = is_signed, .bits = bit_count };
508 return addZIRInstConst(mod, scope, src, .{
511 const result = try addZIRInstConst(mod, scope, src, .{
509512 .ty = Type.initTag(.comptime_int),
510513 .val = Value.initPayload(&int_type_payload.base),
511514 });
515 return rlWrap(mod, scope, rl, result);
512516 },
513517 };
514 return addZIRInstConst(mod, scope, src, .{
518 const result = try addZIRInstConst(mod, scope, src, .{
515519 .ty = Type.initTag(.type),
516520 .val = val,
517521 });
522 return rlWrap(mod, scope, rl, result);
518523 }
519524 }
520525
......@@ -525,14 +530,19 @@ fn identifier(mod: *Module, scope: *Scope, ident: *ast.Node.OneToken) InnerError
525530 .local_val => {
526531 const local_val = s.cast(Scope.LocalVal).?;
527532 if (mem.eql(u8, local_val.name, ident_name)) {
528 return local_val.inst;
533 return rlWrap(mod, scope, rl, local_val.inst);
529534 }
530535 s = local_val.parent;
531536 },
532537 .local_ptr => {
533538 const local_ptr = s.cast(Scope.LocalPtr).?;
534539 if (mem.eql(u8, local_ptr.name, ident_name)) {
535 return try addZIRUnOp(mod, scope, src, .deref, local_ptr.ptr);
540 if (rl == .lvalue) {
541 return local_ptr.ptr;
542 } else {
543 const result = try addZIRUnOp(mod, scope, src, .deref, local_ptr.ptr);
544 return rlWrap(mod, scope, rl, result);
545 }
536546 }
537547 s = local_ptr.parent;
538548 },
......@@ -542,7 +552,9 @@ fn identifier(mod: *Module, scope: *Scope, ident: *ast.Node.OneToken) InnerError
542552 }
543553
544554 if (mod.lookupDeclName(scope, ident_name)) |decl| {
545 return try addZIRInst(mod, scope, src, zir.Inst.DeclValInModule, .{ .decl = decl }, .{});
555 // TODO handle lvalues
556 const result = try addZIRInst(mod, scope, src, zir.Inst.DeclValInModule, .{ .decl = decl }, .{});
557 return rlWrap(mod, scope, rl, result);
546558 }
547559
548560 return mod.failNode(scope, &ident.base, "use of undeclared identifier '{}'", .{ident_name});
......@@ -1066,10 +1078,7 @@ fn rlWrap(mod: *Module, scope: *Scope, rl: ResultLoc, result: *zir.Inst) InnerEr
10661078 .ptr = ptr_inst,
10671079 .value = result,
10681080 }, .{});
1069 _ = try addZIRInst(mod, scope, result.src, zir.Inst.Store, .{
1070 .ptr = ptr_inst,
1071 .value = casted_result,
1072 }, .{});
1081 _ = try addZIRBinOp(mod, scope, result.src, .store, ptr_inst, casted_result);
10731082 return casted_result;
10741083 },
10751084 .bitcasted_ptr => |bitcasted_ptr| {
src-self-hosted/codegen.zig+499-94
......@@ -50,7 +50,7 @@ pub fn generateSymbol(
5050
5151 switch (typed_value.ty.zigTypeTag()) {
5252 .Fn => {
53 switch (bin_file.options.target.cpu.arch) {
53 switch (bin_file.base.options.target.cpu.arch) {
5454 //.arm => return Function(.arm).generateSymbol(bin_file, src, typed_value, code),
5555 //.armeb => return Function(.armeb).generateSymbol(bin_file, src, typed_value, code),
5656 //.aarch64 => return Function(.aarch64).generateSymbol(bin_file, src, typed_value, code),
......@@ -143,7 +143,7 @@ pub fn generateSymbol(
143143 // TODO handle the dependency of this symbol on the decl's vaddr.
144144 // If the decl changes vaddr, then this symbol needs to get regenerated.
145145 const vaddr = bin_file.local_symbols.items[decl.link.local_sym_index].st_value;
146 const endian = bin_file.options.target.cpu.arch.endian();
146 const endian = bin_file.base.options.target.cpu.arch.endian();
147147 switch (bin_file.ptr_width) {
148148 .p32 => {
149149 try code.resize(4);
......@@ -166,7 +166,7 @@ pub fn generateSymbol(
166166 };
167167 },
168168 .Int => {
169 const info = typed_value.ty.intInfo(bin_file.options.target);
169 const info = typed_value.ty.intInfo(bin_file.base.options.target);
170170 if (info.bits == 8 and !info.signed) {
171171 const x = typed_value.val.toUnsignedInt();
172172 try code.append(@intCast(u8, x));
......@@ -209,10 +209,16 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
209209 err_msg: ?*ErrorMsg,
210210 args: []MCValue,
211211 ret_mcv: MCValue,
212 fn_type: Type,
212213 arg_index: usize,
213214 src: usize,
214215 stack_align: u32,
215216
217 /// The value is an offset into the `Function` `code` from the beginning.
218 /// To perform the reloc, write 32-bit signed little-endian integer
219 /// which is a relative jump, based on the address following the reloc.
220 exitlude_jump_relocs: std.ArrayListUnmanaged(usize) = .{},
221
216222 /// Whenever there is a runtime branch, we push a Branch onto this stack,
217223 /// and pop it off when the runtime branch joins. This provides an "overlay"
218224 /// of the table of mappings from instructions to `MCValue` from within the branch.
......@@ -229,16 +235,26 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
229235 unreach,
230236 /// No more references to this value remain.
231237 dead,
238 /// The value is undefined.
239 undef,
232240 /// A pointer-sized integer that fits in a register.
241 /// If the type is a pointer, this is the pointer address in virtual address space.
233242 immediate: u64,
234243 /// The constant was emitted into the code, at this offset.
244 /// If the type is a pointer, it means the pointer address is embedded in the code.
235245 embedded_in_code: usize,
246 /// The value is a pointer to a constant which was emitted into the code, at this offset.
247 ptr_embedded_in_code: usize,
236248 /// The value is in a target-specific register.
237249 register: Register,
238250 /// The value is in memory at a hard-coded address.
251 /// If the type is a pointer, it means the pointer address is at this memory location.
239252 memory: u64,
240253 /// The value is one of the stack variables.
241 stack_offset: u64,
254 /// If the type is a pointer, it means the pointer address is in the stack at this offset.
255 stack_offset: u32,
256 /// The value is a pointer to one of the stack variables (payload is stack offset).
257 ptr_stack_offset: u32,
242258 /// The value is in the compare flags assuming an unsigned operation,
243259 /// with this operator applied on top of it.
244260 compare_flags_unsigned: math.CompareOperator,
......@@ -271,6 +287,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
271287 .memory,
272288 .compare_flags_unsigned,
273289 .compare_flags_signed,
290 .ptr_stack_offset,
291 .ptr_embedded_in_code,
292 .undef,
274293 => false,
275294
276295 .register,
......@@ -309,6 +328,19 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
309328 self.free_registers |= @as(FreeRegInt, 1) << shift;
310329 }
311330
331 /// Before calling, must ensureCapacity + 1 on branch.registers.
332 /// Returns `null` if all registers are allocated.
333 fn allocReg(self: *Branch, inst: *ir.Inst) ?Register {
334 const free_index = @ctz(FreeRegInt, self.free_registers);
335 if (free_index >= callee_preserved_regs.len) {
336 return null;
337 }
338 self.free_registers &= ~(@as(FreeRegInt, 1) << free_index);
339 const reg = callee_preserved_regs[free_index];
340 self.registers.putAssumeCapacityNoClobber(reg, .{ .inst = inst });
341 return reg;
342 }
343
312344 fn deinit(self: *Branch, gpa: *Allocator) void {
313345 self.inst_table.deinit(gpa);
314346 self.registers.deinit(gpa);
......@@ -349,18 +381,20 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
349381
350382 var function = Self{
351383 .gpa = bin_file.allocator,
352 .target = &bin_file.options.target,
384 .target = &bin_file.base.options.target,
353385 .bin_file = bin_file,
354386 .mod_fn = module_fn,
355387 .code = code,
356388 .err_msg = null,
357389 .args = undefined, // populated after `resolveCallingConventionValues`
358390 .ret_mcv = undefined, // populated after `resolveCallingConventionValues`
391 .fn_type = fn_type,
359392 .arg_index = 0,
360393 .branch_stack = &branch_stack,
361394 .src = src,
362395 .stack_align = undefined,
363396 };
397 defer function.exitlude_jump_relocs.deinit(bin_file.allocator);
364398
365399 var call_info = function.resolveCallingConventionValues(src, fn_type) catch |err| switch (err) {
366400 error.CodegenFail => return Result{ .fail = function.err_msg.? },
......@@ -386,29 +420,78 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
386420 }
387421
388422 fn gen(self: *Self) !void {
389 try self.code.ensureCapacity(self.code.items.len + 11);
390
391 // TODO omit this for naked functions
392 // push rbp
393 // mov rbp, rsp
394 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x55, 0x48, 0x89, 0xe5 });
395
396 // sub rsp, x
397 const stack_end = self.branch_stack.items[0].max_end_stack;
398 if (stack_end > math.maxInt(i32)) {
399 return self.fail(self.src, "too much stack used in call parameters", .{});
400 } else if (stack_end > math.maxInt(i8)) {
401 // 48 83 ec xx sub rsp,0x10
402 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x48, 0x81, 0xec });
403 const x = @intCast(u32, stack_end);
404 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), x);
405 } else if (stack_end != 0) {
406 // 48 81 ec xx xx xx xx sub rsp,0x80
407 const x = @intCast(u8, stack_end);
408 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x48, 0x83, 0xec, x });
409 }
423 switch (arch) {
424 .x86_64 => {
425 try self.code.ensureCapacity(self.code.items.len + 11);
426
427 const cc = self.fn_type.fnCallingConvention();
428 if (cc != .Naked) {
429 // We want to subtract the aligned stack frame size from rsp here, but we don't
430 // yet know how big it will be, so we leave room for a 4-byte stack size.
431 // TODO During semantic analysis, check if there are no function calls. If there
432 // are none, here we can omit the part where we subtract and then add rsp.
433 self.code.appendSliceAssumeCapacity(&[_]u8{
434 // push rbp
435 0x55,
436 // mov rbp, rsp
437 0x48,
438 0x89,
439 0xe5,
440 // sub rsp, imm32 (with reloc)
441 0x48,
442 0x81,
443 0xec,
444 });
445 const reloc_index = self.code.items.len;
446 self.code.items.len += 4;
447
448 try self.genBody(self.mod_fn.analysis.success);
449
450 const stack_end = self.branch_stack.items[0].max_end_stack;
451 if (stack_end > math.maxInt(i32))
452 return self.fail(self.src, "too much stack used in call parameters", .{});
453 const aligned_stack_end = mem.alignForward(stack_end, self.stack_align);
454 mem.writeIntLittle(u32, self.code.items[reloc_index..][0..4], @intCast(u32, aligned_stack_end));
455
456 if (self.code.items.len >= math.maxInt(i32)) {
457 return self.fail(self.src, "unable to perform relocation: jump too far", .{});
458 }
459 for (self.exitlude_jump_relocs.items) |jmp_reloc| {
460 const amt = self.code.items.len - (jmp_reloc + 4);
461 // If it wouldn't jump at all, elide it.
462 if (amt == 0) {
463 self.code.items.len -= 5;
464 continue;
465 }
466 const s32_amt = @intCast(i32, amt);
467 mem.writeIntLittle(i32, self.code.items[jmp_reloc..][0..4], s32_amt);
468 }
469
470 try self.code.ensureCapacity(self.code.items.len + 9);
471 // add rsp, x
472 if (aligned_stack_end > math.maxInt(i8)) {
473 // example: 48 81 c4 ff ff ff 7f add rsp,0x7fffffff
474 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x48, 0x81, 0xc4 });
475 const x = @intCast(u32, aligned_stack_end);
476 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), x);
477 } else if (aligned_stack_end != 0) {
478 // example: 48 83 c4 7f add rsp,0x7f
479 const x = @intCast(u8, aligned_stack_end);
480 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x48, 0x83, 0xc4, x });
481 }
410482
411 try self.genBody(self.mod_fn.analysis.success);
483 self.code.appendSliceAssumeCapacity(&[_]u8{
484 0x5d, // pop rbp
485 0xc3, // ret
486 });
487 } else {
488 try self.genBody(self.mod_fn.analysis.success);
489 }
490 },
491 else => {
492 try self.genBody(self.mod_fn.analysis.success);
493 },
494 }
412495 }
413496
414497 fn genBody(self: *Self, body: ir.Body) InnerError!void {
......@@ -432,8 +515,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
432515 entry.value = .dead;
433516 switch (prev_value) {
434517 .register => |reg| {
435 _ = branch.registers.remove(reg);
436 branch.markRegFree(reg);
518 const reg64 = reg.to64();
519 _ = branch.registers.remove(reg64);
520 branch.markRegFree(reg64);
437521 },
438522 else => {}, // TODO process stack allocation death
439523 }
......@@ -459,26 +543,23 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
459543 .cmp_neq => return self.genCmp(inst.castTag(.cmp_neq).?, .neq),
460544 .condbr => return self.genCondBr(inst.castTag(.condbr).?),
461545 .constant => unreachable, // excluded from function bodies
546 .floatcast => return self.genFloatCast(inst.castTag(.floatcast).?),
547 .intcast => return self.genIntCast(inst.castTag(.intcast).?),
462548 .isnonnull => return self.genIsNonNull(inst.castTag(.isnonnull).?),
463549 .isnull => return self.genIsNull(inst.castTag(.isnull).?),
550 .load => return self.genLoad(inst.castTag(.load).?),
551 .not => return self.genNot(inst.castTag(.not).?),
464552 .ptrtoint => return self.genPtrToInt(inst.castTag(.ptrtoint).?),
553 .ref => return self.genRef(inst.castTag(.ref).?),
465554 .ret => return self.genRet(inst.castTag(.ret).?),
466555 .retvoid => return self.genRetVoid(inst.castTag(.retvoid).?),
556 .store => return self.genStore(inst.castTag(.store).?),
467557 .sub => return self.genSub(inst.castTag(.sub).?),
468558 .unreach => return MCValue{ .unreach = {} },
469 .not => return self.genNot(inst.castTag(.not).?),
470 .floatcast => return self.genFloatCast(inst.castTag(.floatcast).?),
471 .intcast => return self.genIntCast(inst.castTag(.intcast).?),
472559 }
473560 }
474561
475 fn genAlloc(self: *Self, inst: *ir.Inst.NoOp) !MCValue {
476 const elem_ty = inst.base.ty.elemType();
477 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
478 return self.fail(inst.base.src, "type '{}' too big to fit into stack frame", .{elem_ty});
479 };
480 // TODO swap this for inst.base.ty.ptrAlign
481 const abi_align = elem_ty.abiAlignment(self.target.*);
562 fn allocMem(self: *Self, inst: *ir.Inst, abi_size: u32, abi_align: u32) !u32 {
482563 if (abi_align > self.stack_align)
483564 self.stack_align = abi_align;
484565 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
......@@ -488,10 +569,62 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
488569 if (branch.next_stack_offset > branch.max_end_stack)
489570 branch.max_end_stack = branch.next_stack_offset;
490571 try branch.stack.putNoClobber(self.gpa, offset, .{
491 .inst = &inst.base,
572 .inst = inst,
492573 .size = abi_size,
493574 });
494 return MCValue{ .stack_offset = offset };
575 return offset;
576 }
577
578 /// Use a pointer instruction as the basis for allocating stack memory.
579 fn allocMemPtr(self: *Self, inst: *ir.Inst) !u32 {
580 const elem_ty = inst.ty.elemType();
581 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
582 return self.fail(inst.src, "type '{}' too big to fit into stack frame", .{elem_ty});
583 };
584 // TODO swap this for inst.ty.ptrAlign
585 const abi_align = elem_ty.abiAlignment(self.target.*);
586 return self.allocMem(inst, abi_size, abi_align);
587 }
588
589 fn allocRegOrMem(self: *Self, inst: *ir.Inst) !MCValue {
590 const elem_ty = inst.ty;
591 const abi_size = math.cast(u32, elem_ty.abiSize(self.target.*)) catch {
592 return self.fail(inst.src, "type '{}' too big to fit into stack frame", .{elem_ty});
593 };
594 const abi_align = elem_ty.abiAlignment(self.target.*);
595 if (abi_align > self.stack_align)
596 self.stack_align = abi_align;
597 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
598
599 // Make sure the type can fit in a register before we try to allocate one.
600 const ptr_bits = arch.ptrBitWidth();
601 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
602 if (abi_size <= ptr_bytes) {
603 try branch.registers.ensureCapacity(self.gpa, branch.registers.items().len + 1);
604 if (branch.allocReg(inst)) |reg| {
605 return MCValue{ .register = registerAlias(reg, abi_size) };
606 }
607 }
608 const stack_offset = try self.allocMem(inst, abi_size, abi_align);
609 return MCValue{ .stack_offset = stack_offset };
610 }
611
612 /// Does not "move" the instruction.
613 fn copyToNewRegister(self: *Self, inst: *ir.Inst) !MCValue {
614 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
615 try branch.registers.ensureCapacity(self.gpa, branch.registers.items().len + 1);
616
617 const reg = branch.allocReg(inst) orelse
618 return self.fail(inst.src, "TODO implement spilling register to stack", .{});
619 const old_mcv = branch.inst_table.get(inst).?;
620 const new_mcv: MCValue = .{ .register = reg };
621 try self.genSetReg(inst.src, reg, old_mcv);
622 return new_mcv;
623 }
624
625 fn genAlloc(self: *Self, inst: *ir.Inst.NoOp) !MCValue {
626 const stack_offset = try self.allocMemPtr(&inst.base);
627 return MCValue{ .ptr_stack_offset = stack_offset };
495628 }
496629
497630 fn genFloatCast(self: *Self, inst: *ir.Inst.UnOp) !MCValue {
......@@ -572,6 +705,87 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
572705 }
573706 }
574707
708 fn genLoad(self: *Self, inst: *ir.Inst.UnOp) !MCValue {
709 const elem_ty = inst.base.ty;
710 if (!elem_ty.hasCodeGenBits())
711 return MCValue.none;
712 const ptr = try self.resolveInst(inst.operand);
713 const is_volatile = inst.operand.ty.isVolatilePtr();
714 if (inst.base.isUnused() and !is_volatile)
715 return MCValue.dead;
716 const dst_mcv: MCValue = blk: {
717 if (inst.base.operandDies(0) and ptr.isMutable()) {
718 // The MCValue that holds the pointer can be re-used as the value.
719 // TODO track this in the register/stack allocation metadata.
720 break :blk ptr;
721 } else {
722 break :blk try self.allocRegOrMem(&inst.base);
723 }
724 };
725 switch (ptr) {
726 .none => unreachable,
727 .undef => unreachable,
728 .unreach => unreachable,
729 .dead => unreachable,
730 .compare_flags_unsigned => unreachable,
731 .compare_flags_signed => unreachable,
732 .immediate => |imm| try self.setRegOrMem(inst.base.src, elem_ty, dst_mcv, .{ .memory = imm }),
733 .ptr_stack_offset => |off| try self.setRegOrMem(inst.base.src, elem_ty, dst_mcv, .{ .stack_offset = off }),
734 .ptr_embedded_in_code => |off| {
735 try self.setRegOrMem(inst.base.src, elem_ty, dst_mcv, .{ .embedded_in_code = off });
736 },
737 .embedded_in_code => {
738 return self.fail(inst.base.src, "TODO implement loading from MCValue.embedded_in_code", .{});
739 },
740 .register => {
741 return self.fail(inst.base.src, "TODO implement loading from MCValue.register", .{});
742 },
743 .memory => {
744 return self.fail(inst.base.src, "TODO implement loading from MCValue.memory", .{});
745 },
746 .stack_offset => {
747 return self.fail(inst.base.src, "TODO implement loading from MCValue.stack_offset", .{});
748 },
749 }
750 return dst_mcv;
751 }
752
753 fn genStore(self: *Self, inst: *ir.Inst.BinOp) !MCValue {
754 const ptr = try self.resolveInst(inst.lhs);
755 const value = try self.resolveInst(inst.rhs);
756 const elem_ty = inst.rhs.ty;
757 switch (ptr) {
758 .none => unreachable,
759 .undef => unreachable,
760 .unreach => unreachable,
761 .dead => unreachable,
762 .compare_flags_unsigned => unreachable,
763 .compare_flags_signed => unreachable,
764 .immediate => |imm| {
765 try self.setRegOrMem(inst.base.src, elem_ty, .{ .memory = imm }, value);
766 },
767 .ptr_stack_offset => |off| {
768 try self.genSetStack(inst.base.src, elem_ty, off, value);
769 },
770 .ptr_embedded_in_code => |off| {
771 try self.setRegOrMem(inst.base.src, elem_ty, .{ .embedded_in_code = off }, value);
772 },
773 .embedded_in_code => {
774 return self.fail(inst.base.src, "TODO implement storing to MCValue.embedded_in_code", .{});
775 },
776 .register => {
777 return self.fail(inst.base.src, "TODO implement storing to MCValue.register", .{});
778 },
779 .memory => {
780 return self.fail(inst.base.src, "TODO implement storing to MCValue.memory", .{});
781 },
782 .stack_offset => {
783 return self.fail(inst.base.src, "TODO implement storing to MCValue.stack_offset", .{});
784 },
785 }
786 return .none;
787 }
788
575789 fn genSub(self: *Self, inst: *ir.Inst.BinOp) !MCValue {
576790 // No side effects, so if it's unreferenced, do nothing.
577791 if (inst.base.isUnused())
......@@ -654,13 +868,19 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
654868 fn genX8664BinMathCode(self: *Self, src: usize, dst_mcv: MCValue, src_mcv: MCValue, opx: u8, mr: u8) !void {
655869 switch (dst_mcv) {
656870 .none => unreachable,
871 .undef => unreachable,
657872 .dead, .unreach, .immediate => unreachable,
658873 .compare_flags_unsigned => unreachable,
659874 .compare_flags_signed => unreachable,
875 .ptr_stack_offset => unreachable,
876 .ptr_embedded_in_code => unreachable,
660877 .register => |dst_reg| {
661878 switch (src_mcv) {
662879 .none => unreachable,
880 .undef => try self.genSetReg(src, dst_reg, .undef),
663881 .dead, .unreach => unreachable,
882 .ptr_stack_offset => unreachable,
883 .ptr_embedded_in_code => unreachable,
664884 .register => |src_reg| {
665885 self.rex(.{ .b = dst_reg.isExtended(), .r = src_reg.isExtended(), .w = dst_reg.size() == 64 });
666886 self.code.appendSliceAssumeCapacity(&[_]u8{ mr + 0x1, 0xC0 | (@as(u8, src_reg.id() & 0b111) << 3) | @as(u8, dst_reg.id() & 0b111) });
......@@ -743,6 +963,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
743963 for (info.args) |mc_arg, arg_i| {
744964 const arg = inst.args[arg_i];
745965 const arg_mcv = try self.resolveInst(inst.args[arg_i]);
966 // Here we do not use setRegOrMem even though the logic is similar, because
967 // the function call will move the stack pointer, so the offsets are different.
746968 switch (mc_arg) {
747969 .none => continue,
748970 .register => |reg| {
......@@ -754,6 +976,13 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
754976 // mov qword ptr [rsp + stack_offset], x
755977 return self.fail(inst.base.src, "TODO implement calling with parameters in memory", .{});
756978 },
979 .ptr_stack_offset => {
980 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_stack_offset arg", .{});
981 },
982 .ptr_embedded_in_code => {
983 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_embedded_in_code arg", .{});
984 },
985 .undef => unreachable,
757986 .immediate => unreachable,
758987 .unreach => unreachable,
759988 .dead => unreachable,
......@@ -788,17 +1017,47 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
7881017 return info.return_value;
7891018 }
7901019
1020 fn genRef(self: *Self, inst: *ir.Inst.UnOp) !MCValue {
1021 const operand = try self.resolveInst(inst.operand);
1022 switch (operand) {
1023 .unreach => unreachable,
1024 .dead => unreachable,
1025 .none => return .none,
1026
1027 .immediate,
1028 .register,
1029 .ptr_stack_offset,
1030 .ptr_embedded_in_code,
1031 .compare_flags_unsigned,
1032 .compare_flags_signed,
1033 => {
1034 const stack_offset = try self.allocMemPtr(&inst.base);
1035 try self.genSetStack(inst.base.src, inst.operand.ty, stack_offset, operand);
1036 return MCValue{ .ptr_stack_offset = stack_offset };
1037 },
1038
1039 .stack_offset => |offset| return MCValue{ .ptr_stack_offset = offset },
1040 .embedded_in_code => |offset| return MCValue{ .ptr_embedded_in_code = offset },
1041 .memory => |vaddr| return MCValue{ .immediate = vaddr },
1042
1043 .undef => return self.fail(inst.base.src, "TODO implement ref on an undefined value", .{}),
1044 }
1045 }
1046
7911047 fn ret(self: *Self, src: usize, mcv: MCValue) !MCValue {
792 try self.setRegOrStack(src, self.ret_mcv, mcv);
1048 const ret_ty = self.fn_type.fnReturnType();
1049 try self.setRegOrMem(src, ret_ty, self.ret_mcv, mcv);
7931050 switch (arch) {
7941051 .i386 => {
7951052 try self.code.append(0xc3); // ret
7961053 },
7971054 .x86_64 => {
798 try self.code.appendSlice(&[_]u8{
799 0x5d, // pop rbp
800 0xc3, // ret
801 });
1055 // TODO when implementing defer, this will need to jump to the appropriate defer expression.
1056 // TODO optimization opportunity: figure out when we can emit this as a 2 byte instruction
1057 // which is available if the jump is 127 bytes or less forward.
1058 try self.code.resize(self.code.items.len + 5);
1059 self.code.items[self.code.items.len - 5] = 0xe9; // jmp rel32
1060 try self.exitlude_jump_relocs.append(self.gpa, self.code.items.len - 4);
8021061 },
8031062 else => return self.fail(src, "TODO implement return for {}", .{self.target.cpu.arch}),
8041063 }
......@@ -882,7 +1141,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
8821141 // test reg, 1
8831142 // TODO detect al, ax, eax
8841143 try self.code.ensureCapacity(self.code.items.len + 4);
885 self.rex(.{ .b = reg.isExtended(), .w = reg.size() == 64 });
1144 // TODO audit this codegen: we force w = true here to make
1145 // the value affect the big register
1146 self.rex(.{ .b = reg.isExtended(), .w = true });
8861147 self.code.appendSliceAssumeCapacity(&[_]u8{
8871148 0xf6,
8881149 @as(u8, 0xC0) | (0 << 3) | @truncate(u3, reg.id()),
......@@ -938,6 +1199,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
9381199 switch (reloc) {
9391200 .rel32 => |pos| {
9401201 const amt = self.code.items.len - (pos + 4);
1202 // If it wouldn't jump at all, elide it.
1203 if (amt == 0) {
1204 self.code.items.len -= 5;
1205 return;
1206 }
9411207 const s32_amt = math.cast(i32, amt) catch
9421208 return self.fail(src, "unable to perform relocation: jump too far", .{});
9431209 mem.writeIntLittle(i32, self.code.items[pos..][0..4], s32_amt);
......@@ -1042,25 +1308,141 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
10421308 }
10431309
10441310 /// Sets the value without any modifications to register allocation metadata or stack allocation metadata.
1045 fn setRegOrStack(self: *Self, src: usize, loc: MCValue, val: MCValue) !void {
1311 fn setRegOrMem(self: *Self, src: usize, ty: Type, loc: MCValue, val: MCValue) !void {
10461312 switch (loc) {
10471313 .none => return,
10481314 .register => |reg| return self.genSetReg(src, reg, val),
1049 .stack_offset => {
1050 return self.fail(src, "TODO implement setRegOrStack for stack offset", .{});
1315 .stack_offset => |off| return self.genSetStack(src, ty, off, val),
1316 .memory => {
1317 return self.fail(src, "TODO implement setRegOrMem for memory", .{});
10511318 },
10521319 else => unreachable,
10531320 }
10541321 }
10551322
1056 fn genSetReg(self: *Self, src: usize, reg: Register, mcv: MCValue) error{ CodegenFail, OutOfMemory }!void {
1323 fn genSetStack(self: *Self, src: usize, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
10571324 switch (arch) {
10581325 .x86_64 => switch (mcv) {
10591326 .dead => unreachable,
1327 .ptr_stack_offset => unreachable,
1328 .ptr_embedded_in_code => unreachable,
10601329 .unreach, .none => return, // Nothing to do.
1330 .undef => {
1331 if (!self.wantSafety())
1332 return; // The already existing value will do just fine.
1333 // TODO Upgrade this to a memset call when we have that available.
1334 switch (ty.abiSize(self.target.*)) {
1335 1 => return self.genSetStack(src, ty, stack_offset, .{ .immediate = 0xaa }),
1336 2 => return self.genSetStack(src, ty, stack_offset, .{ .immediate = 0xaaaa }),
1337 4 => return self.genSetStack(src, ty, stack_offset, .{ .immediate = 0xaaaaaaaa }),
1338 8 => return self.genSetStack(src, ty, stack_offset, .{ .immediate = 0xaaaaaaaaaaaaaaaa }),
1339 else => return self.fail(src, "TODO implement memset", .{}),
1340 }
1341 },
1342 .compare_flags_unsigned => |op| {
1343 return self.fail(src, "TODO implement set stack variable with compare flags value (unsigned)", .{});
1344 },
1345 .compare_flags_signed => |op| {
1346 return self.fail(src, "TODO implement set stack variable with compare flags value (signed)", .{});
1347 },
1348 .immediate => |x_big| {
1349 const abi_size = ty.abiSize(self.target.*);
1350 const adj_off = stack_offset + abi_size;
1351 if (adj_off > 128) {
1352 return self.fail(src, "TODO implement set stack variable with large stack offset", .{});
1353 }
1354 try self.code.ensureCapacity(self.code.items.len + 8);
1355 switch (abi_size) {
1356 1 => {
1357 return self.fail(src, "TODO implement set abi_size=1 stack variable with immediate", .{});
1358 },
1359 2 => {
1360 return self.fail(src, "TODO implement set abi_size=2 stack variable with immediate", .{});
1361 },
1362 4 => {
1363 const x = @intCast(u32, x_big);
1364 // We have a positive stack offset value but we want a twos complement negative
1365 // offset from rbp, which is at the top of the stack frame.
1366 const negative_offset = @intCast(i8, -@intCast(i32, adj_off));
1367 const twos_comp = @bitCast(u8, negative_offset);
1368 // mov DWORD PTR [rbp+offset], immediate
1369 self.code.appendSliceAssumeCapacity(&[_]u8{ 0xc7, 0x45, twos_comp });
1370 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), x);
1371 },
1372 8 => {
1373 return self.fail(src, "TODO implement set abi_size=8 stack variable with immediate", .{});
1374 },
1375 else => {
1376 return self.fail(src, "TODO implement set abi_size=large stack variable with immediate", .{});
1377 },
1378 }
1379 if (x_big <= math.maxInt(u32)) {} else {
1380 return self.fail(src, "TODO implement set stack variable with large immediate", .{});
1381 }
1382 },
1383 .embedded_in_code => |code_offset| {
1384 return self.fail(src, "TODO implement set stack variable from embedded_in_code", .{});
1385 },
1386 .register => |reg| {
1387 const abi_size = ty.abiSize(self.target.*);
1388 const adj_off = stack_offset + abi_size;
1389 try self.code.ensureCapacity(self.code.items.len + 7);
1390 self.rex(.{ .w = reg.size() == 64, .b = reg.isExtended() });
1391 const reg_id: u8 = @truncate(u3, reg.id());
1392 if (adj_off <= 128) {
1393 // example: 48 89 55 7f mov QWORD PTR [rbp+0x7f],rdx
1394 const RM = @as(u8, 0b01_000_101) | (reg_id << 3);
1395 const negative_offset = @intCast(i8, -@intCast(i32, adj_off));
1396 const twos_comp = @bitCast(u8, negative_offset);
1397 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x89, RM, twos_comp });
1398 } else if (adj_off <= 2147483648) {
1399 // example: 48 89 95 80 00 00 00 mov QWORD PTR [rbp+0x80],rdx
1400 const RM = @as(u8, 0b10_000_101) | (reg_id << 3);
1401 const negative_offset = @intCast(i32, -@intCast(i33, adj_off));
1402 const twos_comp = @bitCast(u32, negative_offset);
1403 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x89, RM });
1404 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), twos_comp);
1405 } else {
1406 return self.fail(src, "stack offset too large", .{});
1407 }
1408 },
1409 .memory => |vaddr| {
1410 return self.fail(src, "TODO implement set stack variable from memory vaddr", .{});
1411 },
1412 .stack_offset => |off| {
1413 if (stack_offset == off)
1414 return; // Copy stack variable to itself; nothing to do.
1415 return self.fail(src, "TODO implement copy stack variable to stack variable", .{});
1416 },
1417 },
1418 else => return self.fail(src, "TODO implement getSetStack for {}", .{self.target.cpu.arch}),
1419 }
1420 }
1421
1422 fn genSetReg(self: *Self, src: usize, reg: Register, mcv: MCValue) InnerError!void {
1423 switch (arch) {
1424 .x86_64 => switch (mcv) {
1425 .dead => unreachable,
1426 .ptr_stack_offset => unreachable,
1427 .ptr_embedded_in_code => unreachable,
1428 .unreach, .none => return, // Nothing to do.
1429 .undef => {
1430 if (!self.wantSafety())
1431 return; // The already existing value will do just fine.
1432 // Write the debug undefined value.
1433 switch (reg.size()) {
1434 8 => return self.genSetReg(src, reg, .{ .immediate = 0xaa }),
1435 16 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaa }),
1436 32 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaaaaaa }),
1437 64 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaaaaaaaaaaaaaa }),
1438 else => unreachable,
1439 }
1440 },
10611441 .compare_flags_unsigned => |op| {
10621442 try self.code.ensureCapacity(self.code.items.len + 3);
1063 self.rex(.{ .b = reg.isExtended(), .w = reg.size() == 64 });
1443 // TODO audit this codegen: we force w = true here to make
1444 // the value affect the big register
1445 self.rex(.{ .b = reg.isExtended(), .w = true });
10641446 const opcode: u8 = switch (op) {
10651447 .gte => 0x93,
10661448 .gt => 0x97,
......@@ -1076,9 +1458,6 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
10761458 return self.fail(src, "TODO set register with compare flags value (signed)", .{});
10771459 },
10781460 .immediate => |x| {
1079 if (reg.size() != 64) {
1080 return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
1081 }
10821461 // 32-bit moves zero-extend to 64-bit, so xoring the 32-bit
10831462 // register is the fastest way to zero a register.
10841463 if (x == 0) {
......@@ -1131,16 +1510,13 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
11311510 //
11321511 // In this case, the encoding of the REX byte is 0b0100100B
11331512 try self.code.ensureCapacity(self.code.items.len + 10);
1134 self.rex(.{ .w = true, .b = reg.isExtended() });
1513 self.rex(.{ .w = reg.size() == 64, .b = reg.isExtended() });
11351514 self.code.items.len += 9;
11361515 self.code.items[self.code.items.len - 9] = 0xB8 | @as(u8, reg.id() & 0b111);
11371516 const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8];
11381517 mem.writeIntLittle(u64, imm_ptr, x);
11391518 },
11401519 .embedded_in_code => |code_offset| {
1141 if (reg.size() != 64) {
1142 return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
1143 }
11441520 // We need the offset from RIP in a signed i32 twos complement.
11451521 // The instruction is 7 bytes long and RIP points to the next instruction.
11461522 try self.code.ensureCapacity(self.code.items.len + 7);
......@@ -1148,7 +1524,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
11481524 // but the operation size is unchanged. Since we're using a disp32, we want mode 0 and lower three
11491525 // bits as five.
11501526 // REX 0x8D 0b00RRR101, where RRR is the lower three bits of the id.
1151 self.rex(.{ .w = true, .b = reg.isExtended() });
1527 self.rex(.{ .w = reg.size() == 64, .b = reg.isExtended() });
11521528 self.code.items.len += 6;
11531529 const rip = self.code.items.len;
11541530 const big_offset = @intCast(i64, code_offset) - @intCast(i64, rip);
......@@ -1160,12 +1536,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
11601536 },
11611537 .register => |src_reg| {
11621538 // If the registers are the same, nothing to do.
1163 if (src_reg == reg)
1539 if (src_reg.id() == reg.id())
11641540 return;
11651541
1166 if (reg.size() != 64) {
1167 return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
1168 }
11691542 // This is a variant of 8B /r. Since we're using 64-bit moves, we require a REX.
11701543 // This is thus three bytes: REX 0x8B R/M.
11711544 // If the destination is extended, the R field must be 1.
......@@ -1173,14 +1546,11 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
11731546 // Since the register is being accessed directly, the R/M mode is three. The reg field (the middle
11741547 // three bits) contain the destination, and the R/M field (the lower three bits) contain the source.
11751548 try self.code.ensureCapacity(self.code.items.len + 3);
1176 self.rex(.{ .w = true, .r = reg.isExtended(), .b = src_reg.isExtended() });
1549 self.rex(.{ .w = reg.size() == 64, .r = reg.isExtended(), .b = src_reg.isExtended() });
11771550 const R = 0xC0 | (@as(u8, reg.id() & 0b111) << 3) | @as(u8, src_reg.id() & 0b111);
11781551 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, R });
11791552 },
11801553 .memory => |x| {
1181 if (reg.size() != 64) {
1182 return self.fail(src, "TODO decide whether to implement non-64-bit loads", .{});
1183 }
11841554 if (x <= math.maxInt(u32)) {
11851555 // Moving from memory to a register is a variant of `8B /r`.
11861556 // Since we're using 64-bit moves, we require a REX.
......@@ -1190,7 +1560,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
11901560 // 0b00RRR100, where RRR is the lower three bits of the register ID.
11911561 // The instruction is thus eight bytes; REX 0x8B 0b00RRR100 0x25 followed by a four-byte disp32.
11921562 try self.code.ensureCapacity(self.code.items.len + 8);
1193 self.rex(.{ .w = true, .b = reg.isExtended() });
1563 self.rex(.{ .w = reg.size() == 64, .b = reg.isExtended() });
11941564 self.code.appendSliceAssumeCapacity(&[_]u8{
11951565 0x8B,
11961566 0x04 | (@as(u8, reg.id() & 0b111) << 3), // R
......@@ -1218,7 +1588,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12181588 // is no way to possibly encode it. This means that RSP, RBP, R12, and R13 cannot be used with
12191589 // this instruction.
12201590 const id3 = @truncate(u3, reg.id());
1221 std.debug.assert(id3 != 4 and id3 != 5);
1591 assert(id3 != 4 and id3 != 5);
12221592
12231593 // Rather than duplicate the logic used for the move, we just use a self-call with a new MCValue.
12241594 try self.genSetReg(src, reg, MCValue{ .immediate = x });
......@@ -1233,14 +1603,34 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12331603 //
12341604 // Furthermore, if this is an extended register, both B and R must be set in the REX byte, as *both*
12351605 // register operands need to be marked as extended.
1236 self.rex(.{ .w = true, .b = reg.isExtended(), .r = reg.isExtended() });
1606 self.rex(.{ .w = reg.size() == 64, .b = reg.isExtended(), .r = reg.isExtended() });
12371607 const RM = (@as(u8, reg.id() & 0b111) << 3) | @truncate(u3, reg.id());
12381608 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, RM });
12391609 }
12401610 }
12411611 },
1242 .stack_offset => |off| {
1243 return self.fail(src, "TODO implement genSetReg for stack variables", .{});
1612 .stack_offset => |unadjusted_off| {
1613 try self.code.ensureCapacity(self.code.items.len + 7);
1614 const size_bytes = @divExact(reg.size(), 8);
1615 const off = unadjusted_off + size_bytes;
1616 self.rex(.{ .w = reg.size() == 64, .r = reg.isExtended() });
1617 const reg_id: u8 = @truncate(u3, reg.id());
1618 if (off <= 128) {
1619 // Example: 48 8b 4d 7f mov rcx,QWORD PTR [rbp+0x7f]
1620 const RM = @as(u8, 0b01_000_101) | (reg_id << 3);
1621 const negative_offset = @intCast(i8, -@intCast(i32, off));
1622 const twos_comp = @bitCast(u8, negative_offset);
1623 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8b, RM, twos_comp });
1624 } else if (off <= 2147483648) {
1625 // Example: 48 8b 8d 80 00 00 00 mov rcx,QWORD PTR [rbp+0x80]
1626 const RM = @as(u8, 0b10_000_101) | (reg_id << 3);
1627 const negative_offset = @intCast(i32, -@intCast(i33, off));
1628 const twos_comp = @bitCast(u32, negative_offset);
1629 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8b, RM });
1630 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), twos_comp);
1631 } else {
1632 return self.fail(src, "stack offset too large", .{});
1633 }
12441634 },
12451635 },
12461636 else => return self.fail(src, "TODO implement getSetReg for {}", .{self.target.cpu.arch}),
......@@ -1279,24 +1669,6 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12791669 }
12801670 }
12811671
1282 /// Does not "move" the instruction.
1283 fn copyToNewRegister(self: *Self, inst: *ir.Inst) !MCValue {
1284 const branch = &self.branch_stack.items[self.branch_stack.items.len - 1];
1285 try branch.registers.ensureCapacity(self.gpa, branch.registers.items().len + 1);
1286 try branch.inst_table.ensureCapacity(self.gpa, branch.inst_table.items().len + 1);
1287
1288 const free_index = @ctz(FreeRegInt, branch.free_registers);
1289 if (free_index >= callee_preserved_regs.len)
1290 return self.fail(inst.src, "TODO implement spilling register to stack", .{});
1291 branch.free_registers &= ~(@as(FreeRegInt, 1) << free_index);
1292 const reg = callee_preserved_regs[free_index];
1293 branch.registers.putAssumeCapacityNoClobber(reg, .{ .inst = inst });
1294 const old_mcv = branch.inst_table.get(inst).?;
1295 const new_mcv: MCValue = .{ .register = reg };
1296 try self.genSetReg(inst.src, reg, old_mcv);
1297 return new_mcv;
1298 }
1299
13001672 /// If the MCValue is an immediate, and it does not fit within this type,
13011673 /// we put it in a register.
13021674 /// A potential opportunity for future optimization here would be keeping track
......@@ -1324,6 +1696,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
13241696 }
13251697
13261698 fn genTypedValue(self: *Self, src: usize, typed_value: TypedValue) !MCValue {
1699 if (typed_value.val.isUndef())
1700 return MCValue.undef;
13271701 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
13281702 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
13291703 switch (typed_value.ty.zigTypeTag()) {
......@@ -1398,11 +1772,16 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
13981772 for (param_types) |ty, i| {
13991773 switch (ty.zigTypeTag()) {
14001774 .Bool, .Int => {
1775 const param_size = @intCast(u32, ty.abiSize(self.target.*));
14011776 if (next_int_reg >= c_abi_int_param_regs.len) {
14021777 result.args[i] = .{ .stack_offset = next_stack_offset };
1403 next_stack_offset += @intCast(u32, ty.abiSize(self.target.*));
1778 next_stack_offset += param_size;
14041779 } else {
1405 result.args[i] = .{ .register = c_abi_int_param_regs[next_int_reg] };
1780 const aliased_reg = registerAlias(
1781 c_abi_int_param_regs[next_int_reg],
1782 param_size,
1783 );
1784 result.args[i] = .{ .register = aliased_reg };
14061785 next_int_reg += 1;
14071786 }
14081787 },
......@@ -1426,7 +1805,9 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14261805 .x86_64 => switch (cc) {
14271806 .Naked => unreachable,
14281807 .Unspecified, .C => {
1429 result.return_value = .{ .register = c_abi_int_return_regs[0] };
1808 const ret_ty_size = @intCast(u32, ret_ty.abiSize(self.target.*));
1809 const aliased_reg = registerAlias(c_abi_int_return_regs[0], ret_ty_size);
1810 result.return_value = .{ .register = aliased_reg };
14301811 },
14311812 else => return self.fail(src, "TODO implement function return values for {}", .{cc}),
14321813 },
......@@ -1435,6 +1816,16 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14351816 return result;
14361817 }
14371818
1819 /// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
1820 fn wantSafety(self: *Self) bool {
1821 return switch (self.bin_file.base.options.optimize_mode) {
1822 .Debug => true,
1823 .ReleaseSafe => true,
1824 .ReleaseFast => false,
1825 .ReleaseSmall => false,
1826 };
1827 }
1828
14381829 fn fail(self: *Self, src: usize, comptime format: []const u8, args: anytype) error{ CodegenFail, OutOfMemory } {
14391830 @setCold(true);
14401831 assert(self.err_msg == null);
......@@ -1463,5 +1854,19 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14631854 fn parseRegName(name: []const u8) ?Register {
14641855 return std.meta.stringToEnum(Register, name);
14651856 }
1857
1858 fn registerAlias(reg: Register, size_bytes: u32) Register {
1859 switch (arch) {
1860 // For x86_64 we have to pick a smaller register alias depending on abi size.
1861 .x86_64 => switch (size_bytes) {
1862 1 => return reg.to8(),
1863 2 => return reg.to16(),
1864 4 => return reg.to32(),
1865 8 => return reg.to64(),
1866 else => unreachable,
1867 },
1868 else => return reg,
1869 }
1870 }
14661871 };
14671872}
src-self-hosted/codegen/x86_64.zig+20
......@@ -81,6 +81,26 @@ pub const Register = enum(u8) {
8181 else => null,
8282 };
8383 }
84
85 /// Convert from any register to its 64 bit alias.
86 pub fn to64(self: Register) Register {
87 return @intToEnum(Register, self.id());
88 }
89
90 /// Convert from any register to its 32 bit alias.
91 pub fn to32(self: Register) Register {
92 return @intToEnum(Register, @as(u8, self.id()) + 16);
93 }
94
95 /// Convert from any register to its 16 bit alias.
96 pub fn to16(self: Register) Register {
97 return @intToEnum(Register, @as(u8, self.id()) + 32);
98 }
99
100 /// Convert from any register to its 8 bit alias.
101 pub fn to8(self: Register) Register {
102 return @intToEnum(Register, @as(u8, self.id()) + 48);
103 }
84104};
85105
86106// zig fmt: on
src-self-hosted/ir.zig+9-2
......@@ -67,9 +67,14 @@ pub const Inst = struct {
6767 constant,
6868 isnonnull,
6969 isnull,
70 /// Read a value from a pointer.
71 load,
7072 ptrtoint,
73 ref,
7174 ret,
7275 retvoid,
76 /// Write a value to a pointer. LHS is pointer, RHS is value.
77 store,
7378 sub,
7479 unreach,
7580 not,
......@@ -85,6 +90,7 @@ pub const Inst = struct {
8590 .breakpoint,
8691 => NoOp,
8792
93 .ref,
8894 .ret,
8995 .bitcast,
9096 .not,
......@@ -93,6 +99,7 @@ pub const Inst = struct {
9399 .ptrtoint,
94100 .floatcast,
95101 .intcast,
102 .load,
96103 => UnOp,
97104
98105 .add,
......@@ -103,6 +110,7 @@ pub const Inst = struct {
103110 .cmp_gte,
104111 .cmp_gt,
105112 .cmp_neq,
113 .store,
106114 => BinOp,
107115
108116 .assembly => Assembly,
......@@ -157,8 +165,7 @@ pub const Inst = struct {
157165
158166 /// Returns `null` if runtime-known.
159167 pub fn value(base: *Inst) ?Value {
160 if (base.ty.onePossibleValue())
161 return Value.initTag(.the_one_possible_value);
168 if (base.ty.onePossibleValue()) |opv| return opv;
162169
163170 const inst = base.cast(Constant) orelse return null;
164171 return inst.val;
src-self-hosted/link.zig+63-57
......@@ -16,6 +16,7 @@ pub const Options = struct {
1616 output_mode: std.builtin.OutputMode,
1717 link_mode: std.builtin.LinkMode,
1818 object_format: std.builtin.ObjectFormat,
19 optimize_mode: std.builtin.Mode,
1920 /// Used for calculating how much space to reserve for symbols in case the binary file
2021 /// does not already have a symbol table.
2122 symbol_count_hint: u64 = 32,
......@@ -66,6 +67,7 @@ pub fn writeFilePath(
6667 .link_mode = module.link_mode,
6768 .object_format = module.object_format,
6869 .symbol_count_hint = module.decls.items.len,
70 .optimize_mode = module.optimize_mode,
6971 };
7072 const af = try dir.atomicFile(sub_path, .{ .mode = determineMode(options) });
7173 defer af.deinit();
......@@ -88,9 +90,12 @@ pub fn writeFilePath(
8890
8991fn openCFile(allocator: *Allocator, file: fs.File, options: Options) !File.C {
9092 return File.C{
93 .base = .{
94 .tag = .c,
95 .options = options,
96 },
9197 .allocator = allocator,
9298 .file = file,
93 .options = options,
9499 .main = std.ArrayList(u8).init(allocator),
95100 .header = std.ArrayList(u8).init(allocator),
96101 .constants = std.ArrayList(u8).init(allocator),
......@@ -114,6 +119,8 @@ pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !File
114119
115120pub const File = struct {
116121 tag: Tag,
122 options: Options,
123
117124 pub fn cast(base: *File, comptime T: type) ?*T {
118125 if (base.tag != T.base_tag)
119126 return null;
......@@ -123,47 +130,47 @@ pub const File = struct {
123130
124131 pub fn makeWritable(base: *File, dir: fs.Dir, sub_path: []const u8) !void {
125132 switch (base.tag) {
126 .Elf => return @fieldParentPtr(Elf, "base", base).makeWritable(dir, sub_path),
127 .C => {},
133 .elf => return @fieldParentPtr(Elf, "base", base).makeWritable(dir, sub_path),
134 .c => {},
128135 }
129136 }
130137
131138 pub fn makeExecutable(base: *File) !void {
132139 switch (base.tag) {
133 .Elf => return @fieldParentPtr(Elf, "base", base).makeExecutable(),
134 .C => unreachable,
140 .elf => return @fieldParentPtr(Elf, "base", base).makeExecutable(),
141 .c => unreachable,
135142 }
136143 }
137144
138145 pub fn updateDecl(base: *File, module: *Module, decl: *Module.Decl) !void {
139146 switch (base.tag) {
140 .Elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl),
141 .C => return @fieldParentPtr(C, "base", base).updateDecl(module, decl),
147 .elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl),
148 .c => return @fieldParentPtr(C, "base", base).updateDecl(module, decl),
142149 }
143150 }
144151
145152 pub fn allocateDeclIndexes(base: *File, decl: *Module.Decl) !void {
146153 switch (base.tag) {
147 .Elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl),
148 .C => {},
154 .elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl),
155 .c => {},
149156 }
150157 }
151158
152159 pub fn deinit(base: *File) void {
153160 switch (base.tag) {
154 .Elf => @fieldParentPtr(Elf, "base", base).deinit(),
155 .C => @fieldParentPtr(C, "base", base).deinit(),
161 .elf => @fieldParentPtr(Elf, "base", base).deinit(),
162 .c => @fieldParentPtr(C, "base", base).deinit(),
156163 }
157164 }
158165
159166 pub fn destroy(base: *File) void {
160167 switch (base.tag) {
161 .Elf => {
168 .elf => {
162169 const parent = @fieldParentPtr(Elf, "base", base);
163170 parent.deinit();
164171 parent.allocator.destroy(parent);
165172 },
166 .C => {
173 .c => {
167174 const parent = @fieldParentPtr(C, "base", base);
168175 parent.deinit();
169176 parent.allocator.destroy(parent);
......@@ -173,29 +180,22 @@ pub const File = struct {
173180
174181 pub fn flush(base: *File) !void {
175182 try switch (base.tag) {
176 .Elf => @fieldParentPtr(Elf, "base", base).flush(),
177 .C => @fieldParentPtr(C, "base", base).flush(),
183 .elf => @fieldParentPtr(Elf, "base", base).flush(),
184 .c => @fieldParentPtr(C, "base", base).flush(),
178185 };
179186 }
180187
181188 pub fn freeDecl(base: *File, decl: *Module.Decl) void {
182189 switch (base.tag) {
183 .Elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl),
184 .C => unreachable,
190 .elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl),
191 .c => unreachable,
185192 }
186193 }
187194
188195 pub fn errorFlags(base: *File) ErrorFlags {
189196 return switch (base.tag) {
190 .Elf => @fieldParentPtr(Elf, "base", base).error_flags,
191 .C => return .{ .no_entry_point_found = false },
192 };
193 }
194
195 pub fn options(base: *File) Options {
196 return switch (base.tag) {
197 .Elf => @fieldParentPtr(Elf, "base", base).options,
198 .C => @fieldParentPtr(C, "base", base).options,
197 .elf => @fieldParentPtr(Elf, "base", base).error_flags,
198 .c => return .{ .no_entry_point_found = false },
199199 };
200200 }
201201
......@@ -207,14 +207,14 @@ pub const File = struct {
207207 exports: []const *Module.Export,
208208 ) !void {
209209 switch (base.tag) {
210 .Elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
211 .C => return {},
210 .elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
211 .c => return {},
212212 }
213213 }
214214
215215 pub const Tag = enum {
216 Elf,
217 C,
216 elf,
217 c,
218218 };
219219
220220 pub const ErrorFlags = struct {
......@@ -222,15 +222,15 @@ pub const File = struct {
222222 };
223223
224224 pub const C = struct {
225 pub const base_tag: Tag = .C;
226 base: File = File{ .tag = base_tag },
225 pub const base_tag: Tag = .c;
226
227 base: File,
227228
228229 allocator: *Allocator,
229230 header: std.ArrayList(u8),
230231 constants: std.ArrayList(u8),
231232 main: std.ArrayList(u8),
232233 file: ?fs.File,
233 options: Options,
234234 called: std.StringHashMap(void),
235235 need_stddef: bool = false,
236236 need_stdint: bool = false,
......@@ -294,13 +294,13 @@ pub const File = struct {
294294 };
295295
296296 pub const Elf = struct {
297 pub const base_tag: Tag = .Elf;
298 base: File = File{ .tag = base_tag },
297 pub const base_tag: Tag = .elf;
298
299 base: File,
299300
300301 allocator: *Allocator,
301302 file: ?fs.File,
302303 owns_file_handle: bool,
303 options: Options,
304304 ptr_width: enum { p32, p64 },
305305
306306 /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
......@@ -460,13 +460,13 @@ pub const File = struct {
460460 self.file = try dir.createFile(sub_path, .{
461461 .truncate = false,
462462 .read = true,
463 .mode = determineMode(self.options),
463 .mode = determineMode(self.base.options),
464464 });
465465 }
466466
467467 /// Returns end pos of collision, if any.
468468 fn detectAllocCollision(self: *Elf, start: u64, size: u64) ?u64 {
469 const small_ptr = self.options.target.cpu.arch.ptrBitWidth() == 32;
469 const small_ptr = self.base.options.target.cpu.arch.ptrBitWidth() == 32;
470470 const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr);
471471 if (start < ehdr_size)
472472 return ehdr_size;
......@@ -569,7 +569,7 @@ pub const File = struct {
569569 };
570570 if (self.phdr_load_re_index == null) {
571571 self.phdr_load_re_index = @intCast(u16, self.program_headers.items.len);
572 const file_size = self.options.program_code_size_hint;
572 const file_size = self.base.options.program_code_size_hint;
573573 const p_align = 0x1000;
574574 const off = self.findFreeSpace(file_size, p_align);
575575 std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
......@@ -588,7 +588,7 @@ pub const File = struct {
588588 }
589589 if (self.phdr_got_index == null) {
590590 self.phdr_got_index = @intCast(u16, self.program_headers.items.len);
591 const file_size = @as(u64, ptr_size) * self.options.symbol_count_hint;
591 const file_size = @as(u64, ptr_size) * self.base.options.symbol_count_hint;
592592 // We really only need ptr alignment but since we are using PROGBITS, linux requires
593593 // page align.
594594 const p_align = 0x1000;
......@@ -671,7 +671,7 @@ pub const File = struct {
671671 self.symtab_section_index = @intCast(u16, self.sections.items.len);
672672 const min_align: u16 = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym);
673673 const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym);
674 const file_size = self.options.symbol_count_hint * each_size;
674 const file_size = self.base.options.symbol_count_hint * each_size;
675675 const off = self.findFreeSpace(file_size, min_align);
676676 std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
677677
......@@ -726,7 +726,7 @@ pub const File = struct {
726726
727727 /// Commit pending changes and write headers.
728728 pub fn flush(self: *Elf) !void {
729 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
729 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
730730
731731 // Unfortunately these have to be buffered and done at the end because ELF does not allow
732732 // mixing local and global symbols within a symbol table.
......@@ -845,7 +845,7 @@ pub const File = struct {
845845 }
846846 self.shdr_table_dirty = false;
847847 }
848 if (self.entry_addr == null and self.options.output_mode == .Exe) {
848 if (self.entry_addr == null and self.base.options.output_mode == .Exe) {
849849 std.log.debug(.link, "no_entry_point_found = true\n", .{});
850850 self.error_flags.no_entry_point_found = true;
851851 } else {
......@@ -875,7 +875,7 @@ pub const File = struct {
875875 };
876876 index += 1;
877877
878 const endian = self.options.target.cpu.arch.endian();
878 const endian = self.base.options.target.cpu.arch.endian();
879879 hdr_buf[index] = switch (endian) {
880880 .Little => elf.ELFDATA2LSB,
881881 .Big => elf.ELFDATA2MSB,
......@@ -893,10 +893,10 @@ pub const File = struct {
893893
894894 assert(index == 16);
895895
896 const elf_type = switch (self.options.output_mode) {
896 const elf_type = switch (self.base.options.output_mode) {
897897 .Exe => elf.ET.EXEC,
898898 .Obj => elf.ET.REL,
899 .Lib => switch (self.options.link_mode) {
899 .Lib => switch (self.base.options.link_mode) {
900900 .Static => elf.ET.REL,
901901 .Dynamic => elf.ET.DYN,
902902 },
......@@ -904,7 +904,7 @@ pub const File = struct {
904904 mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(elf_type), endian);
905905 index += 2;
906906
907 const machine = self.options.target.cpu.arch.toElfMachine();
907 const machine = self.base.options.target.cpu.arch.toElfMachine();
908908 mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(machine), endian);
909909 index += 2;
910910
......@@ -1216,7 +1216,7 @@ pub const File = struct {
12161216 },
12171217 };
12181218
1219 const required_alignment = typed_value.ty.abiAlignment(self.options.target);
1219 const required_alignment = typed_value.ty.abiAlignment(self.base.options.target);
12201220
12211221 const stt_bits: u8 = switch (typed_value.ty.zigTypeTag()) {
12221222 .Fn => elf.STT_FUNC,
......@@ -1361,9 +1361,9 @@ pub const File = struct {
13611361 }
13621362
13631363 fn writeProgHeader(self: *Elf, index: usize) !void {
1364 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1364 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
13651365 const offset = self.program_headers.items[index].p_offset;
1366 switch (self.options.target.cpu.arch.ptrBitWidth()) {
1366 switch (self.base.options.target.cpu.arch.ptrBitWidth()) {
13671367 32 => {
13681368 var phdr = [1]elf.Elf32_Phdr{progHeaderTo32(self.program_headers.items[index])};
13691369 if (foreign_endian) {
......@@ -1383,9 +1383,9 @@ pub const File = struct {
13831383 }
13841384
13851385 fn writeSectHeader(self: *Elf, index: usize) !void {
1386 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1386 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
13871387 const offset = self.sections.items[index].sh_offset;
1388 switch (self.options.target.cpu.arch.ptrBitWidth()) {
1388 switch (self.base.options.target.cpu.arch.ptrBitWidth()) {
13891389 32 => {
13901390 var shdr: [1]elf.Elf32_Shdr = undefined;
13911391 shdr[0] = sectHeaderTo32(self.sections.items[index]);
......@@ -1433,7 +1433,7 @@ pub const File = struct {
14331433
14341434 self.offset_table_count_dirty = false;
14351435 }
1436 const endian = self.options.target.cpu.arch.endian();
1436 const endian = self.base.options.target.cpu.arch.endian();
14371437 const off = shdr.sh_offset + @as(u64, entry_size) * index;
14381438 switch (self.ptr_width) {
14391439 .p32 => {
......@@ -1475,7 +1475,7 @@ pub const File = struct {
14751475 syms_sect.sh_size = needed_size; // anticipating adding the global symbols later
14761476 self.shdr_table_dirty = true; // TODO look into only writing one section
14771477 }
1478 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1478 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
14791479 switch (self.ptr_width) {
14801480 .p32 => {
14811481 var sym = [1]elf.Elf32_Sym{
......@@ -1511,7 +1511,7 @@ pub const File = struct {
15111511 .p32 => @sizeOf(elf.Elf32_Sym),
15121512 .p64 => @sizeOf(elf.Elf64_Sym),
15131513 };
1514 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1514 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
15151515 const global_syms_off = syms_sect.sh_offset + self.local_symbols.items.len * sym_size;
15161516 switch (self.ptr_width) {
15171517 .p32 => {
......@@ -1577,9 +1577,12 @@ pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !Fi
15771577 }
15781578
15791579 var self: File.Elf = .{
1580 .base = .{
1581 .tag = .elf,
1582 .options = options,
1583 },
15801584 .allocator = allocator,
15811585 .file = file,
1582 .options = options,
15831586 .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
15841587 32 => .p32,
15851588 64 => .p64,
......@@ -1637,10 +1640,13 @@ fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !Fil
16371640 .raw => return error.IncrFailed,
16381641 }
16391642 var self: File.Elf = .{
1643 .base = .{
1644 .tag = .elf,
1645 .options = options,
1646 },
16401647 .allocator = allocator,
16411648 .file = file,
16421649 .owns_file_handle = false,
1643 .options = options,
16441650 .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
16451651 32 => .p32,
16461652 64 => .p64,
src-self-hosted/type.zig+75-12
......@@ -380,7 +380,7 @@ pub const Type = extern union {
380380 },
381381 .single_mut_pointer => {
382382 const payload = @fieldParentPtr(Payload.SingleMutPointer, "base", ty.ptr_otherwise);
383 try out_stream.writeAll("* ");
383 try out_stream.writeAll("*");
384384 ty = payload.pointee_type;
385385 continue;
386386 },
......@@ -803,6 +803,58 @@ pub const Type = extern union {
803803 };
804804 }
805805
806 pub fn isVolatilePtr(self: Type) bool {
807 return switch (self.tag()) {
808 .u8,
809 .i8,
810 .u16,
811 .i16,
812 .u32,
813 .i32,
814 .u64,
815 .i64,
816 .usize,
817 .isize,
818 .c_short,
819 .c_ushort,
820 .c_int,
821 .c_uint,
822 .c_long,
823 .c_ulong,
824 .c_longlong,
825 .c_ulonglong,
826 .c_longdouble,
827 .f16,
828 .f32,
829 .f64,
830 .f128,
831 .c_void,
832 .bool,
833 .void,
834 .type,
835 .anyerror,
836 .comptime_int,
837 .comptime_float,
838 .noreturn,
839 .@"null",
840 .@"undefined",
841 .array,
842 .array_u8_sentinel_0,
843 .fn_noreturn_no_args,
844 .fn_void_no_args,
845 .fn_naked_noreturn_no_args,
846 .fn_ccc_void_no_args,
847 .function,
848 .int_unsigned,
849 .int_signed,
850 .single_mut_pointer,
851 .single_const_pointer,
852 .single_const_pointer_to_comptime_int,
853 .const_slice_u8,
854 => false,
855 };
856 }
857
806858 /// Asserts the type is a pointer or array type.
807859 pub fn elemType(self: Type) Type {
808860 return switch (self.tag()) {
......@@ -1601,7 +1653,7 @@ pub const Type = extern union {
16011653 };
16021654 }
16031655
1604 pub fn onePossibleValue(self: Type) bool {
1656 pub fn onePossibleValue(self: Type) ?Value {
16051657 var ty = self;
16061658 while (true) switch (ty.tag()) {
16071659 .f16,
......@@ -1640,21 +1692,32 @@ pub const Type = extern union {
16401692 .single_const_pointer_to_comptime_int,
16411693 .array_u8_sentinel_0,
16421694 .const_slice_u8,
1643 => return false,
1644
16451695 .c_void,
1646 .void,
1647 .noreturn,
1648 .@"null",
1649 .@"undefined",
1650 => return true,
1696 => return null,
1697
1698 .void => return Value.initTag(.void_value),
1699 .noreturn => return Value.initTag(.unreachable_value),
1700 .@"null" => return Value.initTag(.null_value),
1701 .@"undefined" => return Value.initTag(.undef),
16511702
1652 .int_unsigned => return ty.cast(Payload.IntUnsigned).?.bits == 0,
1653 .int_signed => return ty.cast(Payload.IntSigned).?.bits == 0,
1703 .int_unsigned => {
1704 if (ty.cast(Payload.IntUnsigned).?.bits == 0) {
1705 return Value.initTag(.zero);
1706 } else {
1707 return null;
1708 }
1709 },
1710 .int_signed => {
1711 if (ty.cast(Payload.IntSigned).?.bits == 0) {
1712 return Value.initTag(.zero);
1713 } else {
1714 return null;
1715 }
1716 },
16541717 .array => {
16551718 const array = ty.cast(Payload.Array).?;
16561719 if (array.len == 0)
1657 return true;
1720 return Value.initTag(.empty_array);
16581721 ty = array.elem_type;
16591722 continue;
16601723 },
src-self-hosted/value.zig+50-22
......@@ -63,7 +63,9 @@ pub const Value = extern union {
6363
6464 undef,
6565 zero,
66 the_one_possible_value, // when the type only has one possible value
66 void_value,
67 unreachable_value,
68 empty_array,
6769 null_value,
6870 bool_true,
6971 bool_false, // See last_no_payload_tag below.
......@@ -164,7 +166,9 @@ pub const Value = extern union {
164166 .const_slice_u8_type,
165167 .undef,
166168 .zero,
167 .the_one_possible_value,
169 .void_value,
170 .unreachable_value,
171 .empty_array,
168172 .null_value,
169173 .bool_true,
170174 .bool_false,
......@@ -285,7 +289,8 @@ pub const Value = extern union {
285289 .null_value => return out_stream.writeAll("null"),
286290 .undef => return out_stream.writeAll("undefined"),
287291 .zero => return out_stream.writeAll("0"),
288 .the_one_possible_value => return out_stream.writeAll("(one possible value)"),
292 .void_value => return out_stream.writeAll("{}"),
293 .unreachable_value => return out_stream.writeAll("unreachable"),
289294 .bool_true => return out_stream.writeAll("true"),
290295 .bool_false => return out_stream.writeAll("false"),
291296 .ty => return val.cast(Payload.Ty).?.ty.format("", options, out_stream),
......@@ -312,6 +317,7 @@ pub const Value = extern union {
312317 try out_stream.print("&[{}] ", .{elem_ptr.index});
313318 val = elem_ptr.array_ptr;
314319 },
320 .empty_array => return out_stream.writeAll(".{}"),
315321 .bytes => return std.zig.renderStringLiteral(self.cast(Payload.Bytes).?.data, out_stream),
316322 .repeated => {
317323 try out_stream.writeAll("(repeated) ");
......@@ -388,7 +394,9 @@ pub const Value = extern union {
388394
389395 .undef,
390396 .zero,
391 .the_one_possible_value,
397 .void_value,
398 .unreachable_value,
399 .empty_array,
392400 .bool_true,
393401 .bool_false,
394402 .null_value,
......@@ -460,15 +468,18 @@ pub const Value = extern union {
460468 .decl_ref,
461469 .elem_ptr,
462470 .bytes,
463 .undef,
464471 .repeated,
465472 .float_16,
466473 .float_32,
467474 .float_64,
468475 .float_128,
476 .void_value,
477 .unreachable_value,
478 .empty_array,
469479 => unreachable,
470480
471 .the_one_possible_value, // An integer with one possible value is always zero.
481 .undef => unreachable,
482
472483 .zero,
473484 .bool_false,
474485 => return BigIntMutable.init(&space.limbs, 0).toConst(),
......@@ -532,16 +543,19 @@ pub const Value = extern union {
532543 .decl_ref,
533544 .elem_ptr,
534545 .bytes,
535 .undef,
536546 .repeated,
537547 .float_16,
538548 .float_32,
539549 .float_64,
540550 .float_128,
551 .void_value,
552 .unreachable_value,
553 .empty_array,
541554 => unreachable,
542555
556 .undef => unreachable,
557
543558 .zero,
544 .the_one_possible_value, // an integer with one possible value is always zero
545559 .bool_false,
546560 => return 0,
547561
......@@ -570,7 +584,7 @@ pub const Value = extern union {
570584 .float_64 => @floatCast(T, self.cast(Payload.Float_64).?.val),
571585 .float_128 => @floatCast(T, self.cast(Payload.Float_128).?.val),
572586
573 .zero, .the_one_possible_value => 0,
587 .zero => 0,
574588 .int_u64 => @intToFloat(T, self.cast(Payload.Int_u64).?.int),
575589 // .int_i64 => @intToFloat(f128, self.cast(Payload.Int_i64).?.int),
576590 .int_i64 => @panic("TODO lld: error: undefined symbol: __floatditf"),
......@@ -637,9 +651,11 @@ pub const Value = extern union {
637651 .float_32,
638652 .float_64,
639653 .float_128,
654 .void_value,
655 .unreachable_value,
656 .empty_array,
640657 => unreachable,
641658
642 .the_one_possible_value, // an integer with one possible value is always zero
643659 .zero,
644660 .bool_false,
645661 => return 0,
......@@ -714,11 +730,13 @@ pub const Value = extern union {
714730 .float_32,
715731 .float_64,
716732 .float_128,
733 .void_value,
734 .unreachable_value,
735 .empty_array,
717736 => unreachable,
718737
719738 .zero,
720739 .undef,
721 .the_one_possible_value, // an integer with one possible value is always zero
722740 .bool_false,
723741 => return true,
724742
......@@ -797,13 +815,13 @@ pub const Value = extern union {
797815 // return Value.initPayload(&res_payload.base).copy(allocator);
798816 },
799817 32 => {
800 var res_payload = Value.Payload.Float_32{.val = self.toFloat(f32)};
818 var res_payload = Value.Payload.Float_32{ .val = self.toFloat(f32) };
801819 if (!self.eql(Value.initPayload(&res_payload.base)))
802820 return error.Overflow;
803821 return Value.initPayload(&res_payload.base).copy(allocator);
804822 },
805823 64 => {
806 var res_payload = Value.Payload.Float_64{.val = self.toFloat(f64)};
824 var res_payload = Value.Payload.Float_64{ .val = self.toFloat(f64) };
807825 if (!self.eql(Value.initPayload(&res_payload.base)))
808826 return error.Overflow;
809827 return Value.initPayload(&res_payload.base).copy(allocator);
......@@ -875,7 +893,9 @@ pub const Value = extern union {
875893 .int_i64,
876894 .int_big_positive,
877895 .int_big_negative,
878 .the_one_possible_value,
896 .empty_array,
897 .void_value,
898 .unreachable_value,
879899 => unreachable,
880900
881901 .zero => false,
......@@ -939,10 +959,12 @@ pub const Value = extern union {
939959 .bytes,
940960 .repeated,
941961 .undef,
962 .void_value,
963 .unreachable_value,
964 .empty_array,
942965 => unreachable,
943966
944967 .zero,
945 .the_one_possible_value, // an integer with one possible value is always zero
946968 .bool_false,
947969 => .eq,
948970
......@@ -964,8 +986,8 @@ pub const Value = extern union {
964986 pub fn order(lhs: Value, rhs: Value) std.math.Order {
965987 const lhs_tag = lhs.tag();
966988 const rhs_tag = rhs.tag();
967 const lhs_is_zero = lhs_tag == .zero or lhs_tag == .the_one_possible_value;
968 const rhs_is_zero = rhs_tag == .zero or rhs_tag == .the_one_possible_value;
989 const lhs_is_zero = lhs_tag == .zero;
990 const rhs_is_zero = rhs_tag == .zero;
969991 if (lhs_is_zero) return rhs.orderAgainstZero().invert();
970992 if (rhs_is_zero) return lhs.orderAgainstZero();
971993
......@@ -1071,9 +1093,11 @@ pub const Value = extern union {
10711093 .float_32,
10721094 .float_64,
10731095 .float_128,
1096 .void_value,
1097 .unreachable_value,
1098 .empty_array,
10741099 => unreachable,
10751100
1076 .the_one_possible_value => Value.initTag(.the_one_possible_value),
10771101 .ref_val => self.cast(Payload.RefVal).?.val,
10781102 .decl_ref => self.cast(Payload.DeclRef).?.decl.value(),
10791103 .elem_ptr => {
......@@ -1130,7 +1154,6 @@ pub const Value = extern union {
11301154 .single_const_pointer_to_comptime_int_type,
11311155 .const_slice_u8_type,
11321156 .zero,
1133 .the_one_possible_value,
11341157 .bool_true,
11351158 .bool_false,
11361159 .null_value,
......@@ -1147,8 +1170,12 @@ pub const Value = extern union {
11471170 .float_32,
11481171 .float_64,
11491172 .float_128,
1173 .void_value,
1174 .unreachable_value,
11501175 => unreachable,
11511176
1177 .empty_array => unreachable, // out of bounds array index
1178
11521179 .bytes => {
11531180 const int_payload = try allocator.create(Payload.Int_u64);
11541181 int_payload.* = .{ .int = self.cast(Payload.Bytes).?.data[index] };
......@@ -1175,8 +1202,7 @@ pub const Value = extern union {
11751202 return self.tag() == .undef;
11761203 }
11771204
1178 /// Valid for all types. Asserts the value is not undefined.
1179 /// `.the_one_possible_value` is reported as not null.
1205 /// Valid for all types. Asserts the value is not undefined and not unreachable.
11801206 pub fn isNull(self: Value) bool {
11811207 return switch (self.tag()) {
11821208 .ty,
......@@ -1221,7 +1247,7 @@ pub const Value = extern union {
12211247 .single_const_pointer_to_comptime_int_type,
12221248 .const_slice_u8_type,
12231249 .zero,
1224 .the_one_possible_value,
1250 .empty_array,
12251251 .bool_true,
12261252 .bool_false,
12271253 .function,
......@@ -1238,9 +1264,11 @@ pub const Value = extern union {
12381264 .float_32,
12391265 .float_64,
12401266 .float_128,
1267 .void_value,
12411268 => false,
12421269
12431270 .undef => unreachable,
1271 .unreachable_value => unreachable,
12441272 .null_value => true,
12451273 };
12461274 }
src-self-hosted/zir.zig+47-13
......@@ -183,6 +183,10 @@ pub const Inst = struct {
183183 shl,
184184 /// Integer shift-right. Arithmetic or logical depending on the signedness of the integer type.
185185 shr,
186 /// Create a const pointer type based on the element type. `*const T`
187 single_const_ptr_type,
188 /// Create a mutable pointer type based on the element type. `*T`
189 single_mut_ptr_type,
186190 /// Write a value to a pointer. For loading, see `deref`.
187191 store,
188192 /// String Literal. Makes an anonymous Decl and then takes a pointer to it.
......@@ -228,6 +232,8 @@ pub const Inst = struct {
228232 .ref,
229233 .bitcast_lvalue,
230234 .typeof,
235 .single_const_ptr_type,
236 .single_mut_ptr_type,
231237 => UnOp,
232238
233239 .add,
......@@ -242,6 +248,7 @@ pub const Inst = struct {
242248 .mulwrap,
243249 .shl,
244250 .shr,
251 .store,
245252 .sub,
246253 .subwrap,
247254 .cmp_lt,
......@@ -270,7 +277,6 @@ pub const Inst = struct {
270277 .coerce_result_block_ptr => CoerceResultBlockPtr,
271278 .compileerror => CompileError,
272279 .@"const" => Const,
273 .store => Store,
274280 .str => Str,
275281 .int => Int,
276282 .inttype => IntType,
......@@ -348,6 +354,8 @@ pub const Inst = struct {
348354 .ret_type,
349355 .shl,
350356 .shr,
357 .single_const_ptr_type,
358 .single_mut_ptr_type,
351359 .store,
352360 .str,
353361 .sub,
......@@ -545,17 +553,6 @@ pub const Inst = struct {
545553 kw_args: struct {},
546554 };
547555
548 pub const Store = struct {
549 pub const base_tag = Tag.store;
550 base: Inst,
551
552 positionals: struct {
553 ptr: *Inst,
554 value: *Inst,
555 },
556 kw_args: struct {},
557 };
558
559556 pub const Str = struct {
560557 pub const base_tag = Tag.str;
561558 base: Inst,
......@@ -745,7 +742,7 @@ pub const Inst = struct {
745742 .@"false" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_false) },
746743 .@"null" => .{ .ty = Type.initTag(.@"null"), .val = Value.initTag(.null_value) },
747744 .@"undefined" => .{ .ty = Type.initTag(.@"undefined"), .val = Value.initTag(.undef) },
748 .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.the_one_possible_value) },
745 .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.void_value) },
749746 };
750747 }
751748 };
......@@ -1601,6 +1598,21 @@ const EmitZIR = struct {
16011598 const decl = decl_ref.decl;
16021599 return try self.emitUnnamedDecl(try self.emitDeclRef(src, decl));
16031600 }
1601 if (typed_value.val.isUndef()) {
1602 const as_inst = try self.arena.allocator.create(Inst.BinOp);
1603 as_inst.* = .{
1604 .base = .{
1605 .tag = .as,
1606 .src = src,
1607 },
1608 .positionals = .{
1609 .lhs = (try self.emitType(src, typed_value.ty)).inst,
1610 .rhs = (try self.emitPrimitive(src, .@"undefined")).inst,
1611 },
1612 .kw_args = .{},
1613 };
1614 return self.emitUnnamedDecl(&as_inst.base);
1615 }
16041616 switch (typed_value.ty.zigTypeTag()) {
16051617 .Pointer => {
16061618 const ptr_elem_type = typed_value.ty.elemType();
......@@ -1837,9 +1849,12 @@ const EmitZIR = struct {
18371849 .ptrtoint => try self.emitUnOp(inst.src, new_body, inst.castTag(.ptrtoint).?, .ptrtoint),
18381850 .isnull => try self.emitUnOp(inst.src, new_body, inst.castTag(.isnull).?, .isnull),
18391851 .isnonnull => try self.emitUnOp(inst.src, new_body, inst.castTag(.isnonnull).?, .isnonnull),
1852 .load => try self.emitUnOp(inst.src, new_body, inst.castTag(.load).?, .deref),
1853 .ref => try self.emitUnOp(inst.src, new_body, inst.castTag(.ref).?, .ref),
18401854
18411855 .add => try self.emitBinOp(inst.src, new_body, inst.castTag(.add).?, .add),
18421856 .sub => try self.emitBinOp(inst.src, new_body, inst.castTag(.sub).?, .sub),
1857 .store => try self.emitBinOp(inst.src, new_body, inst.castTag(.store).?, .store),
18431858 .cmp_lt => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_lt).?, .cmp_lt),
18441859 .cmp_lte => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_lte).?, .cmp_lte),
18451860 .cmp_eq => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_eq).?, .cmp_eq),
......@@ -2103,6 +2118,25 @@ const EmitZIR = struct {
21032118 };
21042119 return self.emitUnnamedDecl(&inttype_inst.base);
21052120 },
2121 .Pointer => {
2122 if (ty.isSinglePointer()) {
2123 const inst = try self.arena.allocator.create(Inst.UnOp);
2124 const tag: Inst.Tag = if (ty.isConstPtr()) .single_const_ptr_type else .single_mut_ptr_type;
2125 inst.* = .{
2126 .base = .{
2127 .src = src,
2128 .tag = tag,
2129 },
2130 .positionals = .{
2131 .operand = (try self.emitType(src, ty.elemType())).inst,
2132 },
2133 .kw_args = .{},
2134 };
2135 return self.emitUnnamedDecl(&inst.base);
2136 } else {
2137 std.debug.panic("TODO implement emitType for {}", .{ty});
2138 }
2139 },
21062140 else => std.debug.panic("TODO implement emitType for {}", .{ty}),
21072141 },
21082142 }
src-self-hosted/zir_sema.zig+28-5
......@@ -50,6 +50,8 @@ pub fn analyzeInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!
5050 .ref => return analyzeInstRef(mod, scope, old_inst.castTag(.ref).?),
5151 .ret_ptr => return analyzeInstRetPtr(mod, scope, old_inst.castTag(.ret_ptr).?),
5252 .ret_type => return analyzeInstRetType(mod, scope, old_inst.castTag(.ret_type).?),
53 .single_const_ptr_type => return analyzeInstSingleConstPtrType(mod, scope, old_inst.castTag(.single_const_ptr_type).?),
54 .single_mut_ptr_type => return analyzeInstSingleMutPtrType(mod, scope, old_inst.castTag(.single_mut_ptr_type).?),
5355 .store => return analyzeInstStore(mod, scope, old_inst.castTag(.store).?),
5456 .str => return analyzeInstStr(mod, scope, old_inst.castTag(.str).?),
5557 .int => {
......@@ -287,8 +289,11 @@ fn analyzeInstCoerceResultPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp
287289 return mod.fail(scope, inst.base.src, "TODO implement analyzeInstCoerceResultPtr", .{});
288290}
289291
292/// Equivalent to `as(ptr_child_type(typeof(ptr)), value)`.
290293fn analyzeInstCoerceToPtrElem(mod: *Module, scope: *Scope, inst: *zir.Inst.CoerceToPtrElem) InnerError!*Inst {
291 return mod.fail(scope, inst.base.src, "TODO implement analyzeInstCoerceToPtrElem", .{});
294 const ptr = try resolveInst(mod, scope, inst.positionals.ptr);
295 const operand = try resolveInst(mod, scope, inst.positionals.value);
296 return mod.coerce(scope, ptr.ty.elemType(), operand);
292297}
293298
294299fn analyzeInstRetPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
......@@ -296,7 +301,10 @@ fn analyzeInstRetPtr(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerErr
296301}
297302
298303fn analyzeInstRef(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
299 return mod.fail(scope, inst.base.src, "TODO implement analyzeInstRef", .{});
304 const operand = try resolveInst(mod, scope, inst.positionals.operand);
305 const b = try mod.requireRuntimeBlock(scope, inst.base.src);
306 const ptr_type = try mod.singleConstPtrType(scope, inst.base.src, operand.ty);
307 return mod.addUnOp(b, inst.base.src, ptr_type, .ref, operand);
300308}
301309
302310fn analyzeInstRetType(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) InnerError!*Inst {
......@@ -333,8 +341,10 @@ fn analyzeInstAllocInferred(mod: *Module, scope: *Scope, inst: *zir.Inst.NoOp) I
333341 return mod.fail(scope, inst.base.src, "TODO implement analyzeInstAllocInferred", .{});
334342}
335343
336fn analyzeInstStore(mod: *Module, scope: *Scope, inst: *zir.Inst.Store) InnerError!*Inst {
337 return mod.fail(scope, inst.base.src, "TODO implement analyzeInstStore", .{});
344fn analyzeInstStore(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) InnerError!*Inst {
345 const ptr = try resolveInst(mod, scope, inst.positionals.lhs);
346 const value = try resolveInst(mod, scope, inst.positionals.rhs);
347 return mod.storePtr(scope, inst.base.src, ptr, value);
338348}
339349
340350fn analyzeInstParamType(mod: *Module, scope: *Scope, inst: *zir.Inst.ParamType) InnerError!*Inst {
......@@ -872,7 +882,7 @@ fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) Inn
872882fn analyzeInstComptimeOp(mod: *Module, scope: *Scope, res_type: Type, inst: *zir.Inst.BinOp, lhs_val: Value, rhs_val: Value) InnerError!*Inst {
873883 // incase rhs is 0, simply return lhs without doing any calculations
874884 // TODO Once division is implemented we should throw an error when dividing by 0.
875 if (rhs_val.tag() == .zero or rhs_val.tag() == .the_one_possible_value) {
885 if (rhs_val.compareWithZero(.eq)) {
876886 return mod.constInst(scope, inst.base.src, .{
877887 .ty = res_type,
878888 .val = lhs_val,
......@@ -1073,6 +1083,7 @@ fn analyzeInstUnreachNoChk(mod: *Module, scope: *Scope, unreach: *zir.Inst.NoOp)
10731083
10741084fn analyzeInstUnreachable(mod: *Module, scope: *Scope, unreach: *zir.Inst.NoOp) InnerError!*Inst {
10751085 const b = try mod.requireRuntimeBlock(scope, unreach.base.src);
1086 // TODO Add compile error for @optimizeFor occurring too late in a scope.
10761087 if (mod.wantSafety(scope)) {
10771088 // TODO Once we have a panic function to call, call it here instead of this.
10781089 _ = try mod.addNoOp(b, unreach.base.src, Type.initTag(.void), .breakpoint);
......@@ -1129,3 +1140,15 @@ fn analyzeDeclVal(mod: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerErr
11291140
11301141 return decl;
11311142}
1143
1144fn analyzeInstSingleConstPtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
1145 const elem_type = try resolveType(mod, scope, inst.positionals.operand);
1146 const ty = try mod.singleConstPtrType(scope, inst.base.src, elem_type);
1147 return mod.constType(scope, inst.base.src, ty);
1148}
1149
1150fn analyzeInstSingleMutPtrType(mod: *Module, scope: *Scope, inst: *zir.Inst.UnOp) InnerError!*Inst {
1151 const elem_type = try resolveType(mod, scope, inst.positionals.operand);
1152 const ty = try mod.singleMutPtrType(scope, inst.base.src, elem_type);
1153 return mod.constType(scope, inst.base.src, ty);
1154}
test/stage2/compare_output.zig+34
......@@ -363,5 +363,39 @@ pub fn addCases(ctx: *TestContext) !void {
363363 ,
364364 "",
365365 );
366
367 // Local mutable variables.
368 case.addCompareOutput(
369 \\export fn _start() noreturn {
370 \\ assert(add(3, 4) == 7);
371 \\ assert(add(20, 10) == 30);
372 \\
373 \\ exit();
374 \\}
375 \\
376 \\fn add(a: u32, b: u32) u32 {
377 \\ var x: u32 = undefined;
378 \\ x = 0;
379 \\ x += a;
380 \\ x += b;
381 \\ return x;
382 \\}
383 \\
384 \\pub fn assert(ok: bool) void {
385 \\ if (!ok) unreachable; // assertion failure
386 \\}
387 \\
388 \\fn exit() noreturn {
389 \\ asm volatile ("syscall"
390 \\ :
391 \\ : [number] "{rax}" (231),
392 \\ [arg1] "{rdi}" (0)
393 \\ : "rcx", "r11", "memory"
394 \\ );
395 \\ unreachable;
396 \\}
397 ,
398 "",
399 );
366400 }
367401}