#! @file select.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the selection of instructions: the x86-64 code of a function, made #! from its intermediate code and where the register allocator put each value. #! Each operation is written as a few instructions over the registers and #! slots its operands are in, computing in `rax`, `rcx`, and `rdx`, and `xmm0` #! and `xmm1`, which hold no value between instructions. Constants and the #! addresses the code knows become immediates and addressing modes, and a #! comparison only a branch reads is the branch's own test. #! #! A function's frame is on the stack, below the caller's frame pointer and #! return address: the registers a call keeps that it saved, the address its #! memory result goes to, the values' slots, words the runtime's helpers write, #! where it calls anything, the copies of the parameters it takes in memory, #! its cells, and the arguments it passes on the stack. Where a check #! fails, the code jumps to a stub after the function's body, which calls the #! trap stub with the error, so the check costs a compare and a jump never #! taken. import sakura::compiler; import binary::amd64; module sakura::native; #! A check's failure, written after the function's body. struct trap_site { var patch: u64; #! The jump to it. var code: u32; #! The error it stops the program with. var at: u64; #! Where in the source the check is. var site: u32; #! The inline site the check is in. var index: u32; #! The instruction checking. } #! A safe point's call of the function running the handlers, written after #! the function's body, where a signal the program handles came. struct safe_site { var patch: u64; #! The jump to it. var back: u64; #! Where the code goes on. var at: u64; #! Where in the source the safe point is. var site: u32; #! The inline site it is in. var index: u32; #! The safe point. } #! An entry of a switch's table: where a case goes, a block or code leading to #! one. struct table_entry { var block: u32; #! The block, or `never` where it is code. var at: u64; #! Where the code is in the text. } #! A switch's table of addresses, written after the function's body. struct switch_table { var patch: u64; #! Where the jump through it holds its address. var first: u32; #! Its first entry in `entries`. var count: u32; #! How many entries it has. } #! A word operand: a register, memory, or an immediate. struct operand_of { var kind: u8; #! 0 for a register, 1 for memory, 2 for an immediate. var r: reg; var m: mem; var imm: i32; } #! What selecting the code of one function keeps, which makes the moves between #! the places of its values. pub struct selector : move_maker { var b: &mut building; #! The executable being built. var body: &code; #! The function's code. var p: placing; #! Where its values are. var index: u32; #! The function. var start: u64; #! Where its code begins in the text. # The frame, as offsets below the frame pointer. var frame: u64; #! The bytes of the frame below the frame pointer. var dst_at: u64; #! Of the address a result held in memory is written to. var slot_base: u64; #! Of the slots: slot `k` is at `slot_base + 8 * k + 8`, and a vector's of `n` words at that of its last. var scratch_at: u64; #! Of three words the runtime's helpers write. var cells: vector; #! Of each cell. var copies: vector; #! Of the copy of each parameter of the entry held in memory, or 0. var zero_from: u64; #! The cells zeroed as the function begins, from this offset var zero_to: u64; #! up to this one. var out_words: u64; #! How many words the calls it makes pass on the stack. var labels: vector; #! Where each block begins in the text. var jumps: fixup_list; #! The jumps to blocks, and the block each goes to, to patch once every block is placed. var traps: vector; var safe_points: vector; var tables: vector; var entries: vector; #! The entries of every table, one table's after another's. var addresses: vector; #! Where the code holds an address within itself, as a word. var calls_first: u64; #! The first of the building's calls the function makes. var stub_spans: vector; #! Of each stub written after the body, where its code begins and ends within the function's, then the instruction it is of. var pads: vector; #! Where the padding before each loop's head that `relax` aligns begins. var constants: vector; #! The vectors of constant lanes the code loads, 32 bytes each, written after its tables. var constant_uses: vector; #! Where the code holds the address of each it loads, and which, by `pair_key(place, constant)`. var last_at: u64; var last_site: u32; var returned: u64; #! The bytes of the memory it returns, or 0. var leaf: bool; #! Whether it calls nothing. var saved: reg[5]; #! The registers a call keeps that it saves below the frame pointer, in order, from the highest. var save_count: u64; #! How many. var aligned: bool; #! Whether its frame keeps `rsp` a multiple of 16, as calls, safe points, and taking signals need. var tails: bool; #! Whether a call a return comes straight after may be a jump, made once the frame is left: in code optimized with inlining, where no pointer into the frame is kept where the code cannot follow it. var framed: vector; #! Where tail calls may be made, whether each value may point into the frame. var tailed: u32; #! The return a call before it took the place of, jumping, or 0. var upper_parts: vector; #! Where registers hold 32 bytes of lanes, each its start and end as a pair's key, in code that may run without AVX. var uses_upper: bool; #! Whether that code works on 32 bytes of lanes at all. var single: vector; #! Whether each value is a real held as an `f32`, in its low four bytes, as `singles.sakura` says. var works: vector; #! Whether each instruction works an arithmetic of `f32`s in single precision. } # Frames. #! Finds the registers a call keeps that the function holds values in, which #! it saves as it begins and gives back as it returns. One reading `frame` #! saves every one of them, so what its callers hold in them is in its frame, #! where a reader of the stack from there up finds it. Finds too #! whether its frame keeps `rsp` a multiple of 16: where it calls anything, as #! C needs, or makes a safe point or takes signals, which call what does. #! @param this The selector. def selector::find_saved(&mut this): void { var used: u64 = 0; for &each in this.p.child_locs { if each.kind == place::gpr && keeps(each.number) { used = used | (1u << each.number as u64); } } this.aligned = !this.leaf; for k in 0..this.p.order.length { var walk := this.body.walk(this.p.order[k]); while walk.more() { val kind: op = this.body.insts[walk.next()].kind; if kind == op::frame { used = 0xFFFF; } if kind == op::safepoint || kind == op::signals { this.aligned = true; } } } for &r in kept_gprs { if (used & (1u << r as u64)) != 0 { this.saved[this.save_count] = r; this.save_count++; } } } #! The registers a function saves, one bit each by number. #! @param this The selector. #! @returns The bits. def selector::saved_mask(&this): u32 { var mask: u64 = 0; for k in 0..this.save_count { mask = mask | (1u << this.saved[k] as u64); } return mask as u32; } #! Lays out the frame of the function. The scratch the runtime's helpers write #! is only that of one calling anything. #! @param this The selector. #! @param memory Whether each parameter of the entry is held in memory. #! @param sizes The bytes of each one held in memory. def selector::lay_frame(&mut this, memory: span, sizes: span): void { var below: u64 = 8 * this.save_count; if this.returned != 0 { below += 8; this.dst_at = below; } this.slot_base = below; below += 8 * this.p.slot_count as u64; if !this.leaf { below += 24; } this.scratch_at = below; this.copies.resize(memory.length); for i in 0..memory.length { continue if !memory[i]; below = round_up(below + round_up(sizes[i], 8), 16); this.copies[i] = below; } # The cells the frame zeroes come together, then those it need not: those # of functions inlined, whose code clears them, and those every read of # which some write comes before. val writes := this.b.c.result_writes(this.index); val zeroed := zeroed_cells(this.body, this.p.order.view(), this.p.number.view(), writes.view()); this.cells.resize(this.body.cells.length); below = round_up(below, 8); this.zero_from = below; for pass in 0..2u { for i in 0..this.body.cells.length { val each: cell = this.body.cells[i]; val zeroes := each.kind != ck::inlined && each.kind != ck::undefined && zeroed[i]; continue if zeroes != (pass == 0); val align := each.align < 8 ? 8 : (each.align > 16 ? 16 : each.align as u64); below = round_up(below + round_up(each.size as u64, 8), align); this.cells[i] = below; } if pass == 0 { this.zero_to = below; } } # The arguments passed on the stack are at its bottom. this.frame = round_up(below + 8 * this.out_words, this.aligned ? 16 : 8); } #! The memory of a value's slot: the words it takes, from the lowest. #! @param this The selector. #! @param value The value. #! @returns The memory. def selector::slot(&this, value: u32): mem { val k := this.p.slot_of[value] as u64 + (this.p.bytes[value] / 8) as u64 - 1; return at(reg::rbp, -((this.slot_base + 8 * k + 8) as i64) as i32); } #! The memory of a word the scratch of the frame holds. #! @param this The selector. #! @param k The word: 0, 1, or 2. #! @returns The memory. def selector::scratch_word(&this, k: u64): mem { return at(reg::rbp, (8 * k as i64 - this.scratch_at as i64) as i32); } #! The memory of a place a move reads or writes that is no register. #! @param this The selector. #! @param held The place. #! @returns The memory. def selector::memory_of(&this, held: &loc): mem { if held.kind == place::slot { return this.slot(held.value); } if held.kind == place::out { return at(reg::rsp, (8 * held.value as u64) as i32); } # A word the function was called with past those in registers, above the # return address and the caller's frame pointer. return at(reg::rbp, (16 + 8 * (held.value as u64 - arg_count)) as i32); } # Values made again. #! The address a value made again is, where it is known while compiling: of the #! globals, a datum, or the image. #! @param this The selector. #! @param value The value. #! @param address Where the address is written. #! @returns Whether it is known. def selector::known_address(&this, value: u32, address: &mut u64): bool { val made := this.body.defining(value); return false if made == 0; val held: inst = this.body.insts[made]; if held.kind == op::global { address = this.b.globals + held.imm; return true; } if held.kind == op::datum { address = this.b.datum_address(held.aux) + held.imm; return true; } if held.kind == op::image { address = this.b.image_address; return true; } return false; } #! Where in the frame a value made again points, where it is an address of the #! frame: a cell, or the copy of a parameter held in memory. #! @param this The selector. #! @param value The value. #! @param offset Where the offset below the frame pointer is written. #! @returns Whether it is. def selector::frame_address(&this, value: u32, offset: &mut u64): bool { if this.p.memory_params[value] { offset = this.copies[this.body.origins[value].index]; return true; } val made := this.body.defining(value); return false if made == 0; val held: inst = this.body.insts[made]; return false if held.kind != op::cell; offset = this.cells[held.aux]; return true; } #! The bits of a value made again that is a constant. #! @param this The selector. #! @param value The value. #! @param bits Where the bits are written. #! @returns Whether it is a constant. def selector::constant_bits(&this, value: u32, bits: &mut u64): bool { val made := this.body.defining(value); return false if made == 0 || this.p.memory_params[value]; val held: inst = this.body.insts[made]; return false if held.kind != op::iconst && held.kind != op::fconst; bits = held.imm; return true; } #! Makes a value made again in a general register. #! @param this The selector. #! @param value The value. #! @param into The register. def selector::remake(&mut this, value: u32, into: reg): void { var offset: u64 = 0; if this.frame_address(value, &mut offset) { this.b.text.lea(into, at(reg::rbp, -(offset as i64) as i32)); return; } var address: u64 = 0; if this.known_address(value, &mut address) { this.b.text.mov_imm(into, address); return; } val held: inst = this.body.insts[this.body.defining(value)]; match held.kind { op::iconst, op::fconst => this.b.text.mov_imm(into, held.imm); op::callback => this.b.text.load(8, false, into, absolute(this.b.callback_word(held.aux))); op::c_address => this.b.text.load(8, false, into, absolute(this.b.got_word(held.aux))); op::frame => this.b.text.mov(into, reg::rsp); else => this.b.text.mov_imm(into, 0); } } # Moves. #! Makes a move: from a register, a slot, the stack, or a value made again, to #! a register, a slot, or the stack. `rcx` carries a word between memory, and #! `xmm0` a vector. #! @param this The selector. #! @param made The move. pub def selector::move_one(&mut this, made: &transfer): void { val from := made.from; val to := made.to; return if to.kind == place::none || from.same(&to); if made.bytes == 64 { this.move_wide(this.memory_of(&from), this.memory_of(&to)); return; } if made.bytes > 8 { this.move_lanes(from, to, made.bytes == 32); return; } if to.kind == place::gpr { val r := to.number as reg; match from.kind { place::gpr => this.b.text.mov(r, from.number as reg); place::xmm => this.b.text.movq_from_xmm(r, from.number); place::remade => this.remake(from.value, r); else => this.b.text.load(8, false, r, this.memory_of(&from)); } return; } if to.kind == place::xmm { match from.kind { place::xmm => this.b.text.movaps(to.number, from.number); place::gpr => this.b.text.movq_to_xmm(to.number, from.number as reg); place::remade => { this.remake(from.value, reg::rcx); this.b.text.movq_to_xmm(to.number, reg::rcx); } else => this.b.text.movsd_load(to.number, this.memory_of(&from)); } return; } # To memory. val dst := this.memory_of(&to); match from.kind { place::gpr => this.b.text.store(8, dst, from.number as reg); place::xmm => this.b.text.movsd_store(dst, from.number); place::remade => { var bits: u64 = 0; if this.constant_bits(from.value, &mut bits) && fits_i32(bits) { this.b.text.store_imm(dst, bits as i32); return; } this.remake(from.value, reg::rcx); this.b.text.store(8, dst, reg::rcx); } else => { this.b.text.load(8, false, reg::rcx, this.memory_of(&from)); this.b.text.store(8, dst, reg::rcx); } } } #! Makes moves all at once: each place written is read first by any move #! reading it, and a cycle saves one place in `rax`, or in `xmm0` for an SSE #! register, before writing it. Each move made gives its place among those #! waiting to the last. #! @param this The selector. #! @param given The moves, whose places written all differ. def selector::parallel(&mut this, given: span): void { var pending := vector::::new(scratch()); for &each in given { continue if each.to.kind == place::none || each.from.same(&each.to); pending.append(each); } make_moves::(&mut pending, this, true); } #! Whether a move reads the place another writes. #! @param this The selector. #! @param reader The move that may read it. #! @param writer The move writing it. #! @returns Whether it does. pub def selector::move_reads(&this, reader: &transfer, writer: &transfer): bool { return reader.from.same(&writer.to); } #! The move saving what a move would write over, which a cycle of moves still #! reads, in `rax`, or in `xmm0` for an SSE register. #! @param this The selector. #! @param written The move. #! @param pending The moves waiting, among them those reading the place. #! @returns The move saving it. pub def selector::move_saving(&mut this, written: &transfer, pending: span): transfer { # It holds the value a move reading it moves, which is as wide as that is. val saved: loc = written.to; var bytes: u8 = 8; for &each in pending { if each.from.same(&saved) { bytes = each.bytes; break; } } val keep := saved.kind == place::xmm ? in_xmm(0) : in_gpr(reg::rax); return transfer { from = saved, to = keep, bytes = bytes }; } #! Has a move read what another saved from where it was saved. #! @param this The selector. #! @param reader The move. #! @param saved The move saving what it reads. pub def selector::move_reread(&this, reader: &mut transfer, saved: &transfer): void { reader.from = saved.to; } #! Makes the moves of the gap before a place. #! @param this The selector. #! @param at The place. def selector::gap(&mut this, at: u32): void { val moves := this.p.gap_moves.of(at); return if moves.length == 0; this.parallel(moves); } #! Makes the moves along an edge. #! @param this The selector. #! @param edge The edge. def selector::edge(&mut this, edge: u32): void { val moves := this.p.edge_moves_of(edge); return if moves.length == 0; this.parallel(moves); } #! Whether an edge moves anything. #! @param this The selector. #! @param edge The edge. #! @returns Whether it does. def selector::moves_on(&this, edge: u32): bool { return this.p.edge_first[edge as u64] != this.p.edge_first[edge as u64 + 1]; } # Operands. #! Where a value is read by an instruction. #! @param this The selector. #! @param value The value. #! @param index The instruction reading it. #! @returns Where. def selector::read(&this, value: u32, index: u32): loc { return this.p.read_at(value, index); } #! A general register holding a word an instruction reads: its own, or the #! scratch register given, loaded with it. #! @param this The selector. #! @param value The value. #! @param index The instruction reading it. #! @param scratch The register it is loaded into where it is in none. #! @returns The register. def selector::word_reg(&mut this, value: u32, index: u32, scratch: reg): reg { val held := this.read(value, index); match held.kind { place::gpr => return held.number as reg; place::xmm => this.b.text.movq_from_xmm(scratch, held.number); place::remade => this.remake(value, scratch); place::none => this.b.text.mov_imm(scratch, 0); else => this.b.text.load(8, false, scratch, this.memory_of(&held)); } return scratch; } #! An SSE register holding a real an instruction reads: its own, or the #! scratch register given, loaded with it. #! @param this The selector. #! @param value The value. #! @param index The instruction reading it. #! @param scratch The register it is loaded into where it is in none. #! @returns The register's number. def selector::real_reg(&mut this, value: u32, index: u32, scratch: u8): u8 { val held := this.read(value, index); return this.widened(&held, scratch) if this.single[value]; match held.kind { place::xmm => return held.number; place::gpr => this.b.text.movq_to_xmm(scratch, held.number as reg); place::remade => { this.remake(value, reg::rdx); this.b.text.movq_to_xmm(scratch, reg::rdx); } place::none => { this.b.text.mov_imm(reg::rdx, 0); this.b.text.movq_to_xmm(scratch, reg::rdx); } else => this.b.text.movsd_load(scratch, this.memory_of(&held)); } return scratch; } #! A word an instruction reads as an operand of arithmetic: an immediate where #! it is a constant a 32-bit immediate holds, memory where it is in its slot, #! and a register otherwise. #! @param this The selector. #! @param value The value. #! @param index The instruction reading it. #! @param scratch The register it is loaded into where it is in none. #! @returns The operand. def selector::word_operand(&mut this, value: u32, index: u32, scratch: reg): operand_of { var imm: i32 = 0; if this.immediate(value, &mut imm) { return operand_of { kind = 2, imm = imm }; } if this.read(value, index).kind == place::slot { return operand_of { kind = 1, m = this.slot(value) }; } return operand_of { kind = 0, r = this.word_reg(value, index, scratch) }; } #! Whether a word an instruction reads is a constant a 32-bit immediate holds. #! @param this The selector. #! @param value The value. #! @param imm Where the constant is written. #! @returns Whether it is. def selector::immediate(&this, value: u32, imm: &mut i32): bool { return false if !this.p.remade[value]; var bits: u64 = 0; return false if !this.constant_bits(value, &mut bits) && !this.known_address(value, &mut bits); return false if !fits_i32(bits); imm = bits as i32; return true; } #! The general register a word result is computed into: its own, or the #! fallback where it goes to its slot or nowhere. #! @param this The selector. #! @param value The result. #! @param fallback The register otherwise. #! @returns The register. def selector::target(&this, value: u32, fallback: reg): reg { val held := this.p.made_at(value); return held.kind == place::gpr ? held.number as reg : fallback; } #! Puts a word result computed in a register where it goes. #! @param this The selector. #! @param value The result. #! @param r The register. def selector::put(&mut this, value: u32, r: reg): void { val held := this.p.made_at(value); match held.kind { place::gpr => { if held.number as reg != r { this.b.text.mov(held.number as reg, r); } } place::xmm => this.b.text.movq_to_xmm(held.number, r); place::slot => this.b.text.store(8, this.slot(value), r); else => {} } } #! The SSE register a real result is computed into: its own, or `xmm0`. #! @param this The selector. #! @param value The result. #! @returns The register's number. def selector::real_target(&this, value: u32): u8 { val held := this.p.made_at(value); return held.kind == place::xmm ? held.number : 0; } #! Puts a real result computed in an SSE register where it goes. #! @param this The selector. #! @param value The result. #! @param x The register. def selector::put_real(&mut this, value: u32, x: u8): void { val held := this.p.made_at(value); match held.kind { place::xmm => { if held.number != x { this.b.text.movaps(held.number, x); } } place::gpr => this.b.text.movq_from_xmm(held.number as reg, x); place::slot => this.b.text.movsd_store(this.slot(value), x); else => {} } } #! Whether a result goes anywhere, so it is worth computing. #! @param this The selector. #! @param value The result. #! @returns Whether it does. def selector::wanted(&this, value: u32): bool { return this.p.made_at(value).kind != place::none; } #! The memory an address an instruction reads points at, from an offset: #! addressing the frame or the image directly where the address is one of #! theirs, through the base and index a sum folded into it is made of, and #! otherwise through a register holding it. #! @param this The selector. #! @param value The address. #! @param index The instruction reading it. #! @param offset The bytes from the address. #! @param scratch The register it is loaded into where it is in none. #! @param second The register the index of a sum folded into it is loaded #! into where it is in none. #! @param direct Where whether it points into the frame or the image is #! written, which is never null. #! @returns The memory. def selector::address(&mut this, value: u32, index: u32, offset: u64, scratch: reg, second: reg, direct: &mut bool): mem { direct = false; val made := this.body.defining(value); if made != 0 && this.p.folded[made] && this.body.insts[made].kind == op::add { return this.sum_address(made, index, offset, scratch, second, direct); } if this.p.remade[value] { var below: u64 = 0; if this.frame_address(value, &mut below) { direct = true; return at(reg::rbp, (offset as i64 - below as i64) as i32); } var known: u64 = 0; if this.known_address(value, &mut known) { direct = true; return absolute(known + offset); } } return at(this.word_reg(value, index, scratch), offset as i32); } #! The base, index, and scale of a sum: the word a shift folded into it scales #! as its index, or else the operand held rather than made again, the other #! its base. #! @param this The selector. #! @param sum The sum. #! @param base Where its base is written. #! @param scale Where its index's scale is written. #! @returns Its index. def selector::sum_parts(&this, sum: u32, base: &mut u32, scale: &mut u8): u32 { val a := this.body.arg(sum, 0); val b := this.body.arg(sum, 1); scale = 1; for k in 0..2u { val operand := k == 0 ? a : b; val made := this.body.defining(operand); continue if made == 0 || !this.p.folded[made] || this.body.insts[made].kind != op::shl; base = k == 0 ? b : a; scale = (1u << this.body.insts[this.body.defining(this.body.arg(made, 1))].imm) as u8; return this.body.arg(made, 0); } if this.p.remade[b] { base = b; return a; } base = a; return b; } #! The memory a sum folded into the instruction reading it points at, from an #! offset: its base and its index scaled, the base the frame's or the image's #! own where it is an address of theirs. #! @param this The selector. #! @param sum The sum. #! @param index The instruction reading it. #! @param offset The bytes from the address. #! @param scratch The register the base is loaded into where it is in none. #! @param second The register the index is loaded into where it is in none. #! @param direct Where whether it points into the frame or the image is #! written. #! @returns The memory. def selector::sum_address(&mut this, sum: u32, index: u32, offset: u64, scratch: reg, second: reg, direct: &mut bool): mem { var base: u32 = 0; var scale: u8 = 1; val scaled := this.sum_parts(sum, &mut base, &mut scale); val by := this.word_reg(scaled, index, second); if this.p.remade[base] { var below: u64 = 0; if this.frame_address(base, &mut below) { direct = true; return indexed(reg::rbp, by, scale, (offset as i64 - below as i64) as i32); } var known: u64 = 0; if this.known_address(base, &mut known) { direct = true; return indexed(reg::none, by, scale, (known + offset) as i32); } } return indexed(this.word_reg(base, index, scratch), by, scale, offset as i32); } #! Stops the program with an error where a condition holds, jumping to a stub #! after the function's body that reports it. #! @param this The selector. #! @param condition The condition. #! @param code The error. #! @param index The instruction checking, whose place the report names. def selector::trap_if(&mut this, condition: cc, code: u32, index: u32): void { val held: inst = this.body.insts[index]; this.traps.append(trap_site { patch = this.b.text.jcc(condition), code = code, at = held.at, site = held.site, index = index }); } #! Stops the program with an error where a register holding an address is #! null, where reading at the offset would not fault on its own and the program #! checks. #! @param this The selector. #! @param base The register. #! @param reach How far past the address the access reaches. #! @param index The instruction. def selector::null_check(&mut this, base: reg, reach: u64, index: u32): void { return if reach <= null_page || !this.checking(); this.b.text.test(base, base); this.trap_if(cc::equal, fault::null_reference as u32, index); } #! Whether the program checks what only a checked build does, as `--checks` #! asks: here, an address reached far past null, a function value's index, and #! a trait's vtable, each compared with what it may be. #! @param this The selector. #! @returns Whether it does. def selector::checking(&this): bool { return !this.b.c.checker.checks_off; }