#! @file jit.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains compiling functions to the processor's code as they are first #! called, where the machine runs on Windows as an executable, which is where it #! calls C too. Each operation of a function's code becomes the instructions #! doing its work over the same frame of words the interpreter reads, so a #! compiled function and an interpreted one call each other, and see each #! other's frames, as two interpreted ones do. Running with memory checked, or #! evaluating constants, every function is interpreted. #! #! Compiled code keeps the machine's own records: it pushes a call record for #! each call and pops it as the call returns, and where it stops, every record #! is left for the trace, with the place in the bytecode of the innermost #! function in `jit_origin`. What the interpreter does rarely, as formatting, #! allocating, the system, and C, compiled code has `slow_op` do, so each is #! written once. #! #! While compiled code runs: #! - `rbx` is the frame of the function running; #! - `r12` the machine; #! - `r14` the lowest the stack of the system's thread may reach before calls #! are interpreted, which take only the machine's own stack; #! - `r15` the steps left before compiled code settles what it took, as a jump #! or a call takes one: `jit_arm` gives it as many as the host allows and a #! thread's turn has, and `jit_tick` settles them as they run out; #! - a function returns its words in `rdx`, `rcx`, and `r8`, and in `eax` 0, or #! the halt it stopped with. import std::containers; import system::windows; import sakura::compiler; module sakura::machine; #! What `run_native` and `call_native` give where the function was not run as #! compiled code, which the machine then interprets. No halt is numbered so. pub const jit_declined: u64 = 0xFFFF; #! The halt a number compiled code gives stands for. #! @param code The number, as `halt` numbers its members. #! @returns The halt. pub def halt_numbered(code: u64): halt { return match code { 0 => halt::none, 2 => halt::no_main, 3 => halt::unsupported, 4 => halt::out_of_bounds, 5 => halt::null_reference, 6 => halt::division, 7 => halt::not_held, 8 => halt::stack_overflow, 9 => halt::unreachable, 11 => halt::invalid_release, 13 => halt::not_member, 15 => halt::not_constant, 16 => halt::evaluation_limit, 17 => halt::not_evaluated, 18 => halt::invalid_access, 19 => halt::address, 20 => halt::exited, 21 => halt::aborted, 22 => halt::foreign_missing, 23 => halt::callback, 24 => halt::out_of_memory, 25 => halt::elsewhere, 26 => halt::faulted, 27 => halt::unwritten, 28 => halt::step_limit, else => halt::unsupported }; } #! Where compiled code finds what it reads and writes of the machine, as the #! bytes from the machine's first to each field's, and the functions it calls. pub struct jit_layout { var calls_data: u64; #! `calls`' records. var calls_used: u64; #! How many calls are running. var calls_capacity: u64; #! How many records fit. var top: u64; #! `top`. var stack_end: u64; #! `stack_end`. var left: u64; #! `jit_left`. var origin: u64; #! `jit_origin`. var results: u64; #! `results`. var table: u64; #! The address of `jit_table`. var tick: u64; #! `jit_helper_tick`. var slow: u64; #! `jit_helper_slow`. var call: u64; #! `jit_helper_call`. var grow: u64; #! `jit_helper_grow`. var copy: u64; #! `jit_helper_copy`. var zero: u64; #! `jit_helper_zero`. var frem: u64; #! `jit_helper_frem`. var guard: u64; #! The code a helper is called through, keeping `xmm6` to `xmm15`. var quick: u64; #! `jit_helper_quick`. var threads: u64; #! `threads`. var writes_at: u64; #! `writes_at`. var console_at: u64; #! `console_writes_at`. var calling_c: u64; #! `calling_c`. var last_error: u64; #! `last_error`. var foreign_fault: u64; #! `foreign_fault`. } #! As many steps as compiled code takes where nothing counts them. const jit_unbounded: u64 = 0x4000000000000000; #! Gives compiled code the steps it may take before it settles them: as many as #! the host still allows, the last of which stops it, and as a thread's turn #! has left. #! @param this The machine. def interpreter::jit_arm(&mut this): void { var batch := jit_unbounded; if this.options.steps != 0 && this.budget < batch { batch = this.budget + 1; } if this.threads != null && this.countdown < batch { batch = this.countdown; } if batch == 0 { batch = 1; } this.jit_batch = batch; this.jit_left = batch; } #! Takes the steps compiled code took from what the host allows and the turn, #! none of them the last of either, so the machine's own code counts on. #! @param this The machine. def interpreter::jit_settle(&mut this): void { val used := this.jit_batch - this.jit_left; if this.options.steps != 0 { this.budget = this.budget >= used ? this.budget - used : 0; } if this.threads != null { this.countdown = this.countdown > used ? this.countdown - used : 1; } this.jit_batch = 0; this.jit_left = 0; } when backend == native && os == windows { # What the stub entering compiled code leaves of the system's stack above its # lowest, for the machine's own code and the host's to run in. const jit_stack_margin: u64 = 0x20000; # The bytes of executable memory taken at once. const jit_chunk: u64 = 0x100000; # The paths compiled code takes rarely, made after the function's own code. const cold_fault: u8 = 0; # Stops with a halt: the place, the halt. const cold_error: u8 = 1; # Stops with the halt in `eax`. const cold_tick: u8 = 2; # Settles the steps taken, then goes back. const cold_call: u8 = 3; # Calls as the interpreter does, then goes back. const cold_grow: u8 = 4; # Makes room for more call records, then goes back. const cold_pass: u8 = 5; # Stops with the halt a compiled callee gave, the place it left kept. # A path compiled code takes rarely. struct jit_cold { var kind: u8; #! What it does. var from: u64; #! The displacement of the jump into it. var back: u64; #! Where in the code it goes back to. var pc: u64; #! Where the operation is in the bytecode. var value: u64; #! The halt, for a fault. } # Where a word of the frame is held while compiled code runs. A word held in # a register is written to the frame only where the machine's own code reads # it, and read back from it only where that code writes it. const held_memory: u8 = 0; # In the frame. const held_gpr: u8 = 1; # In a general register. const held_real: u8 = 2; # In an XMM register, as the double the frame holds. const held_single: u8 = 3; # In an XMM register, as the single the double is exactly. # The registers words are held in, which Microsoft's ABI has a callee keep, so # calls of compiled code and of the machine's helpers leave them as they were. const word_gprs: u8[4] = [rsi, rdi, r13, rbp]; const word_xmms: u8[10] = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; # The XMM register a word held as a single is widened in to be read as bits. const xmm_scratch: u8 = 5; # What stands for no register. const no_reg: u8 = 0xFF; # What compiling a function keeps track of. struct jit_function : owning { var out: machine_code; #! The code made. var at: vector; #! Where each operation of the bytecode begins in it; the bytecode's end is the exit. var jumps: vector; #! Pairs: where a displacement is, and the bytecode it jumps to. var colds: vector; #! The paths taken rarely. var function: u32; #! The function. var frame: u64; #! The bytes of its frame. var exit: u64; #! Where the bytecode ends, which jumps to the exit name. var layout: jit_layout; #! Where it reaches the machine. var places: vector; #! Where each word is held. var regs: vector; #! The register of each word held in one. var exact: vector; #! Whether each word only ever holds a double a single holds exactly. var held: vector; #! The words held in registers. var lows: vector; #! Where in the code each word's span begins, which a register holds it over. var highs: vector; #! Where it ends. var gprs: u64; #! How many of `word_gprs` it uses, which it keeps. var xmms: u64; #! How many of `word_xmms` it uses, which it keeps. var reserved: u64; #! The bytes it takes of the stack below what it pushes. } def jit_function::close(&mut this): void { this.out.close(); this.at.close(); this.jumps.close(); this.colds.close(); this.places.close(); this.regs.close(); this.exact.close(); this.held.close(); this.lows.close(); this.highs.close(); } # The displacement of a word of the frame. def slot_at(index: u32): u64 { return index as u64 * word_size; } # Where a word is held. def jit_function::place(&this, index: u32): u8 { return (index as u64) < this.places.length ? this.places[index as u64] : held_memory; } # The register a word is held in. def jit_function::reg(&this, index: u32): u8 { return this.regs[index as u64]; } # The general register a word is held in, or `no_reg`. def jit_function::gpr_of(&this, index: u32): u8 { return this.place(index) == held_gpr ? this.reg(index) : no_reg; } # The XMM register a word is held in as a double, or `no_reg`. def jit_function::real_of(&this, index: u32): u8 { return this.place(index) == held_real ? this.reg(index) : no_reg; } # The XMM register a word is held in as a single, or `no_reg`. def jit_function::single_of(&this, index: u32): u8 { return this.place(index) == held_single ? this.reg(index) : no_reg; } # The register holding an address a word holds: its own, where it is held in # a general register, or `rax`, which it is read into. def jit_function::address_in(&mut this, index: u32): u8 { val held := this.gpr_of(index); return held if held != no_reg; this.get(rax, index); return rax; } # Whether a word only ever holds what a single holds exactly. def jit_function::is_exact(&this, index: u32): bool { return (index as u64) < this.exact.length && this.exact[index as u64]; } # A word into a general register, as its bits. def jit_function::get(&mut this, to: u8, index: u32): void { val at := this.place(index); if at == held_gpr { if this.reg(index) != to { this.out.mov(to, this.reg(index)); } } else if at == held_real { this.out.movq_from_xmm(to, this.reg(index)); } else if at == held_single { this.out.sse_reg(0xF3, 0x5A, xmm_scratch, this.reg(index)); this.out.movq_from_xmm(to, xmm_scratch); } else { this.out.load(to, rbx, slot_at(index)); } } # A general register's bits into a word. def jit_function::put(&mut this, index: u32, from: u8): void { val at := this.place(index); if at == held_gpr { if this.reg(index) != from { this.out.mov(this.reg(index), from); } } else if at == held_real { this.out.movq_to_xmm(this.reg(index), from); } else if at == held_single { this.out.movq_to_xmm(xmm_scratch, from); this.out.sse_reg(0xF2, 0x5A, this.reg(index), xmm_scratch); } else { this.out.store(rbx, slot_at(index), from); } } # A word into `xmm`, as a double. def jit_function::get_real(&mut this, xmm: u8, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.movq_to_xmm(xmm, this.reg(index)); } else if at == held_real { this.out.movaps(xmm, this.reg(index)); } else if at == held_single { this.out.sse_reg(0xF3, 0x5A, xmm, this.reg(index)); } else { this.out.sse_mem(0xF2, 0x10, xmm, rbx, slot_at(index)); } } # A double in `xmm` into a word. def jit_function::put_real(&mut this, index: u32, xmm: u8): void { val at := this.place(index); if at == held_gpr { this.out.movq_from_xmm(this.reg(index), xmm); } else if at == held_real { this.out.movaps(this.reg(index), xmm); } else if at == held_single { this.out.sse_reg(0xF2, 0x5A, this.reg(index), xmm); } else { this.out.sse_mem(0xF2, 0x11, xmm, rbx, slot_at(index)); } } # A word into `xmm`, as a single, rounded as converting the double rounds. def jit_function::get_single(&mut this, xmm: u8, index: u32): void { val at := this.place(index); if at == held_single { this.out.movaps(xmm, this.reg(index)); } else if at == held_real { this.out.sse_reg(0xF2, 0x5A, xmm, this.reg(index)); } else if at == held_gpr { this.out.movq_to_xmm(xmm, this.reg(index)); this.out.sse_reg(0xF2, 0x5A, xmm, xmm); } else { this.out.sse_mem(0xF2, 0x5A, xmm, rbx, slot_at(index)); } } # A single in `xmm` into a word, as the double it is. def jit_function::put_single(&mut this, index: u32, xmm: u8): void { if this.place(index) == held_single { this.out.movaps(this.reg(index), xmm); return; } this.out.sse_reg(0xF3, 0x5A, xmm, xmm); this.put_real(index, xmm); } # One word into another, as its bits. def jit_function::copy_word(&mut this, to: u32, from: u32): void { val t := this.place(to); val f := this.place(from); if (t == held_real && f == held_real) || (t == held_single && f == held_single) { this.out.movaps(this.reg(to), this.reg(from)); } else if t == held_real && f == held_single { this.out.sse_reg(0xF3, 0x5A, this.reg(to), this.reg(from)); } else if t == held_single && f == held_real { this.out.sse_reg(0xF2, 0x5A, this.reg(to), this.reg(from)); } else if t == held_gpr && f == held_gpr { if this.reg(to) != this.reg(from) { this.out.mov(this.reg(to), this.reg(from)); } } else { this.get(rax, from); this.put(to, rax); } } # A word of 64 bits into a word of the frame. def jit_function::put_imm(&mut this, index: u32, value: u64): void { val at := this.place(index); if at == held_gpr { this.out.mov_imm(this.reg(index), value); } else if at == held_memory && fits32(value) { this.out.store_imm(rbx, slot_at(index), value); } else if at == held_single { this.out.mov_imm(rax, single_bits(value)); this.out.movq_to_xmm(this.reg(index), rax); } else { this.out.mov_imm(rax, value); this.put(index, rax); } } # An arithmetic of a general register and a word, the register written. A # word held in an XMM register is read through `rcx`. def jit_function::alu_word(&mut this, ext: u8, reg: u8, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.alu(ext, reg, this.reg(index)); } else if at == held_memory { this.out.alu_mem(ext, reg, rbx, slot_at(index)); } else { this.get(rcx, index); this.out.alu(ext, reg, rcx); } } # `imul reg, word`. def jit_function::imul_word(&mut this, reg: u8, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.imul(reg, this.reg(index)); } else if at == held_memory { this.out.imul_mem(reg, rbx, slot_at(index)); } else { this.get(rcx, index); this.out.imul(reg, rcx); } } # Sets the flags as `test` of a word with itself does. def jit_function::test_word(&mut this, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.test(this.reg(index), this.reg(index)); } else if at == held_memory { this.out.alu_mem_imm(alu_cmp, rbx, slot_at(index), 0); } else { this.get(rcx, index); this.out.test(rcx, rcx); } } # An arithmetic of doubles, `xmm` and a word, `xmm` written. Neither is `xmm1`. def jit_function::real_word(&mut this, opcode: u64, xmm: u8, index: u32): void { val at := this.place(index); if at == held_real { this.out.sse_reg(0xF2, opcode, xmm, this.reg(index)); } else if at == held_memory { this.out.sse_mem(0xF2, opcode, xmm, rbx, slot_at(index)); } else { this.get_real(1, index); this.out.sse_reg(0xF2, opcode, xmm, 1); } } # An arithmetic of singles, `xmm` and a word, `xmm` written. def jit_function::single_word(&mut this, opcode: u64, xmm: u8, index: u32): void { if this.place(index) == held_single { this.out.sse_reg(0xF3, opcode, xmm, this.reg(index)); } else { this.get_single(1, index); this.out.sse_reg(0xF3, opcode, xmm, 1); } } # Writes a word held in a register to the frame, for the machine's own code # to read. def jit_function::spill(&mut this, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.store(rbx, slot_at(index), this.reg(index)); } else if at == held_real { this.out.sse_mem(0xF2, 0x11, this.reg(index), rbx, slot_at(index)); } else if at == held_single { this.out.sse_reg(0xF3, 0x5A, xmm_scratch, this.reg(index)); this.out.sse_mem(0xF2, 0x11, xmm_scratch, rbx, slot_at(index)); } } # Reads a word held in a register back from the frame, after the machine's # own code wrote it. def jit_function::reload(&mut this, index: u32): void { val at := this.place(index); if at == held_gpr { this.out.load(this.reg(index), rbx, slot_at(index)); } else if at == held_real { this.out.sse_mem(0xF2, 0x10, this.reg(index), rbx, slot_at(index)); } else if at == held_single { this.out.sse_mem(0xF2, 0x5A, this.reg(index), rbx, slot_at(index)); } } # Every word held in a register over a place in the code to the frame. def jit_function::spill_all(&mut this, pc: u64): void { for i in 0..this.held.length { val each: u32 = this.held[i]; if this.lows[each as u64] <= pc && pc <= this.highs[each as u64] { this.spill(each); } } } # Every word held in a register over a place in the code back from the frame, # which leaves alone a register held another word's there. def jit_function::reload_all(&mut this, pc: u64): void { for i in 0..this.held.length { val each: u32 = this.held[i]; if this.lows[each as u64] <= pc && pc <= this.highs[each as u64] { this.reload(each); } } } # The bits of the single a double's bits stand for exactly. def single_bits(value: u64): u64 { var wide := value; val narrow := ((&mut wide) as *mut f64)[0] as f32; var out: u32 = 0; ((&mut out) as *mut f32)[0] = narrow; return out as u64; } # Whether a double's bits stand for what a single holds exactly. def single_exact(value: u64): bool { var wide := value; val real := ((&mut wide) as *mut f64)[0]; val back := (real as f32) as f64; var out: u64 = 0; ((&mut out) as *mut f64)[0] = back; return out == value; } # A jump, of a condition or none, to an operation of the bytecode. def jit_function::jump_to(&mut this, cc: u8, target: u64, always: bool): void { val at := always ? this.out.jmp() : this.out.jcc(cc); this.jumps.append(at); this.jumps.append(target); } # A jump, of a condition, into a path taken rarely. def jit_function::cold(&mut this, cc: u8, kind: u8, pc: u64, value: u64, always: bool): void { val from := always ? this.out.jmp() : this.out.jcc(cc); this.colds.append(jit_cold { kind = kind, from = from, back = this.out.length, pc = pc, value = value }); } # Stops where a word in `reg` is an address in the null page. def jit_function::null_check(&mut this, reg: u8, pc: u64): void { this.out.alu_imm(alu_cmp, reg, null_page); this.cold(cc_b, cold_fault, pc, halt::null_reference as u64, false); } # Takes a step, as a jump or a call does. def jit_function::step(&mut this, pc: u64): void { this.out.byte(0x49); this.out.byte(0xFF); this.out.byte(0xCF); # dec r15 this.cold(cc_e, cold_tick, pc, 0, false); } # Keeps what the machine's own code reads of compiled code's: the steps left, # and where the frames in use end, as the host and C calling back place # frames past them. def jit_function::sync(&mut this): void { this.out.store(r12, this.layout.left, r15); this.out.lea(rax, rbx, this.frame); this.out.store(r12, this.layout.top, rax); } # The words of the frame an operation the machine's own code runs reads and # writes, as `slow_op` and `jit_call` reach them. # @returns Whether they are known; where they are not, every word held in a # register is written to the frame and read back. def helper_words(code: *u32, pc: u64, reads: &mut vector, writes: &mut vector): bool { reads.clear(); writes.clear(); val kind := code[pc]; match kind { bc::allocate as u32 => { writes.append(code[pc + 1]); reads.append(code[pc + 2]); } bc::release as u32, bc::exit as u32, bc::trap_word as u32 => { reads.append(code[pc + 1]); } bc::resize as u32, bc::equal as u32 => { writes.append(code[pc + 1]); reads.append(code[pc + 2]); reads.append(code[pc + 3]); } bc::retrait as u32, bc::catch as u32 => { writes.append(code[pc + 1]); reads.append(code[pc + 2]); } bc::format as u32, bc::format_text as u32, bc::safepoint as u32 => {} bc::format_value as u32 => { for i in 0..code[pc + 2] as u64 { reads.append(code[pc + 3 + i]); } } bc::format_bytes as u32, bc::fault as u32 => { reads.append(code[pc + 1]); reads.append(code[pc + 2]); } bc::format_owned as u32 => { writes.append(code[pc + 1]); writes.append(code[pc + 2]); } bc::syscall as u32 => { writes.append(code[pc + 1]); for k in 2..9u { reads.append(code[pc + k]); } } bc::environ as u32, bc::signals as u32, bc::c_address as u32, bc::callback as u32 => { writes.append(code[pc + 1]); } bc::atomic as u32 => { writes.append(code[pc + 1]); reads.append(code[pc + 4]); reads.append(code[pc + 5]); reads.append(code[pc + 6]); } bc::start as u32 => { writes.append(code[pc + 1]); reads.append(code[pc + 2]); reads.append(code[pc + 3]); reads.append(code[pc + 4]); } bc::call as u32, bc::call_value as u32, bc::call_c as u32, bc::call_trait as u32 => { # The arguments, then the count of the results and the words they go to. val args := pc + (kind == bc::call_trait as u32 ? 4 : 3); val argc := code[args - 1] as u64; for i in 0..argc { reads.append(code[args + i]); } val resc := code[args + argc] as u64; for i in 0..resc { writes.append(code[args + argc + 1 + i]); } } else => { return false; } } return true; } # Whether an operation the machine's own code runs may run code of the # program's, or let another thread run, so the steps taken are settled # around it and the frames in use known: the system, C, threads, signals' # handlers, and calls. def runs_code(kind: u32): bool { return kind == bc::syscall as u32 || kind == bc::call_c as u32 || kind == bc::start as u32 || kind == bc::safepoint as u32 || kind == bc::call as u32 || kind == bc::call_trait as u32 || kind == bc::call_value as u32; } # Writes to the frame the words a helper reads, then calls it with the # machine, the frame, the function, and the place, reads back the words it # wrote, and stops with the halt it gives, if any. An operation running no # code of the program's is run by `jit_helper_quick`, which settles nothing. def jit_function::call_helper(&mut this, helper: u64, code: *u32, pc: u64): void { var reads := vector::::new(); var writes := vector::::new(); val known := helper_words(code, pc, &mut reads, &mut writes); if known { for i in 0..reads.length { this.spill(reads[i]); } } else { this.spill_all(pc); } val full := runs_code(code[pc]) || helper != this.layout.slow; if full { this.sync(); } this.out.mov(rcx, r12); this.out.mov(rdx, rbx); this.out.mov_imm(r8, this.function as u64); this.out.mov_imm(r9, pc); this.call_sakura(full ? helper : this.layout.quick); if full { this.out.load(r15, r12, this.layout.left); } if known { for i in 0..writes.length { this.reload(writes[i]); } } else { this.reload_all(pc); } reads.close(); writes.close(); this.out.test_status(); this.cold(cc_ne, cold_error, pc, 0, false); } # Calls a helper of the machine's own, its arguments in `rcx`, `rdx`, `r8`, # and `r9`, through the guard: the machine's code keeps no XMM register across # a call, where Microsoft's ABI has a callee keep `xmm6` to `xmm15`, which # compiled code holds words in. def jit_function::call_sakura(&mut this, helper: u64): void { this.out.mov_imm(rax, helper); this.out.mov_imm(r10, this.layout.guard); this.out.call_reg(r10); } # Copies bytes from `[from + fd]` to `[to + td]`: through `rcx` where they # are few, and otherwise by `jit_helper_copy`. Neither register is `rcx`. def jit_function::copy(&mut this, to: u8, td: u64, from: u8, fd: u64, size: u64): void { if size <= 128 { var i: u64 = 0; while i + 8 <= size { this.out.load(rcx, from, fd + i); this.out.store(to, td + i, rcx); i += 8; } if i + 4 <= size { this.out.load_narrow(0x8B, false, rcx, from, fd + i); this.out.store_narrow(4, to, td + i, rcx); i += 4; } if i + 2 <= size { this.out.load_narrow(0x0FB7, false, rcx, from, fd + i); this.out.store_narrow(2, to, td + i, rcx); i += 2; } if i < size { this.out.load_narrow(0x0FB6, false, rcx, from, fd + i); this.out.store_narrow(1, to, td + i, rcx); } return; } this.out.lea(r8, from, fd); this.out.lea(rcx, to, td); this.out.mov(rdx, r8); this.out.mov_imm(r8, size); this.call_sakura(this.layout.copy); } # Zeroes bytes from `[to + td]`, as `copy` copies them. `to` is not `rcx`. def jit_function::zero(&mut this, to: u8, td: u64, size: u64): void { if size <= 256 { this.out.alu(alu_xor, rcx, rcx); var i: u64 = 0; while i + 8 <= size { this.out.store(to, td + i, rcx); i += 8; } if i + 4 <= size { this.out.store_narrow(4, to, td + i, rcx); i += 4; } if i + 2 <= size { this.out.store_narrow(2, to, td + i, rcx); i += 2; } if i < size { this.out.store_narrow(1, to, td + i, rcx); } return; } this.out.lea(rcx, to, td); this.out.mov_imm(rdx, size); this.call_sakura(this.layout.zero); } # A comparison's result in `rax` as a word, 1 or 0, into the frame. def jit_function::put_condition(&mut this, cc: u8, index: u32): void { this.out.set_rax(cc); this.put(index, rax); } # Readies compiling functions: where compiled code finds the machine's fields # and its helpers, the table of compiled functions, and the stub the machine # enters compiled code through. def interpreter::jit_begin(&mut this): void { this.jit_on = false; return if this.options.evaluating || this.options.checks || this.options.interpret; val count := this.routines.length; return if count == 0; val base := this as *mut interpreter as u64; this.jit_at.calls_data = (&mut this.calls) as *mut call_stack as u64 - base; this.jit_at.calls_used = this.jit_at.calls_data + 8; this.jit_at.calls_capacity = this.jit_at.calls_data + 16; this.jit_at.top = (&mut this.top) as *mut u64 as u64 - base; this.jit_at.stack_end = (&mut this.stack_end) as *mut u64 as u64 - base; this.jit_at.left = (&mut this.jit_left) as *mut u64 as u64 - base; this.jit_at.origin = (&mut this.jit_origin) as *mut u64 as u64 - base; this.jit_at.results = (&mut this.results[0]) as *mut u64 as u64 - base; val tick: cfn = jit_helper_tick; val slow: cfn = jit_helper_slow; val call: cfn = jit_helper_call; val grow: cfn = jit_helper_grow; val copy: cfn = jit_helper_copy; val zero: cfn = jit_helper_zero; val frem: cfn = jit_helper_frem; val quick: cfn = jit_helper_quick; this.jit_at.quick = quick as u64; this.jit_at.threads = (&mut this.threads) as *mut *mut threading as u64 - base; this.jit_at.writes_at = (&mut this.writes_at) as *mut u64 as u64 - base; this.jit_at.console_at = (&mut this.console_writes_at) as *mut u64 as u64 - base; this.jit_at.calling_c = (&mut this.calling_c) as *mut u64 as u64 - base; this.jit_at.last_error = (&mut this.last_error) as *mut u32 as u64 - base; this.jit_at.foreign_fault = (&mut this.foreign_fault) as *mut halt as u64 - base; this.jit_at.tick = tick as u64; this.jit_at.slow = slow as u64; this.jit_at.call = call as u64; this.jit_at.grow = grow as u64; this.jit_at.copy = copy as u64; this.jit_at.zero = zero as u64; this.jit_at.frem = frem as u64; this.jit_table = raw_allocate_zeroed(count * word_size) as *mut u64; this.jit_at.table = this.jit_table as u64; this.jit_tried.resize(count, false); # The stub: it keeps the registers Microsoft's ABI has a callee keep, takes # the machine, the frame, and the code in `rcx`, `rdx`, and `r8`, finds how # low the thread's stack reaches from its TEB, and gives `jit_declined` # where the stack is that low already. The words a function returns are # kept in `results`. var stub := machine_code::new(); stub.push(rbx); stub.push(rbp); stub.push(rsi); stub.push(rdi); stub.push(r12); stub.push(r13); stub.push(r14); stub.push(r15); stub.alu_imm(alu_sub, rsp, 40); stub.mov(r12, rcx); stub.mov(rbx, rdx); # mov r14, gs:[0x1478], the stack's lowest address, `DeallocationStack`. stub.byte(0x65); stub.byte(0x4C); stub.byte(0x8B); stub.byte(0x34); stub.byte(0x25); stub.u32(0x1478); stub.alu_imm(alu_add, r14, jit_stack_margin); stub.alu(alu_cmp, rsp, r14); val low := stub.jcc(cc_b); stub.load(r15, r12, this.jit_at.left); stub.call_reg(r8); stub.store(r12, this.jit_at.left, r15); stub.store(r12, this.jit_at.results, rdx); stub.store(r12, this.jit_at.results + 8, rcx); stub.store(r12, this.jit_at.results + 16, r8); val done := stub.length; stub.alu_imm(alu_add, rsp, 40); stub.pop(r15); stub.pop(r14); stub.pop(r13); stub.pop(r12); stub.pop(rdi); stub.pop(rsi); stub.pop(rbp); stub.pop(rbx); stub.ret(); stub.land(low, stub.length); stub.mov_imm(rax, jit_declined); val back := stub.jmp(); stub.land(back, done); this.jit_stub = this.jit_place(&stub); stub.close(); # The guard: it keeps `xmm6` to `xmm15` around a call of the helper in # `rax`, leaving the 32 bytes the helper may keep its arguments in below. var guard := machine_code::new(); guard.alu_imm(alu_sub, rsp, 32 + 16 * word_xmms.length + 8); for i in 0..word_xmms.length { guard.save_xmm(rsp, 32 + 16 * i, word_xmms[i]); } guard.call_reg(rax); for i in 0..word_xmms.length { guard.restore_xmm(word_xmms[i], rsp, 32 + 16 * i); } guard.alu_imm(alu_add, rsp, 32 + 16 * word_xmms.length + 8); guard.ret(); this.jit_at.guard = this.jit_place(&guard); guard.close(); this.jit_on = this.jit_stub != 0 && this.jit_at.guard != 0; } # Gives back the code compiled and the table of it. def interpreter::jit_end(&mut this): void { for &each in this.jit_chunks { val memory: u64 = each; _ = VirtualFree(memory, 0, 0x8000); } this.jit_chunks.close(); if this.jit_table != null { raw_release(this.jit_table as *mut u8); this.jit_table = null; } this.jit_tried.close(); this.jit_on = false; } # Places code made in executable memory, which it then stays in. # @returns Where it begins, or 0 where no memory was given. def interpreter::jit_place(&mut this, made: &machine_code): u64 { val size := round_up(made.length, 16); if this.jit_chunks.length == 0 || this.jit_used + size > this.jit_limit { val taken := size > jit_chunk ? round_up(size, 65536) : jit_chunk; val memory := VirtualAlloc(0, taken, 0x3000, 0x40); return 0 if memory == 0; this.jit_chunks.append(memory); this.jit_used = memory; this.jit_limit = memory + taken; } val at := this.jit_used; memcpy(at as *mut u8, made.bytes.view().data, made.length); _ = FlushInstructionCache(GetCurrentProcess(), at, made.length); this.jit_used = at + size; return at; } #! Where a function's compiled code begins, compiling it the first time it is #! asked for, or 0 where it is interpreted. #! @param this The machine. #! @param function The function. #! @returns The address. def interpreter::native_of(&mut this, function: u32): u64 { val known := this.jit_table[function]; return known if known != 0 || this.jit_tried[function as u64]; this.jit_tried.set(function as u64, true); val made := this.jit_compile(function); this.jit_table[function] = made; return made; } #! Runs a function's compiled code, its frame ready, through the stub. #! @param this The machine. #! @param entry Where its code begins. #! @param fp Its frame. #! @returns 0 where it returned, the halt it stopped with, or `jit_declined`. def interpreter::run_native(&mut this, entry: u64, fp: *mut u64): u64 { this.jit_arm(); val stub := this.jit_stub as cfn; val ran := stub(this as *mut interpreter as u64, fp as u64, entry) & 0xFFFFFFFF; this.jit_settle(); return ran; } #! Runs a function the interpreter calls as compiled code, where it has some, #! its call begun, then writes what it returned into the caller's words and #! ends the call. #! @param this The machine. #! @param callee The function called. #! @param next Its frame. #! @param fp The caller's frame. #! @param code The caller's code. #! @param results Where the caller's code lists the words of the results. #! @param current The caller. #! @returns 0 where it returned, the halt it stopped with, or `jit_declined`. def interpreter::call_native(&mut this, callee: u32, next: *mut u64, fp: *mut u64, code: *u32, results: u64, current: u32): u64 { val entry := this.native_of(callee); return jit_declined if entry == 0; val ran := this.run_native(entry, next); return ran if ran != 0; val count := code[results] as u64; for i in 0..count { fp[code[results + 1 + i]] = this.results[i]; } this.calls.truncate(); this.top = fp as u64 + this.routines[current].frame; return 0; } # Calls a function as the interpreter's call, `call_trait`, or `call_value` # does, but for the step compiled code took already, running it compiled or # interpreted, then writes what it returned into the caller's words. # @param this The machine. # @param fp The caller's frame. # @param current The caller. # @param pc Where the call is in its code. # @returns Why it stopped, or `none`. def interpreter::jit_call(&mut this, fp: *mut u64, current: u32, pc: u64): halt { val code := this.routines[current].code; val kind := code[pc]; val next := (fp as u64 + this.routines[current].frame) as *mut u64; var callee: u32 = 0; var results: u64 = 0; var dst: u64 = 0; if kind == bc::call as u32 { callee = code[pc + 1]; val argc := code[pc + 2] as u64; results = pc + 3 + argc; val held: routine = this.routines[callee]; return halt::stack_overflow if next as u64 + held.frame > this.stack_end; val k := this.pass(&held, next, fp, code, pc + 3, 0, 0); dst = held.returned != 0 ? fp[code[pc + 3 + k]] : 0; } else if kind == bc::call_trait as u32 { val argc := code[pc + 3] as u64; val args := pc + 4; results = args + argc; val slot := code[pc + 2] as u64; val vtable := fp[code[args + 1]]; if vtable >= this.c.program.vtables.length || slot >= this.c.program.vtables[vtable].functions.length { return halt::null_reference; } callee = this.c.program.vtables[vtable].functions[slot]; return halt::null_reference if callee == no_function; val held: routine = this.routines[callee]; return halt::stack_overflow if next as u64 + held.frame > this.stack_end; # `this` is the reference the trait reference holds, and a default of a # trait this one composes is given the vtable whose slots it addresses. var k: u64 = 2; if held.count != 0 { val taken: param_slot = this.params[held.params as u64]; val at := taken.offset / word_size; next[at] = fp[code[args]]; if taken.words == 2 { next[at + 1] = this.c.program.vtables[vtable].owners[slot] as u64; } k = this.pass(&held, next, fp, code, args, 2, 1); } dst = held.returned != 0 ? fp[code[args + k]] : 0; } else { val argc := code[pc + 2] as u64; val args := pc + 3; results = args + argc; val index := fp[code[args]] - 1; return halt::null_reference if index >= this.routines.length; callee = index as u32; val held: routine = this.routines[callee]; return halt::stack_overflow if next as u64 + held.frame > this.stack_end; val k := this.pass(&held, next, fp, code, args, 2, 0); if held.closure { next[held.env / word_size] = fp[code[args + 1]]; } dst = held.returned != 0 ? fp[code[args + k]] : 0; } val held: routine = this.routines[callee]; this.enter(callee, &held, next, 0, pc, results, dst); val why := this.execute(this.calls.length - 1); return why if why != halt::none; val count := code[results] as u64; for i in 0..count { fp[code[results + 1 + i]] = this.results[i]; } return halt::none; } # Runs a signal's handler where one came, as the interpreter's `safepoint` # does, as a call of its own. def interpreter::jit_safepoint(&mut this, fp: *mut u64, code: *u32, pc: u64, current: u32): halt { return halt::none if (this.threads != null && this.strand != this.threads[0].strands[0]) || !signals_came(); val callee := code[pc + 1]; val held: routine = this.routines[callee]; val next := (fp as u64 + this.routines[current].frame) as *mut u64; return halt::stack_overflow if next as u64 + held.frame > this.stack_end; this.enter(callee, &held, next, pc + 2, pc, none, 0); return this.execute(this.calls.length - 1); } # Where compiled code's steps ran out: every step of the batch is taken, the # last now, which may stop the call or let another thread run. def jit_helper_tick(machine: u64): u64 { val m := machine as *mut interpreter; m[0].jit_left = 1; m[0].jit_settle(); val why := m[0].spent(); m[0].jit_arm(); return why as u64; } # Runs an operation compiled code has the machine's own code run. def jit_helper_slow(machine: u64, fp: u64, function: u64, pc: u64): u64 { val m := machine as *mut interpreter; m[0].jit_settle(); val code := m[0].routines[function].code; val kind := code[pc]; val why := kind == bc::safepoint as u32 ? m[0].jit_safepoint(fp as *mut u64, code, pc, function as u32) : m[0].slow_op(kind, fp as *mut u64, code, pc, function as u32); m[0].jit_arm(); return why as u64; } # Runs an operation compiled code has the machine's own code run that runs no # code of the program's and lets no other thread run, so no step is settled. def jit_helper_quick(machine: u64, fp: u64, function: u64, pc: u64): u64 { val m := machine as *mut interpreter; val code := m[0].routines[function].code; return m[0].slow_op(code[pc], fp as *mut u64, code, pc, function as u32) as u64; } # Calls as the interpreter does, where compiled code calls a function not # compiled, through a value or a trait, or with the system's stack low. def jit_helper_call(machine: u64, fp: u64, function: u64, pc: u64): u64 { val m := machine as *mut interpreter; m[0].jit_settle(); val why := m[0].jit_call(fp as *mut u64, function as u32, pc); m[0].jit_arm(); return why as u64; } # Makes room for more call records. def jit_helper_grow(machine: u64): void { val m := machine as *mut interpreter; m[0].calls.grow(); } # Copies bytes. def jit_helper_copy(to: u64, from: u64, size: u64): void { memcpy(to as *mut u8, from as *u8, size); } # Zeroes bytes. def jit_helper_zero(to: u64, size: u64): void { memset(to as *mut u8, 0, size); } # The remainder of two doubles, given and given back as their bits. def jit_helper_frem(a: u64, b: u64): u64 { var x := a; var y := b; var out: u64 = 0; ((&mut out) as *mut f64)[0] = ((&mut x) as *mut f64)[0] % ((&mut y) as *mut f64)[0]; return out; } # How an operation reads or writes a word, which choosing where the word is # held weighs: as an integer, as a double, as a single, or as bits only. const use_int: u8 = 0; const use_real: u8 = 1; const use_single: u8 = 2; const use_any: u8 = 3; # How a function's operations read and write each word of its frame, each # read and write weighed by how deep in loops it is. struct jit_uses : owning { var ints: vector; #! Reads and writes as an integer. var reals: vector; #! As a double. var singles: vector; #! As a single. var inexact: vector; #! Whether something written to it may be what no single holds. var copies: vector; #! Pairs: a word, and a word whose value it is given as it is. var lows: vector; #! Where in the code each word is first read or written. var highs: vector; #! Where it is last. var weight: u64; #! The weight of the operation counted. var pc: u64; #! Where the operation counted is. var ok: bool; #! Whether every operation's words are known. } def jit_uses::close(&mut this): void { this.ints.close(); this.reals.close(); this.singles.close(); this.inexact.close(); this.copies.close(); this.lows.close(); this.highs.close(); } # Counts a read of a word. def jit_uses::read(&mut this, index: u32, kind: u8): void { val at := index as u64; if at >= this.ints.length { this.ok = false; return; } if this.pc < this.lows[at] { this.lows.set(at, this.pc); } if this.pc > this.highs[at] || this.highs[at] == none { this.highs.set(at, this.pc); } if kind == use_int { this.ints.set(at, this.ints[at] + this.weight); } else if kind == use_real { this.reals.set(at, this.reals[at] + this.weight); } else if kind == use_single { this.singles.set(at, this.singles[at] + this.weight); } } # Counts a write of a word, of what a single may not hold exactly unless # `exact` says it does. def jit_uses::write(&mut this, index: u32, kind: u8, exact: bool): void { this.read(index, kind); if !exact && (index as u64) < this.inexact.length { this.inexact.set(index as u64, true); } } # Counts a word being given another's value, as a move gives it. def jit_uses::carries(&mut this, to: u32, from: u32): void { this.read(to, use_any); this.read(from, use_any); this.copies.append(to); this.copies.append(from); } # Where an operation jumps to, where it is a jump, or `none`. A switch's # earliest case is given, which a loop is found by as well. def jump_target(code: *u32, pc: u64): u64 { val kind := code[pc]; return match kind { bc::jump as u32 => code[pc + 1] as u64, bc::jump_if as u32, bc::jump_zero as u32 => code[pc + 2] as u64, bc::jump_eq as u32, bc::jump_ne as u32, bc::jump_lts as u32, bc::jump_ltu as u32, bc::jump_les as u32, bc::jump_leu as u32, bc::jump_eq_k as u32, bc::jump_ne_k as u32, bc::jump_lts_k as u32, bc::jump_ltu_k as u32, bc::jump_les_k as u32, bc::jump_leu_k as u32, bc::jump_gts_k as u32, bc::jump_gtu_k as u32, bc::jump_ges_k as u32, bc::jump_geu_k as u32, bc::move_jump as u32 => code[pc + 3] as u64, bc::add_k_jump as u32 => code[pc + 4] as u64, else => none }; } # Counts the words an operation reads and writes. def interpreter::jit_count(&mut this, u: &mut jit_uses, code: *u32, pc: u64): void { val kind := code[pc]; val a := code[pc + 1]; val b := code[pc + 2]; val c := code[pc + 3]; match kind { bc::move as u32, bc::move_jump as u32 => u.carries(a, b); bc::konst as u32 => u.write(a, use_any, single_exact(b as u64 | (c as u64 << 32))); bc::add as u32, bc::sub as u32, bc::mul as u32, bc::divs as u32, bc::divu as u32, bc::rems as u32, bc::remu as u32, bc::band as u32, bc::bor as u32, bc::bxor as u32, bc::shl as u32, bc::shrs as u32, bc::shru as u32, bc::eq as u32, bc::ne as u32, bc::lts as u32, bc::ltu as u32, bc::les as u32, bc::leu as u32, bc::eqsu as u32, bc::ltsu as u32, bc::lesu as u32, bc::ltus as u32, bc::leus as u32, bc::load_u8_x as u32 => { u.write(a, use_int, false); u.read(b, use_int); u.read(c, use_int); } bc::fadd as u32, bc::fsub as u32, bc::fmul as u32, bc::fdiv as u32, bc::frem as u32 => { u.write(a, use_real, false); u.read(b, use_real); u.read(c, use_real); } bc::feq as u32, bc::fne as u32, bc::flt as u32, bc::fle as u32 => { u.write(a, use_int, false); u.read(b, use_real); u.read(c, use_real); } bc::fadd_f32 as u32, bc::fsub_f32 as u32, bc::fmul_f32 as u32, bc::fdiv_f32 as u32 => { u.write(a, use_single, true); u.read(b, use_single); u.read(c, use_single); } bc::neg as u32, bc::bnot as u32, bc::lnot as u32, bc::ones as u32, bc::clz as u32, bc::ctz as u32, bc::bswap as u32, bc::wrap as u32, bc::add_k as u32, bc::mul_k as u32, bc::band_k as u32, bc::shl_k as u32, bc::shru_k as u32, bc::shrs_k as u32, bc::load_i8 as u32, bc::load_u8 as u32, bc::load_i16 as u32, bc::load_u16 as u32, bc::load_i32 as u32, bc::load_u32 as u32, bc::load_i64 as u32, bc::add_k_jump as u32 => { u.write(a, use_int, false); u.read(b, use_int); } bc::fneg as u32 => { # Negating keeps a single what it was. u.write(a, use_real, true); u.read(b, use_real); u.carries(a, b); } bc::itof as u32, bc::utof as u32 => { u.write(a, use_real, false); u.read(b, use_int); } bc::ftoi as u32, bc::ftou as u32 => { u.write(a, use_int, false); u.read(b, use_real); } bc::fsingle as u32 => { u.write(a, use_single, true); u.read(b, use_real); } bc::fsqrt as u32 => { u.write(a, use_real, false); u.read(b, use_real); } bc::select as u32 => { u.read(b, use_int); u.carries(a, c); u.carries(a, code[pc + 4]); } bc::cell as u32, bc::global as u32, bc::datum as u32 => u.write(a, use_int, false); bc::load_f32 as u32 => { u.write(a, use_single, true); u.read(b, use_int); } bc::store_8 as u32, bc::store_16 as u32, bc::store_32 as u32, bc::store_64 as u32 => { u.read(a, use_int); u.read(c, use_int); } bc::store_f32 as u32 => { u.read(a, use_int); u.read(c, use_single); } bc::store_k8 as u32, bc::store_k16 as u32, bc::store_k32 as u32, bc::store_k64 as u32, bc::clear as u32, bc::check as u32, bc::jump_if as u32, bc::jump_zero as u32, bc::switch as u32, bc::ret_memory as u32, bc::check_ltu_k as u32, bc::jump_eq_k as u32, bc::jump_ne_k as u32, bc::jump_lts_k as u32, bc::jump_ltu_k as u32, bc::jump_les_k as u32, bc::jump_leu_k as u32, bc::jump_gts_k as u32, bc::jump_gtu_k as u32, bc::jump_ges_k as u32, bc::jump_geu_k as u32 => u.read(a, use_int); bc::copy as u32, bc::check_ltu as u32, bc::jump_eq as u32, bc::jump_ne as u32, bc::jump_lts as u32, bc::jump_ltu as u32, bc::jump_les as u32, bc::jump_leu as u32 => { u.read(a, use_int); u.read(b, use_int); } bc::store_8_x as u32 => { u.read(a, use_int); u.read(b, use_int); u.read(code[pc + 4], use_int); } bc::jump as u32, bc::trap as u32, bc::unreachable as u32, bc::abort as u32 => {} bc::ret as u32 => { for i in 0..a as u64 { u.read(code[pc + 2 + i], use_any); } } else => { # Calls, and what the machine's own code runs: what it writes, written # by the machine, may be anything. var reads := vector::::new(); var writes := vector::::new(); if helper_words(code, pc, &mut reads, &mut writes) { for i in 0..reads.length { u.read(reads[i], use_any); } for i in 0..writes.length { u.write(writes[i], use_any, false); } } else { u.ok = false; } reads.close(); writes.close(); } } } # Chooses where each word of a function's frame is held: those read and # written most, loops weighing most, in registers, as integers, as doubles, # or, where every value written to one is a single's, as singles. # # A word is held over the code from where it is first read or written to # where it is last, widened over each loop that code meets, since a loop may # bring control back to where a word is read with what it held when the loop # last went round. Words whose spans do not meet share a register. # @returns How many words its parameters take, which the call writes. def interpreter::jit_place_words(&mut this, j: &mut jit_function, held: &routine, code: *u32, length: u64): u64 { val words := held.cells / word_size; var params: u64 = 0; for p in 0..held.count { val slot: param_slot = this.params[held.params as u64 + p as u64]; val end := slot.offset + (slot.memory ? slot.size : slot.words as u64 * word_size); params = end > params ? end : params; } params = round_up(params, word_size) / word_size; j.places.resize(words, held_memory); j.regs.resize(words, 0); j.exact.resize(words, false); j.lows.resize(words, none); j.highs.resize(words, none); return params if words == 0; # The loops, as the jumps back and where they go, and how deep in them each # operation is. var loops := vector::::new(); var depth := vector::::new(); depth.resize(length + 1, 0); var pc: u64 = 0; while pc < length { var targets := vector::::new(); if code[pc] == bc::switch as u32 { val cases := code[pc + 2] as u64; for i in 0..cases + 1 { targets.append(code[pc + 3 + 3 * i + (i == cases ? 0u : 2u)] as u64); } } else { val target := jump_target(code, pc); if target != none { targets.append(target); } } for &each in targets { val target: u64 = each; if target <= pc { loops.append(target); loops.append(pc); depth.set(target, depth[target] + 1); depth.set(pc + 1, depth[pc + 1] - 1); } } targets.close(); pc += op_width(code, pc); } var u := jit_uses { ints = vector::::new(), reals = vector::::new(), singles = vector::::new(), inexact = vector::::new(), copies = vector::::new(), lows = vector::::new(), highs = vector::::new(), ok = true }; u.ints.resize(words, 0); u.reals.resize(words, 0); u.singles.resize(words, 0); u.inexact.resize(words, false); u.lows.resize(words, none); u.highs.resize(words, none); # What the call gave as the parameters may be anything, and is held from # the start. val env := held.closure ? held.env / word_size : none; for w in 0..words { if w < params || w == env { u.inexact.set(w, true); u.lows.set(w, 0); u.highs.set(w, 0); } } var deep: i64 = 0; var last: u64 = 0; pc = 0; while pc < length { while last <= pc { deep += depth[last]; last++; } u.weight = deep <= 0 ? 1u : (deep == 1 ? 10u : (deep == 2 ? 100u : 1000u)); u.pc = pc; this.jit_count(&mut u, code, pc); pc += op_width(code, pc); } depth.close(); if !u.ok { u.close(); loops.close(); return params; } # A word given another's value may hold what it does. var changed := true; var rounds := 0; while changed && rounds < 64 { changed = false; rounds++; var i: u64 = 0; while i < u.copies.length { val to := u.copies[i] as u64; val from := u.copies[i + 1] as u64; if to < words && from < words && u.inexact[from] && !u.inexact[to] { u.inexact.set(to, true); changed = true; } i += 2; } } # Each word's span, widened over every loop it meets until none widens it. for w in 0..words { j.exact.set(w, !u.inexact[w]); var low: u64 = u.lows[w]; var high: u64 = u.highs[w]; continue if low == none; var widened := true; while widened { widened = false; var i: u64 = 0; while i < loops.length { val start: u64 = loops[i]; val end: u64 = loops[i + 1]; if low <= end && start <= high && (start < low || end > high) { low = start < low ? start : low; high = end > high ? end : high; widened = true; } i += 2; } } j.lows.set(w, low); j.highs.set(w, high); } loops.close(); # The words weighing most take a register of the kind they are read as that # no word whose span meets theirs holds. while true { var best: u64 = 0; var found: u64 = none; for w in 0..words { val total := u.ints[w] + u.reals[w] + u.singles[w]; if total > best && j.places[w] == held_memory { best = total; found = w; } } break if found == none; val floating := u.reals[found] + u.singles[found] > u.ints[found]; val count := floating ? word_xmms.length : word_gprs.length; var chosen: u64 = none; for r in 0..count { val reg := floating ? word_xmms[r] : word_gprs[r]; var free := true; for k in 0..j.held.length { val other := j.held[k] as u64; if j.regs[other] == reg && j.lows[other] <= j.highs[found] && j.lows[found] <= j.highs[other] { free = false; break; } } if free { chosen = r; break; } } if chosen != none { if floating { val single := !u.inexact[found] && u.singles[found] >= u.reals[found]; j.places.set(found, single ? held_single : held_real); j.regs.set(found, word_xmms[chosen]); j.xmms = chosen + 1 > j.xmms ? chosen + 1 : j.xmms; } else { j.places.set(found, held_gpr); j.regs.set(found, word_gprs[chosen]); j.gprs = chosen + 1 > j.gprs ? chosen + 1 : j.gprs; } j.held.append(found as u32); } # A word no register is free for stays in the frame. u.ints.set(found, 0); u.reals.set(found, 0); u.singles.set(found, 0); } u.close(); return params; } # Compiles a function's code. # @returns Where the code begins, or 0 where it is interpreted. def interpreter::jit_compile(&mut this, function: u32): u64 { val held: routine = this.routines[function]; val length := this.c.program.functions[function].compiled.code.length; return 0 if length == 0 || held.frame > 0x40000000; var j := jit_function { out = machine_code::new(), at = vector::::new(), jumps = vector::::new(), colds = vector::::new(), function = function, frame = held.frame, exit = length, layout = this.jit_at, places = vector::::new(), regs = vector::::new(), exact = vector::::new(), held = vector::::new(), lows = vector::::new(), highs = vector::::new() }; j.at.resize(length + 1, none); val params := this.jit_place_words(&mut j, &held, held.code, length); # It keeps the registers it holds words in, and takes the 32 bytes a call of # Microsoft's ABI may keep its register arguments in, the stack aligned to # 16 bytes for the calls it makes. for i in 0..j.gprs { j.out.push(word_gprs[i]); } j.reserved = 32 + 16 * j.xmms + (j.gprs % 2 == 0 ? 8u : 0u); j.out.alu_imm(alu_sub, rsp, j.reserved); for i in 0..j.xmms { j.out.save_xmm(rsp, 32 + 16 * i, word_xmms[i]); } # The frame's cells it zeroes as it starts, and the parameters it holds in # registers, which the call left in the frame. if held.zeroed > held.cells { j.zero(rbx, held.cells, round_up(held.zeroed, 8) - held.cells); } for i in 0..j.held.length { val each: u32 = j.held[i]; if (each as u64) < params || (held.closure && each as u64 == held.env / word_size) { j.reload(each); } } var pc: u64 = 0; while pc < length { j.at.set(pc, j.out.length); if !this.jit_op(&mut j, held.code, pc) { j.close(); return 0; } pc += op_width(held.code, pc); } # The exit, every return and stop leaving through it, which gives back the # registers it kept: the halt is in `eax`, and the words returned in `rdx`, # `rcx`, and `r8`. Then the paths taken rarely. j.at.set(length, j.out.length); for i in 0..j.xmms { j.out.restore_xmm(word_xmms[i], rsp, 32 + 16 * i); } j.out.alu_imm(alu_add, rsp, j.reserved); var g := j.gprs; while g > 0 { g--; j.out.pop(word_gprs[g]); } j.out.ret(); for i in 0..j.colds.length { val each: jit_cold = j.colds[i]; j.out.land(each.from, j.out.length); if each.kind == cold_pass { j.jump_to(0, j.exit, true); } else if each.kind == cold_fault || each.kind == cold_error { j.out.store_imm(r12, j.layout.origin, each.pc); if each.kind == cold_fault { j.out.mov_imm(rax, each.value); } j.jump_to(0, j.exit, true); } else if each.kind == cold_grow { j.out.mov(rcx, r12); j.call_sakura(j.layout.grow); val back := j.out.jmp(); j.out.land(back, each.back); } else { if each.kind == cold_tick { j.out.store(r12, j.layout.left, r15); j.out.mov(rcx, r12); j.call_sakura(j.layout.tick); } else { # The call's arguments to the frame, which it copies from, and its # results back from it, which it writes. var reads := vector::::new(); var writes := vector::::new(); _ = helper_words(held.code, each.pc, &mut reads, &mut writes); for r in 0..reads.length { j.spill(reads[r]); } j.sync(); j.out.mov(rcx, r12); j.out.mov(rdx, rbx); j.out.mov_imm(r8, function as u64); j.out.mov_imm(r9, each.pc); j.call_sakura(j.layout.call); for w in 0..writes.length { j.reload(writes[w]); } reads.close(); writes.close(); } j.out.load(r15, r12, j.layout.left); j.out.test_status(); val ok := j.out.jcc(cc_e); j.out.land(ok, each.back); j.out.store_imm(r12, j.layout.origin, each.pc); j.jump_to(0, j.exit, true); } } # Each jump to the bytecode lands where its operation's code begins. var i: u64 = 0; while i < j.jumps.length { val target: u64 = j.at[j.jumps[i + 1]]; if target == none { j.close(); return 0; } j.out.land(j.jumps[i], target); i += 2; } val placed := this.jit_place(&j.out); j.close(); return placed; } # The condition a comparison of the code holds by, and whether it is signed. def jump_condition(kind: u32): u8 { return match kind { bc::jump_eq as u32, bc::jump_eq_k as u32 => cc_e, bc::jump_ne as u32, bc::jump_ne_k as u32 => cc_ne, bc::jump_lts as u32, bc::jump_lts_k as u32 => cc_l, bc::jump_ltu as u32, bc::jump_ltu_k as u32 => cc_b, bc::jump_les as u32, bc::jump_les_k as u32 => cc_le, bc::jump_leu as u32, bc::jump_leu_k as u32 => cc_be, bc::jump_gts_k as u32 => cc_g, bc::jump_gtu_k as u32 => cc_a, bc::jump_ges_k as u32 => cc_ge, else => cc_ae }; } # Compiles an operation. # @returns Whether it could be, where the function is otherwise interpreted. def interpreter::jit_op(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { val kind := code[pc]; val a := code[pc + 1]; val b := code[pc + 2]; val c := code[pc + 3]; match kind { bc::move as u32 => { j.copy_word(a, b); } bc::konst as u32 => { j.put_imm(a, b as u64 | (c as u64 << 32)); } bc::add as u32, bc::sub as u32, bc::band as u32, bc::bor as u32, bc::bxor as u32 => { val ext := match kind { bc::add as u32 => alu_add, bc::sub as u32 => alu_sub, bc::band as u32 => alu_and, bc::bor as u32 => alu_or, else => alu_xor }; # Into the register the result is held in where there is one, as two # operands, the operation's own taken in either order where it may be. val held := j.gpr_of(a); if held != no_reg && a != c { j.get(held, b); j.alu_word(ext, held, c); } else if held != no_reg && kind != bc::sub as u32 { j.alu_word(ext, held, b); } else { j.get(rax, b); j.alu_word(ext, rax, c); j.put(a, rax); } } bc::mul as u32 => { val held := j.gpr_of(a); if held != no_reg && a != c { j.get(held, b); j.imul_word(held, c); } else if held != no_reg { j.imul_word(held, b); } else { j.get(rax, b); j.imul_word(rax, c); j.put(a, rax); } } bc::divu as u32, bc::remu as u32, bc::divs as u32, bc::rems as u32 => { j.get(r8, c); j.out.test(r8, r8); j.cold(cc_e, cold_fault, pc, halt::division as u64, false); j.get(rax, b); if kind == bc::divu as u32 || kind == bc::remu as u32 { j.out.alu(alu_xor, rdx, rdx); j.out.unary(6, r8); j.put(a, kind == bc::divu as u32 ? rax : rdx); } else { # By -1, the quotient is the negation, wrapping, and the remainder 0. j.out.alu_imm(alu_cmp, r8, 0xFFFFFFFFFFFFFFFF); val minus := j.out.jcc(cc_e); j.out.cqo(); j.out.unary(7, r8); j.put(a, kind == bc::divs as u32 ? rax : rdx); val done := j.out.jmp(); j.out.land(minus, j.out.length); if kind == bc::divs as u32 { j.out.unary(3, rax); j.put(a, rax); } else { j.put_imm(a, 0); } j.out.land(done, j.out.length); } } bc::shl as u32, bc::shru as u32, bc::shrs as u32 => { # A shift of 64 or more gives 0, or the sign, as built code's does. val ext := kind == bc::shl as u32 ? shift_left : (kind == bc::shru as u32 ? shift_right : shift_arithmetic); j.get(rcx, c); j.get(rax, b); j.out.alu_imm(alu_cmp, rcx, 64); val within := j.out.jcc(cc_b); if kind == bc::shrs as u32 { j.out.shift_imm(shift_arithmetic, rax, 63); } else { j.out.alu(alu_xor, rax, rax); } val done := j.out.jmp(); j.out.land(within, j.out.length); j.out.shift_cl(ext, rax); j.out.land(done, j.out.length); j.put(a, rax); } bc::eq as u32, bc::ne as u32, bc::lts as u32, bc::ltu as u32, bc::les as u32, bc::leu as u32 => { val cc := match kind { bc::eq as u32 => cc_e, bc::ne as u32 => cc_ne, bc::lts as u32 => cc_l, bc::ltu as u32 => cc_b, bc::les as u32 => cc_le, else => cc_be }; j.get(rax, b); j.alu_word(alu_cmp, rax, c); j.out.set_rax(cc); j.put(a, rax); } bc::eqsu as u32, bc::ltsu as u32, bc::lesu as u32, bc::ltus as u32, bc::leus as u32 => { # Comparisons of a signed word with an unsigned one, as the interpreter # works them out. j.get(rax, b); j.get(rdx, c); if kind == bc::ltsu as u32 || kind == bc::lesu as u32 { j.out.mov_imm(r8, 1); j.out.test(rax, rax); val negative := j.out.jcc(cc_s); j.out.alu(alu_xor, r8, r8); j.out.alu(alu_cmp, rax, rdx); val below := j.out.jcc(kind == bc::ltsu as u32 ? cc_ae : cc_a); j.out.mov_imm(r8, 1); j.out.land(below, j.out.length); j.out.land(negative, j.out.length); } else { j.out.alu(alu_xor, r8, r8); j.out.test(kind == bc::eqsu as u32 ? rax : rdx, kind == bc::eqsu as u32 ? rax : rdx); val negative := j.out.jcc(cc_s); j.out.alu(alu_cmp, rax, rdx); val fails := j.out.jcc(kind == bc::eqsu as u32 ? cc_ne : (kind == bc::ltus as u32 ? cc_ae : cc_a)); j.out.mov_imm(r8, 1); j.out.land(fails, j.out.length); j.out.land(negative, j.out.length); } j.put(a, r8); } bc::fadd as u32, bc::fsub as u32, bc::fmul as u32, bc::fdiv as u32 => { val opcode: u64 = match kind { bc::fadd as u32 => 0x58, bc::fmul as u32 => 0x59, bc::fsub as u32 => 0x5C, else => 0x5E }; val commutes := kind == bc::fadd as u32 || kind == bc::fmul as u32; val held := j.real_of(a); if held != no_reg && a != c { j.get_real(held, b); j.real_word(opcode, held, c); } else if held != no_reg && commutes { j.real_word(opcode, held, b); } else { j.get_real(0, b); j.real_word(opcode, 0, c); j.put_real(a, 0); } } bc::fadd_f32 as u32, bc::fsub_f32 as u32, bc::fmul_f32 as u32, bc::fdiv_f32 as u32 => { val opcode: u64 = match kind { bc::fadd_f32 as u32 => 0x58, bc::fmul_f32 as u32 => 0x59, bc::fsub_f32 as u32 => 0x5C, else => 0x5E }; val commutes := kind == bc::fadd_f32 as u32 || kind == bc::fmul_f32 as u32; val held := j.single_of(a); if j.is_exact(b) && j.is_exact(c) && held != no_reg && (a != c || commutes) { # Of singles, the single's arithmetic rounds as the double's rounded # to a single does, into the register the result is held in. if a != c { j.get_single(held, b); j.single_word(opcode, held, c); } else { j.single_word(opcode, held, b); } return true; } if j.is_exact(b) && j.is_exact(c) { j.get_single(0, b); j.single_word(opcode, 0, c); } else { j.get_real(0, b); j.real_word(opcode, 0, c); j.out.sse_reg(0xF2, 0x5A, 0, 0); } j.put_single(a, 0); } bc::frem as u32 => { j.get(rcx, b); j.get(rdx, c); j.call_sakura(j.layout.frem); j.put(a, rax); } bc::feq as u32, bc::fne as u32, bc::flt as u32, bc::fle as u32 => { # Not a number is unordered: equal to nothing, and below nothing. j.get_real(0, b); j.get_real(1, c); if kind == bc::feq as u32 || kind == bc::fne as u32 { val equal := kind == bc::feq as u32; j.out.sse_reg(0x66, 0x2E, 0, 1); j.out.set_low(equal ? cc_e : cc_ne, rax); j.out.set_low(equal ? cc_np : cc_p, rcx); j.out.byte(equal ? 0x20 : 0x08); j.out.byte(0xC8); # and al, cl or or al, cl j.out.byte(0x0F); j.out.byte(0xB6); j.out.byte(0xC0); # movzx eax, al j.put(a, rax); } else { j.out.sse_reg(0x66, 0x2E, 1, 0); j.out.set_rax(kind == bc::flt as u32 ? cc_a : cc_ae); j.put(a, rax); } } bc::neg as u32, bc::bnot as u32 => { j.get(rax, b); j.out.unary(kind == bc::neg as u32 ? 3 : 2, rax); j.put(a, rax); } bc::lnot as u32 => { j.test_word(b); j.out.set_rax(cc_e); j.put(a, rax); } bc::fneg as u32 => { if j.place(a) == held_single && j.place(b) == held_single { # A single's sign is its 31st bit. j.out.movq_from_xmm(rax, j.reg(b)); j.out.alu_imm(alu_xor, rax, 0x80000000); j.out.movq_to_xmm(j.reg(a), rax); } else { j.get(rax, b); j.out.flip_sign(rax); j.put(a, rax); } } bc::itof as u32 => { j.get(rax, b); j.out.cvtsi2sd(0, rax); j.put_real(a, 0); } bc::utof as u32 => { # Past the largest signed word, half the value is converted and doubled, # keeping its lowest bit, as built code converts it. j.get(rax, b); j.out.test(rax, rax); val large := j.out.jcc(cc_s); j.out.cvtsi2sd(0, rax); val done := j.out.jmp(); j.out.land(large, j.out.length); j.out.mov(rcx, rax); j.out.shift_imm(shift_right, rcx, 1); j.out.alu_imm(alu_and, rax, 1); j.out.alu(alu_or, rcx, rax); j.out.cvtsi2sd(0, rcx); j.out.sse_reg(0xF2, 0x58, 0, 0); j.out.land(done, j.out.length); j.put_real(a, 0); } bc::ftoi as u32 => { # Not a number is 0, and values past the range saturate, as in built code. j.get_real(0, b); j.out.mov_imm(rax, 0); j.out.sse_reg(0x66, 0x2E, 0, 0); val nan := j.out.jcc(cc_p); j.out.mov_imm(rdx, 0x43E0000000000000); j.out.movq_to_xmm(1, rdx); j.out.sse_reg(0x66, 0x2E, 0, 1); val high := j.out.jcc(cc_ae); j.out.cvttsd2si(rax, 0); val done := j.out.jmp(); j.out.land(high, j.out.length); j.out.mov_imm(rax, 0x7FFFFFFFFFFFFFFF); j.out.land(nan, j.out.length); j.out.land(done, j.out.length); j.put(a, rax); } bc::ftou as u32 => { j.get_real(0, b); j.out.mov_imm(rax, 0); j.out.mov_imm(rdx, 0); j.out.movq_to_xmm(1, rdx); j.out.sse_reg(0x66, 0x2E, 0, 1); val low := j.out.jcc(cc_be); j.out.mov_imm(rdx, 0x43F0000000000000); j.out.movq_to_xmm(1, rdx); j.out.sse_reg(0x66, 0x2E, 0, 1); val full := j.out.jcc(cc_ae); j.out.mov_imm(rdx, 0x43E0000000000000); j.out.movq_to_xmm(1, rdx); j.out.sse_reg(0x66, 0x2E, 0, 1); val upper := j.out.jcc(cc_ae); j.out.cvttsd2si(rax, 0); val done := j.out.jmp(); j.out.land(upper, j.out.length); j.out.sse_reg(0xF2, 0x5C, 0, 1); j.out.cvttsd2si(rax, 0); j.out.mov_imm(rcx, 0x8000000000000000); j.out.alu(alu_xor, rax, rcx); val finished := j.out.jmp(); j.out.land(full, j.out.length); j.out.mov_imm(rax, 0xFFFFFFFFFFFFFFFF); j.out.land(low, j.out.length); j.out.land(done, j.out.length); j.out.land(finished, j.out.length); j.put(a, rax); } bc::fsingle as u32 => { if j.is_exact(b) { j.get_single(0, b); } else { j.get_real(0, b); j.out.sse_reg(0xF2, 0x5A, 0, 0); } j.put_single(a, 0); } bc::fsqrt as u32 => { j.get_real(0, b); j.out.sse_reg(0xF2, 0x51, 0, 0); j.put_real(a, 0); } bc::ones as u32 => { j.get(rcx, b); j.out.bits(0xF3, 0xB8, rax, rcx); j.put(a, rax); } bc::clz as u32, bc::ctz as u32 => { # Of no bits set, there are 64. j.get(rcx, b); j.out.mov_imm(rax, 64); j.out.test(rcx, rcx); val empty := j.out.jcc(cc_e); if kind == bc::clz as u32 { j.out.bits(0, 0xBD, rdx, rcx); j.out.mov_imm(rax, 63); j.out.alu(alu_sub, rax, rdx); } else { j.out.bits(0, 0xBC, rax, rcx); } j.out.land(empty, j.out.length); j.put(a, rax); } bc::bswap as u32 => { j.get(rax, b); j.out.bswap(rax); j.put(a, rax); } bc::wrap as u32 => { val bits := c as u64; j.get(rax, b); if bits < 64 { return false if bits == 0; j.out.shift_imm(shift_left, rax, 64 - bits); j.out.shift_imm(code[pc + 4] != 0 ? shift_arithmetic : shift_right, rax, 64 - bits); } j.put(a, rax); } bc::select as u32 => { j.get(rax, code[pc + 4]); j.get(rdx, c); j.get(r8, b); j.out.test(r8, r8); j.out.cmov(cc_ne, rax, rdx); j.put(a, rax); } bc::cell as u32 => { j.out.lea(rax, rbx, b as u64); j.put(a, rax); } bc::global as u32 => { j.put_imm(a, this.globals as u64 + b as u64); } bc::datum as u32 => { j.put_imm(a, this.data[b as u64] + c as u64); } bc::load_i8 as u32, bc::load_u8 as u32, bc::load_i16 as u32, bc::load_u16 as u32, bc::load_i32 as u32, bc::load_u32 as u32, bc::load_i64 as u32, bc::load_f32 as u32 => { # Through the address's register, into the result's where there are. val offset := c as u64; return false if !fits32(offset); val base := j.address_in(b); j.null_check(base, pc); if kind == bc::load_f32 as u32 { val single := j.single_of(a); j.out.sse_mem(0xF3, 0x10, single != no_reg ? single : 0, base, offset); if single == no_reg { j.put_single(a, 0); } } else { val held := j.gpr_of(a); val into := held != no_reg ? held : rax; match kind { bc::load_i8 as u32 => j.out.load_narrow(0x0FBE, true, into, base, offset); bc::load_u8 as u32 => j.out.load_narrow(0x0FB6, false, into, base, offset); bc::load_i16 as u32 => j.out.load_narrow(0x0FBF, true, into, base, offset); bc::load_u16 as u32 => j.out.load_narrow(0x0FB7, false, into, base, offset); bc::load_i32 as u32 => j.out.load_narrow(0x63, true, into, base, offset); bc::load_u32 as u32 => j.out.load_narrow(0x8B, false, into, base, offset); else => j.out.load(into, base, offset); } if held == no_reg { j.put(a, rax); } } } bc::store_8 as u32, bc::store_16 as u32, bc::store_32 as u32, bc::store_64 as u32, bc::store_f32 as u32 => { val offset := b as u64; return false if !fits32(offset); val base := j.address_in(a); j.null_check(base, pc); if kind == bc::store_f32 as u32 { val single := j.single_of(c); if single == no_reg { j.get_single(0, c); } j.out.sse_mem(0xF3, 0x11, single != no_reg ? single : 0, base, offset); } else { var value := j.gpr_of(c); if value == no_reg { j.get(rdx, c); value = rdx; } if kind == bc::store_64 as u32 { j.out.store(base, offset, value); } else { j.out.store_narrow(kind == bc::store_8 as u32 ? 1 : (kind == bc::store_16 as u32 ? 2 : 4), base, offset, value); } } } bc::store_k8 as u32, bc::store_k16 as u32, bc::store_k32 as u32, bc::store_k64 as u32 => { val offset := b as u64; return false if !fits32(offset); val base := j.address_in(a); j.null_check(base, pc); if kind == bc::store_k64 as u32 { val value := c as u64 | (code[pc + 4] as u64 << 32); if fits32(value) { j.out.store_imm(base, offset, value); } else { j.out.mov_imm(rdx, value); j.out.store(base, offset, rdx); } } else { j.out.store_narrow_imm(kind == bc::store_k8 as u32 ? 1 : (kind == bc::store_k16 as u32 ? 2 : 4), base, offset, c as u64); } } bc::load_u8_x as u32 => { val offset := code[pc + 4] as u64; return false if !fits32(offset); j.get(rax, b); j.alu_word(alu_add, rax, c); j.null_check(rax, pc); j.out.load_narrow(0x0FB6, false, rax, rax, offset); j.put(a, rax); } bc::store_8_x as u32 => { val offset := c as u64; return false if !fits32(offset); j.get(rax, a); j.alu_word(alu_add, rax, b); j.null_check(rax, pc); j.get(rdx, code[pc + 4]); j.out.store_narrow(1, rax, offset, rdx); } bc::copy as u32 => { val size := c as u64; if size != 0 { j.get(rdx, a); j.get(rax, b); j.null_check(rdx, pc); j.null_check(rax, pc); j.copy(rdx, 0, rax, 0, size); } } bc::clear as u32 => { val size := b as u64; if size != 0 { j.get(rdx, a); j.null_check(rdx, pc); j.zero(rdx, 0, size); } } bc::add_k as u32, bc::band_k as u32 => { val held := j.gpr_of(a); val into := held != no_reg ? held : rax; j.get(into, b); j.out.alu_imm(kind == bc::add_k as u32 ? alu_add : alu_and, into, bc_constant(c)); if held == no_reg { j.put(a, rax); } } bc::mul_k as u32 => { val held := j.gpr_of(a); val into := held != no_reg ? held : rax; var from := j.gpr_of(b); if from == no_reg { j.get(rdx, b); from = rdx; } j.out.imul_imm(into, from, bc_constant(c)); if held == no_reg { j.put(a, rax); } } bc::shl_k as u32, bc::shru_k as u32, bc::shrs_k as u32 => { val count := bc_constant(c); val held := j.gpr_of(a); val into := held != no_reg ? held : rax; j.get(into, b); if count >= 64 { if kind == bc::shrs_k as u32 { j.out.shift_imm(shift_arithmetic, into, 63); } else { j.out.alu(alu_xor, into, into); } } else if count != 0 { j.out.shift_imm(kind == bc::shl_k as u32 ? shift_left : (kind == bc::shru_k as u32 ? shift_right : shift_arithmetic), into, count); } if held == no_reg { j.put(a, rax); } } bc::check as u32 => { j.test_word(a); j.cold(cc_e, cold_fault, pc, halt_of(b as u64) as u64, false); } bc::check_ltu as u32 => { val held := j.gpr_of(a); if held != no_reg { j.alu_word(alu_cmp, held, b); } else { j.get(rax, a); j.alu_word(alu_cmp, rax, b); } j.cold(cc_ae, cold_fault, pc, halt_of(c as u64) as u64, false); } bc::check_ltu_k as u32 => { val held := j.gpr_of(a); if held != no_reg { j.out.alu_imm(alu_cmp, held, bc_constant(b)); } else { j.get(rax, a); j.out.alu_imm(alu_cmp, rax, bc_constant(b)); } j.cold(cc_ae, cold_fault, pc, halt_of(c as u64) as u64, false); } bc::jump as u32 => { j.step(pc); j.jump_to(0, a as u64, true); } bc::jump_if as u32, bc::jump_zero as u32 => { j.step(pc); j.test_word(a); j.jump_to(kind == bc::jump_if as u32 ? cc_ne : cc_e, b as u64, false); } bc::jump_eq as u32, bc::jump_ne as u32, bc::jump_lts as u32, bc::jump_ltu as u32, bc::jump_les as u32, bc::jump_leu as u32 => { j.step(pc); val held := j.gpr_of(a); if held != no_reg { j.alu_word(alu_cmp, held, b); } else { j.get(rax, a); j.alu_word(alu_cmp, rax, b); } j.jump_to(jump_condition(kind), c as u64, false); } bc::jump_eq_k as u32, bc::jump_ne_k as u32, bc::jump_lts_k as u32, bc::jump_ltu_k as u32, bc::jump_les_k as u32, bc::jump_leu_k as u32, bc::jump_gts_k as u32, bc::jump_gtu_k as u32, bc::jump_ges_k as u32, bc::jump_geu_k as u32 => { j.step(pc); if j.place(a) == held_gpr { j.out.alu_imm(alu_cmp, j.reg(a), bc_constant(b)); } else { j.get(rax, a); j.out.alu_imm(alu_cmp, rax, bc_constant(b)); } j.jump_to(jump_condition(kind), c as u64, false); } bc::add_k_jump as u32 => { j.step(pc); if j.place(a) == held_gpr && a == b { j.out.alu_imm(alu_add, j.reg(a), bc_constant(c)); } else { j.get(rax, b); j.out.alu_imm(alu_add, rax, bc_constant(c)); j.put(a, rax); } j.jump_to(0, code[pc + 4] as u64, true); } bc::move_jump as u32 => { j.step(pc); j.copy_word(a, b); j.jump_to(0, c as u64, true); } bc::switch as u32 => { j.step(pc); j.get(rax, a); val cases := b as u64; for i in 0..cases { val at := pc + 3 + 3 * i; val value := code[at] as u64 | (code[at + 1] as u64 << 32); if fits32(value) { j.out.alu_imm(alu_cmp, rax, value); } else { j.out.mov_imm(rcx, value); j.out.alu(alu_cmp, rax, rcx); } j.jump_to(cc_e, code[at + 2] as u64, false); } j.jump_to(0, code[pc + 3 + 3 * cases] as u64, true); } bc::call as u32 => { return false if !this.jit_direct_call(j, code, pc); } bc::call_c as u32 => { if !this.jit_c_call(j, code, pc) { j.call_helper(j.layout.slow, code, pc); } } bc::call_trait as u32, bc::call_value as u32 => { val argc := code[pc + (kind == bc::call_trait as u32 ? 3 : 2)] as u64; val results := pc + (kind == bc::call_trait as u32 ? 4 : 3) + argc; return false if code[results] > 3; j.step(pc); j.call_helper(j.layout.call, code, pc); } bc::ret as u32 => { val count := a as u64; return false if count > 3; val into: u8[3] = [rdx, rcx, r8]; for i in 0..count { j.get(into[i], code[pc + 2 + i]); } j.out.alu(alu_xor, rax, rax); j.jump_to(0, j.exit, true); } bc::ret_memory as u32 => { # The result is copied to where the call record says, of the function's # bytes, where neither is null. val size := this.routines[j.function].returned; j.out.load(rax, r12, j.layout.calls_used); j.out.lea_index(rax, rax, rax, 1); j.out.shift_imm(shift_left, rax, 4); j.out.alu_mem(alu_add, rax, r12, j.layout.calls_data); j.out.load(rdx, rax, 0xFFFFFFFFFFFFFFF8); j.out.test(rdx, rdx); val no_dst := j.out.jcc(cc_e); j.get(rax, a); j.out.test(rax, rax); val no_source := j.out.jcc(cc_e); j.copy(rdx, 0, rax, 0, size); j.out.land(no_dst, j.out.length); j.out.land(no_source, j.out.length); j.out.alu(alu_xor, rax, rax); j.jump_to(0, j.exit, true); } bc::trap as u32, bc::unreachable as u32, bc::abort as u32 => { val why := kind == bc::trap as u32 ? halt_of(a as u64) : (kind == bc::abort as u32 ? halt::aborted : halt::unreachable); j.out.store_imm(r12, j.layout.origin, pc); j.out.mov_imm(rax, why as u64); j.jump_to(0, j.exit, true); } else => { # The rest the machine's own code runs, as the interpreter's does. j.call_helper(j.layout.slow, code, pc); } } return true; } # Whether a layout is one word a register passes to C or takes back. def scalar_for_c(shape: &layout): bool { return !in_memory(shape) && shape.size <= 8 && (shape.kind == lk::signed || shape.kind == lk::unsigned || shape.kind == lk::floating || shape.kind == lk::boolean || shape.kind == lk::reference || shape.kind == lk::pointer); } # Compiles a call of C taking at most four arguments and giving a result, if # any, each of one word, as `call_foreign` makes it: the arguments in the # registers of their positions, a real's in the SSE register, a double's in # the general one too, as a variadic function reads it; the frames in use, the # steps left, and the count of calls of C under way kept for C calling the # program back; what the thread's last C call left for `GetLastError` given # back in its TEB around the call; and a function C called back that stopped # stopping this one. The machine's own code calls it where the program's # threads take turns, and where it writes the output the machine keeps. # @returns Whether it could be compiled so. def interpreter::jit_c_call(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { val signature := code[pc + 1]; val argc := code[pc + 2] as u64; val base := pc + 3; val held := &this.c.program.signatures[signature]; val count := held.params.length; return false if count > 4 || argc != count + 1; val result: layout = this.c.program.layouts[held.result]; return false if result.kind != lk::empty && !scalar_for_c(&result); for i in 0..count { val shape: layout = this.c.program.layouts[held.params[i]]; return false if !scalar_for_c(&shape); } j.get(rax, code[base]); j.out.test(rax, rax); j.cold(cc_e, cold_fault, pc, halt::null_reference as u64, false); var slow := vector::::new(); j.out.alu_mem_imm(alu_cmp, r12, j.layout.threads, 0); slow.append(j.out.jcc(cc_ne)); if this.options.capture { j.out.alu_mem(alu_cmp, rax, r12, j.layout.writes_at); slow.append(j.out.jcc(cc_e)); j.out.alu_mem(alu_cmp, rax, r12, j.layout.console_at); slow.append(j.out.jcc(cc_e)); } val gprs: u8[4] = [rcx, rdx, r8, r9]; for i in 0..count { val shape: layout = this.c.program.layouts[held.params[i]]; val word := code[base + 1 + i]; if shape.kind == lk::floating && shape.size == 4 { j.get_single(i as u8, word); } else if shape.kind == lk::floating { j.get_real(i as u8, word); j.out.movq_from_xmm(gprs[i], i as u8); } else { j.get(gprs[i], word); } } j.out.lea(r10, rbx, j.frame); j.out.store(r12, j.layout.top, r10); j.out.store(r12, j.layout.left, r15); j.out.load_narrow(0x8B, false, r11, r12, j.layout.last_error); # mov gs:[0x68], r11d, the thread's `LastErrorValue`. j.out.byte(0x65); j.out.byte(0x44); j.out.byte(0x89); j.out.byte(0x1C); j.out.byte(0x25); j.out.u32(0x68); j.out.op_mem(0, true, 0xFF, 0, r12, j.layout.calling_c); j.out.mov_imm(r10, j.layout.guard); j.out.call_reg(r10); j.out.op_mem(0, true, 0xFF, 1, r12, j.layout.calling_c); # mov r11d, gs:[0x68]. j.out.byte(0x65); j.out.byte(0x44); j.out.byte(0x8B); j.out.byte(0x1C); j.out.byte(0x25); j.out.u32(0x68); j.out.store_narrow(4, r12, j.layout.last_error, r11); j.out.load(r15, r12, j.layout.left); # A function C called back stopped, which stops this one once C is back. j.out.op_mem(0, false, 0x83, 7, r12, j.layout.foreign_fault); j.out.byte(0); val fine := j.out.jcc(cc_e); j.out.load_narrow(0x8B, false, rax, r12, j.layout.foreign_fault); j.out.store_narrow_imm(4, r12, j.layout.foreign_fault, 0); j.out.store_imm(r12, j.layout.origin, pc); j.jump_to(0, j.exit, true); j.out.land(fine, j.out.length); # The result, widened from its bits as the frame holds it. val resc := code[base + argc] as u64; if resc != 0 && result.kind != lk::empty { val into := code[base + argc + 1]; if result.kind == lk::floating { if result.size == 4 { j.out.sse_reg(0xF3, 0x5A, 0, 0); } j.put_real(into, 0); } else { if result.kind == lk::boolean || result.size == 1 { j.out.op_reg(0, result.kind == lk::signed, result.kind == lk::signed ? 0x0FBE : 0x0FB6, rax, rax); } else if result.size == 2 { j.out.op_reg(0, result.kind == lk::signed, result.kind == lk::signed ? 0x0FBF : 0x0FB7, rax, rax); } else if result.size == 4 && result.kind != lk::pointer && result.kind != lk::reference { if result.kind == lk::signed { j.out.op_reg(0, true, 0x63, rax, rax); } else { j.out.op_reg(0, false, 0x8B, rax, rax); } } j.put(into, rax); } } val done := j.out.jmp(); for i in 0..slow.length { j.out.land(slow[i], j.out.length); } slow.close(); j.call_helper(j.layout.slow, code, pc); j.out.land(done, j.out.length); return true; } # Compiles a call of a function by its index: a step, then where the callee # is compiled and the system's stack has room, its frame is checked against # the machine's stack, its arguments copied as `pass` copies them, its record # pushed, and it is called, popping the record as it returns and taking its # words; otherwise the machine calls it as the interpreter does. # @returns Whether it could be compiled. def interpreter::jit_direct_call(&mut this, j: &mut jit_function, code: *u32, pc: u64): bool { val callee := code[pc + 1]; val argc := code[pc + 2] as u64; val results := pc + 3 + argc; val resc := code[results] as u64; return false if resc > 3; val held: routine = this.routines[callee]; val next := j.frame; return false if !fits32(next + held.frame); j.step(pc); j.out.load_rax_absolute(j.layout.table + callee as u64 * word_size); j.out.test(rax, rax); j.cold(cc_e, cold_call, pc, 0, false); val slow := j.colds.length - 1; j.out.alu(alu_cmp, rsp, r14); j.cold(cc_b, cold_call, pc, 0, false); val deep := j.colds.length - 1; j.out.lea(rdx, rbx, next + held.frame); j.out.alu_mem(alu_cmp, rdx, r12, j.layout.stack_end); j.cold(cc_a, cold_fault, pc, halt::stack_overflow as u64, false); # The arguments, as `pass` copies them. var k: u64 = 0; for p in 0..held.count { val slot: param_slot = this.params[held.params as u64 + p as u64]; if slot.memory { j.get(rax, code[pc + 3 + k]); j.out.test(rax, rax); val none_given := j.out.jcc(cc_e); j.copy(rbx, next + slot.offset, rax, 0, slot.size); j.out.land(none_given, j.out.length); k++; continue; } val at := slot.offset / word_size; for w in 0..slot.words { j.get(rcx, code[pc + 3 + k]); j.out.store(rbx, next + (at + w as u64) * word_size, rcx); k++; } } # Its record: the function, its frame, where it was called, and where its # result held in memory goes. val retry := j.out.length; j.out.load(rcx, r12, j.layout.calls_used); j.out.alu_mem(alu_cmp, rcx, r12, j.layout.calls_capacity); j.cold(cc_ae, cold_grow, pc, 0, false); j.colds.at(j.colds.length - 1).back = retry; j.out.lea_index(rdx, rcx, rcx, 1); j.out.shift_imm(shift_left, rdx, 4); j.out.alu_mem(alu_add, rdx, r12, j.layout.calls_data); j.out.store_narrow_imm(4, rdx, 0, callee as u64); j.out.lea(r8, rbx, next); j.out.store(rdx, 8, r8); j.out.store_imm(rdx, 16, 0); j.out.store_imm(rdx, 24, pc); j.out.store_imm(rdx, 32, none); if held.returned != 0 { j.get(r8, code[pc + 3 + k]); j.out.store(rdx, 40, r8); } else { j.out.store_imm(rdx, 40, 0); } j.out.alu_imm(alu_add, rcx, 1); j.out.store(r12, j.layout.calls_used, rcx); j.out.load_rax_absolute(j.layout.table + callee as u64 * word_size); j.out.alu_imm(alu_add, rbx, next); j.out.call_reg(rax); j.out.lea(rbx, rbx, 0 - next); j.out.test_status(); j.cold(cc_ne, cold_pass, pc, 0, false); j.out.op_mem(0, true, 0xFF, 1, r12, j.layout.calls_used); # dec qword [calls_used] val into: u8[3] = [rdx, rcx, r8]; for i in 0..resc { j.put(code[results + 1 + i], into[i]); } # The calls the machine makes itself go on past the call. j.colds.at(slow).back = j.out.length; j.colds.at(deep).back = j.out.length; return true; } } else { def interpreter::jit_begin(&mut this): void { this.jit_on = false; } def interpreter::jit_end(&mut this): void {} def interpreter::native_of(&mut this, function: u32): u64 { return 0; } def interpreter::run_native(&mut this, entry: u64, fp: *mut u64): u64 { return jit_declined; } def interpreter::call_native(&mut this, callee: u32, next: *mut u64, fp: *mut u64, code: *u32, results: u64, current: u32): u64 { return jit_declined; } }