Files
sakurac/compiler/emitter.sakura
T
2026-10-28 22:13:49 -05:00

700 lines
26 KiB
Plaintext

#! @file emitter.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the emitter, which lowers one function's body to intermediate code:
#! where each local is held, the scopes that close them, the values a
#! statement makes that close and no place owns yet, and the cells of the
#! frame what is held in memory lives in. What it does with each part of the
#! language is split across the files of the `emitter` directory.
import sakura::analyzer;
import std::containers;
module sakura::compiler;
#! A value as lowering holds it: the words it is, or the address of the memory
#! holding it, which a struct, union, or fixed array is held in.
pub struct operand {
var kind: u32; #! Its type.
var count: u32; #! How many words it is, where it is held as words.
var words: u32[2]; #! Its words.
var address: u32; #! The address of its memory, where it is held there, or 0.
}
#! Where a value is: in variables of the builder, or in memory.
pub struct location {
var kind: u32; #! The type of what is there.
var held: bool; #! Whether it is in variables rather than memory.
var vars: u32[2]; #! The variable of each word, where it is in variables.
var address: u32; #! The address its memory is reached from.
var offset: u64; #! How many bytes past the address it is.
var framed: bool; #! Whether the memory is in the frame, which a reference to it refers to while the frame lasts.
}
#! How a local is held.
pub enum held_as : u8 {
words, #! As the values of variables, where it is a word or a few.
cell, #! In a cell of the frame, where it is in memory or referred to.
}
#! A local the emitter knows: a variable, a parameter, or a name a test or a
#! loop gives.
pub struct local_info {
var node: u32; #! The node declaring it.
var place: location; #! Where it is.
var closes: bool; #! Whether it is closed where its scope ends.
var pack: u32; #! Of a pack, the first of its values in `packs`, and `count` how many.
var count: u32; #! Of a pack, how many values it holds.
var record: u32; #! One more than its variable among the code's, or 0.
var checks: bool; #! Whether it is an `ensures`, which is checked where its scope ends rather than closed.
}
#! A value a statement made that closes and no place owns, which the statement
#! closes where it ends, where the flag says it was made.
pub struct kept_value {
var address: u32; #! The address of its memory.
var cell: u32; #! One more than the cell holding it, whose address is taken again where it closes, or 0.
var kind: u32; #! Its type.
var flag: u32; #! The variable saying whether it was made, 1, or not, 0.
}
#! A loop being lowered, which `break` and `continue` leave.
pub struct loop_info {
var exit: u32; #! The block `break` goes to.
var next: u32; #! The block `continue` goes to.
var locals: u64; #! How many locals there were before its body, which a jump out of it closes past.
var kept: u64; #! How many kept values there were before its body, which a jump out of it closes past.
}
#! The call whose defaults are being made, which a default asks where it is,
#! or the text of what it was given.
pub struct default_site {
var node: u32; #! The call, or 0 where no default is being made.
var file: u32; #! The file the call is in.
var table: u32; #! The result table its nodes' results are in.
var args: u32; #! The run of the arguments it writes.
var params: u32; #! The run of the parameters of the function it calls.
var skip: u32; #! How many parameters come before the first argument, as `this`.
}
#! The emitter.
pub struct emitter {
var c: &mut lowerer; #! The compiler.
var build: builder; #! What builds the code.
var function: u32; #! The function being lowered.
var table: u32; #! The result table its nodes' results are in.
var result: u32; #! The type its `return` gives.
var locals: vector<local_info>;#! The locals in scope, the innermost last.
var local_ids: scoped_dict<u64, u32>; #! One more than the local each node declares, by its file and node, a change for each local in scope.
var packs: vector<location>; #! The values packs hold.
var kept: vector<kept_value>;#! The values made that close, which no place owns yet.
var loops: vector<loop_info>; #! The loops around what is lowered, the innermost last.
var storage: dict<u32, held_as>;#! How each local is held, by the node declaring it, where it is not in variables.
var free: vector<u32>; #! The temporary cells free to be taken again.
var lanes_cells: vector<bool>; #! Whether each cell is a temporary holding a vector, which only another vector takes again, so the cell is promoted to a vector, not words.
var taken: vector<u32>; #! The temporary cells taken by the statements being lowered.
var held: vector<u32>; #! The temporary cells holding kept values, freed once the values are closed or taken.
var named: dict<u32, u64>; #! Of each variable of the builder holding a word of a named local, the local's variable among the code's, then which word, as `variable << 8 | word`.
var defaulting: default_site; #! The call whose defaults are being made.
var returned: operand; #! What a `return` gives, while the `ensures` it leaves are checked.
var returning: bool; #! Whether a `return` giving a value is closing what it leaves.
}
#! Makes an emitter of a function.
#! @param c The compiler.
#! @param function The function.
#! @returns The emitter, whose builder takes the function's parameters.
pub def emitter::new(c: &mut lowerer, function: u32): emitter {
val signature: u32 = c.program.functions[function].signature;
var params := c.param_types(signature);
val result := c.layout_at(c.program.signatures[signature].result);
# A closure is given its environment, a reference to what it captures.
if c.program.functions[function].closure {
params.append(vt::word);
}
var made := emitter {
c = c,
build = builder::new(params.view()),
function = function,
locals = vector::<local_info>::new(scratch()),
local_ids = scoped_dict::<u64, u32>::new(scratch()),
packs = vector::<location>::new(scratch()),
kept = vector::<kept_value>::new(scratch()),
loops = vector::<loop_info>::new(scratch()),
storage = dict::<u32, held_as>::new(scratch()),
free = vector::<u32>::new(scratch()),
lanes_cells = vector::<bool>::new(scratch()),
taken = vector::<u32>::new(scratch()),
held = vector::<u32>::new(scratch()),
named = dict::<u32, u64>::new(scratch())
};
if !in_memory(&result) {
for _ in 0..word_count(&result) {
made.build.code.results.append(word_type(&result));
}
} else {
made.build.code.returned = result.size as u32;
}
return made;
}
#! Finishes the code lowered and gives it to the function, verifying it where
#! the options ask.
#! @param this The emitter.
pub def emitter::finish(&mut this): void {
var body := this.build.finish();
body.vectors = !this.c.options.evaluating && this.c.checker.names.text(this.c.checker.target.backend) == "native";
if this.c.options.verify {
val verdict := body.verify();
for &each in verdict.problems {
this.c.problems.append($"{this.c.program.functions[this.function].name}: {each}");
}
}
this.c.program.functions[this.function].body = move(&mut body);
}
#! Makes the function's result table the one the checker reads results from.
#! @param this The emitter.
pub def emitter::use_own_table(&mut this): void {
this.c.checker.use_table(this.table);
}
#! Notes what lowering could not lower, at a node.
#! @param this The emitter.
#! @param node The node.
#! @param what What it is, said in words.
pub def emitter::problem(&mut this, node: u32, what: strview): void {
if node == 0 {
this.c.problems.append($"{this.c.program.functions[this.function].name}: {what}");
return;
}
this.c.problem(this.c.checker.at.file, node, what);
}
#! Says where in the source the instructions added next are from.
#! @param this The emitter.
#! @param node The node they are lowered from.
pub def emitter::at_node(&mut this, node: u32): void {
return if node == 0;
this.build.pos = this.place_at(node);
}
#! Where in the source a node is, as instructions and variables say: one more
#! than its file above its byte.
#! @param this The emitter.
#! @param node The node.
#! @returns Where.
def emitter::place_at(&this, node: u32): u64 {
val file := this.c.checker.at.file;
return pair_key(file + 1, this.c.node_offset(file, node));
}
# Operands.
#! A value of no words, as `void` is.
#! @param kind The type.
#! @returns The operand.
pub def operand::none(kind: u32): operand {
return operand { kind = kind };
}
#! A value of one word.
#! @param kind The type.
#! @param word The word.
#! @returns The operand.
pub def operand::one(kind: u32, word: u32): operand {
var made := operand { kind = kind, count = 1 };
made.words[0] = word;
return made;
}
#! A value of two words, as a reference to a trait or a function is.
#! @param kind The type.
#! @param a The first word.
#! @param b The second.
#! @returns The operand.
pub def operand::two(kind: u32, a: u32, b: u32): operand {
var made := operand { kind = kind, count = 2 };
made.words[0] = a;
made.words[1] = b;
return made;
}
#! A value held in memory.
#! @param kind The type.
#! @param address The address of its memory.
#! @returns The operand.
pub def operand::at(kind: u32, address: u32): operand {
return operand { kind = kind, address = address };
}
#! The values of the code an operand gives where it is passed: its words, or
#! the address of its memory.
#! @param this The operand.
#! @param into Where they are appended.
pub def operand::args(&this, into: &mut vector<u32>): void {
if this.address != 0 {
into.append(this.address);
return;
}
for i in 0..this.count {
into.append(this.words[i]);
}
}
# Cells.
#! A temporary cell of a size, which the statement taking it holds until it
#! ends: one taken before and freed since where one fits.
#! @param this The emitter.
#! @param size How many bytes it holds.
#! @param align What its address is a multiple of.
#! @returns The cell.
pub def emitter::temporary(&mut this, size: u64, align: u64): u32 {
return this.temporary_for(size, align, false);
}
#! A temporary cell, as `temporary` gives, holding a vector or not: a cell is
#! taken again only for what it held before, a vector or not.
#! @param this The emitter.
#! @param size How many bytes it holds.
#! @param align What its address is a multiple of.
#! @param lanes Whether it holds a vector.
#! @returns The cell.
def emitter::temporary_for(&mut this, size: u64, align: u64, lanes: bool): u32 {
val wanted := round_up(size == 0 ? word_size : size, word_size) as u32;
val aligned := (align < word_size ? word_size : align) as u32;
for i in 0..this.free.length {
val cell: u32 = this.free[i];
val held: cell = this.build.code.cells[cell];
val vector := (cell as u64) < this.lanes_cells.length && this.lanes_cells[cell];
if held.size == wanted && held.align >= aligned && vector == lanes {
this.free.remove_at(i);
this.taken.append(cell);
return cell;
}
}
val made := this.build.code.add_cell(wanted, aligned, ck::temporary, 0);
if lanes {
this.lanes_cells.resize(made as u64 + 1);
this.lanes_cells[made] = true;
}
this.taken.append(made);
return made;
}
#! A temporary cell holding a value of a type, and its address.
#! @param this The emitter.
#! @param kind The type.
#! @returns The address of the cell.
pub def emitter::temporary_of(&mut this, kind: u32): u32 {
val held := this.c.shape_of(kind);
return this.build.cell_address(this.temporary_for(held.size, held.align, this.c.checker.is_lanes_type(kind)));
}
#! How many temporary cells the statements being lowered have taken, which
#! `release` frees those taken since.
#! @param this The emitter.
#! @returns The mark.
pub def emitter::cell_mark(&this): u64 {
return this.taken.length;
}
#! Frees the temporary cells taken since a mark, to be taken again.
#! @param this The emitter.
#! @param mark How many were taken before.
pub def emitter::release(&mut this, mark: u64): void {
while this.taken.length > mark {
val cell: u32 = this.taken.last();
this.taken.truncate();
# A cell holding a value the statement still closes is held until it does.
var kept := false;
for &each in this.kept {
kept = kept || each.cell == cell + 1;
}
if kept {
this.held.append(cell);
} else {
this.free.append(cell);
}
}
}
#! Frees the cell a kept value was held in, once it is closed or a place took
#! it, where the statement's cells were released before.
#! @param this The emitter.
#! @param cell One more than the cell, or 0.
def emitter::unhold(&mut this, cell: u32): void {
return if cell == 0;
for i in 0..this.held.length {
if this.held[i] == cell - 1 {
this.held.remove_at(i);
this.free.append(cell - 1);
return;
}
}
}
# Locals.
#! The local a node of the file being read declares, or none. A local is
#! known by its file as well as its node, since the defaults of a call name the
#! parameters of a function of another file, whose nodes are counted apart, as
#! the arguments written for them name the caller's locals.
#! @param this The emitter.
#! @param node The node.
#! @returns One more than the local's index, or 0.
pub def emitter::local_of(&this, node: u32): u32 {
return this.local_ids.get_or(&pair_key(this.c.checker.at.file, node), 0);
}
#! Declares a local where it is.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @param closes Whether it is closed where its scope ends.
#! @returns The local's index.
pub def emitter::declare(&mut this, node: u32, place: location, closes: bool): u32 {
val index := this.locals.length as u32;
this.locals.append(local_info {
node = node,
place = place,
closes = closes,
record = this.describe(node, &place)
});
this.local_ids.set(pair_key(this.c.checker.at.file, node), index + 1);
return index;
}
#! Notes a local as a variable debugging information shows, where it is named
#! and held in memory: in a cell, or the copy of a parameter given as memory.
#! Where locals are kept for debugging information, one in an object of the
#! heap is too, whose address a cell is given to hold.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @returns One more than the variable among the code's, or 0.
def emitter::describe(&mut this, node: u32, place: &location): u32 {
return 0 if node == 0 || place.held || place.address == 0 || place.offset != 0;
val name := this.c.checker.param_name(node);
return 0 if name == 0;
val at := this.place_at(node);
val param := this.c.checker.kind_of(node) == nk::param;
val held: origin = this.build.code.origins[place.address];
var cell: u32 = 0;
var given: u32 = 0;
if held.param {
return 0 if held.from != 0 || !place.framed;
given = held.index + 1;
} else if this.build.code.insts[held.from].kind == op::cell {
cell = this.build.code.insts[held.from].aux + 1;
} else {
return 0;
}
# Optimized code notes them only for debugging information.
return 0 if !this.c.options.keep_locals && !this.c.options.describe;
this.build.code.variables.append(variable_info {
name = name, at = at, kind = place.kind, cell = cell, given = given, param = param,
first = this.build.code.insts.length as u32
});
return this.build.code.variables.length as u32;
}
#! Notes a local held in values as a variable debugging information shows,
#! where it is named: one in variables of the builder, which each value they
#! are given binds.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param place Where it is.
#! @param words How many words it is.
def emitter::describe_held(&mut this, node: u32, place: &location, words: u64): void {
return if !this.c.options.describe;
val name := this.c.checker.param_name(node);
return if name == 0;
val at := this.place_at(node);
val param := this.c.checker.kind_of(node) == nk::param;
val index := this.build.code.variables.length as u32;
this.build.code.variables.append(variable_info {
name = name, at = at, kind = place.kind, param = param, held = true
});
for i in 0..words {
this.named.set(place.vars[i], (index as u64 << 8) | i);
}
}
#! Binds a named local to a value given a variable of the builder holding one
#! of its words, where it is one.
#! @param this The emitter.
#! @param held The variable of the builder.
#! @param value The value.
pub def emitter::bind(&mut this, held: u32, value: u32): void {
if this.named.get(&held) is some(found) {
this.bind_word((found >> 8) as u32, (found & 0xFF) as u32, value);
}
}
#! Binds a word of a variable held in values to a value, where the code being
#! built is.
#! @param this The emitter.
#! @param variable The variable, among the code's.
#! @param word Which of its words.
#! @param value The value.
def emitter::bind_word(&mut this, variable: u32, word: u32, value: u32): void {
val block := this.build.at;
this.build.code.bindings.append(binding {
variable = variable, word = word, value = value, after = this.build.code.blocks[block].last, block = block
});
}
#! Makes a place for a local of a type declared by a node, held as the storage
#! worked out for it says: in variables, or a cell.
#! @param this The emitter.
#! @param node The node declaring it.
#! @param kind Its type.
#! @param cells The kind of cell it takes where it takes one: `undefined` for
#! one the frame leaves as it is.
#! @returns Where it is.
pub def emitter::new_place(&mut this, node: u32, kind: u32, cells: ck = ck::local): location {
val held := this.c.shape_of(kind);
var how := this.storage.get_or(&node, held_as::words);
if in_memory(&held) && how == held_as::words {
how = held_as::cell;
}
if this.c.options.keep_locals && how == held_as::words && word_count(&held) != 0 {
how = held_as::cell;
}
match how {
held_as::cell => {
val name := this.c.checker.name_of(node);
val made := this.build.code.add_cell(round_up(held.size == 0 ? word_size : held.size, word_size) as u32,
held.align < word_size ? word_size as u32 : held.align as u32, cells, name);
return location { kind = kind, address = this.build.cell_address(made), framed = true };
}
else => {
var place := location { kind = kind, held = true };
for i in 0..word_count(&held) {
place.vars[i] = this.build.variable(word_type(&held));
}
if !this.c.options.keep_locals {
this.describe_held(node, &place, word_count(&held));
}
return place;
}
}
return location { kind = kind };
}
#! How many locals are in scope, which `end_scope` closes those declared since.
#! @param this The emitter.
#! @returns The mark.
pub def emitter::scope_mark(&this): u64 {
return this.locals.length;
}
#! Closes the locals declared since a mark, in the reverse of the order they
#! were declared, but the one given back by name, and ends their scope.
#! @param this The emitter.
#! @param mark How many were in scope before.
#! @param given The node of a local given back by name, which is not closed, or
#! 0.
pub def emitter::end_scope(&mut this, mark: u64, given: u32): void {
this.close_locals(mark, given);
this.forget_locals(mark);
}
#! Ends the scope of the locals declared since a mark, without closing them.
#! @param this The emitter.
#! @param mark How many were in scope before.
pub def emitter::forget_locals(&mut this, mark: u64): void {
# Each local set the node declaring it once, so taking back the changes
# since the mark gives each node the local it named before.
while this.locals.length > mark {
val record: u32 = this.locals.last().record;
if record != 0 {
this.build.code.variables[record as u64 - 1].end = this.build.code.insts.length as u32;
}
this.locals.truncate();
}
this.local_ids.rewind(mark);
}
#! Closes the locals declared since a mark that close, in the reverse of the
#! order they were declared, so each is closed while everything it was built
#! from still stands, but the one given back by name.
#! @param this The emitter.
#! @param mark How many were in scope before.
#! @param given The node of a local given back by name, or 0.
pub def emitter::close_locals(&mut this, mark: u64, given: u32): void {
var at := this.locals.length;
while at > mark {
at--;
val held: local_info = this.locals[at];
continue if !held.closes || held.node == given;
if held.checks {
this.check_ensures(held.node);
continue;
}
# A pack closes each of its values, the last first.
if held.count != 0 {
var k := held.count;
while k > 0 {
k--;
val each: location = this.packs[held.pack as u64 + k as u64];
this.close(&each);
}
continue;
}
this.close(&held.place);
}
}
# Kept values.
#! Keeps a value a statement made that closes, which no place owns yet, so the
#! statement closes it where it ends unless a place takes it first.
#! @param this The emitter.
#! @param value The value, held in memory.
pub def emitter::keep(&mut this, value: &operand): void {
return if value.address == 0 || !this.c.checker.closes(value.kind);
for &each in this.kept {
return if each.address == value.address;
}
val flag := this.build.variable(vt::word);
this.build.assign(flag, this.build.word(1));
# It may be made down one branch of the statement, and closed where they join,
# so the address of the cell holding it is taken again there.
var cell: u32 = 0;
val held: origin = this.build.code.origins[value.address];
if !held.param && this.build.code.insts[held.from].kind == op::cell {
cell = this.build.code.insts[held.from].aux + 1;
}
this.kept.append(kept_value { address = value.address, cell = cell, kind = value.kind, flag = flag });
}
#! Says a place took a kept value, so the statement no longer closes it.
#! @param this The emitter.
#! @param value The value.
pub def emitter::adopt(&mut this, value: &operand): void {
return if value.address == 0;
var at := this.kept.length;
while at > 0 {
at--;
if this.kept[at].address == value.address {
val cell: u32 = this.kept[at].cell;
this.kept.remove_at(at);
this.unhold(cell);
return;
}
}
}
#! Closes the values kept since a mark, in the reverse of the order they were
#! made, each where it was made on the way here, and forgets them.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::close_kept(&mut this, mark: u64): void {
this.leave_kept(mark);
while this.kept.length > mark {
val cell: u32 = this.kept.last().cell;
this.kept.truncate();
this.unhold(cell);
}
}
#! Forgets the values kept since a mark without closing them, where the program
#! stops before they would be.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::drop_kept(&mut this, mark: u64): void {
while this.kept.length > mark {
val cell: u32 = this.kept.last().cell;
this.kept.truncate();
this.unhold(cell);
}
}
#! Closes the values kept since a mark, each where it was made on the way here,
#! without forgetting them, as a jump out of the statements keeping them does.
#! @param this The emitter.
#! @param mark How many were kept before.
pub def emitter::leave_kept(&mut this, mark: u64): void {
var at := this.kept.length;
while at > mark {
at--;
val held: kept_value = this.kept[at];
val made := this.build.read(held.flag);
# Each close forgets it was made, so a jump in a later pass of a loop, taken
# before it is made again, does not close it twice.
if this.is_one(made) {
val place := location { kind = held.kind, address = held.address, framed = true };
this.close(&place);
this.build.assign(held.flag, this.build.word(0));
continue;
}
val closing := this.build.new_block();
val after := this.build.new_block();
this.build.branch(made, closing, after);
this.build.seal(closing);
this.build.switch_to(closing);
val address := held.cell != 0 ? this.build.cell_address(held.cell - 1) : held.address;
val place := location { kind = held.kind, address = address, framed = true };
this.close(&place);
this.build.assign(held.flag, this.build.word(0));
this.build.jump(after);
this.build.seal(after);
this.build.switch_to(after);
}
}
#! Whether a value is the word 1, made where it is known to be.
#! @param this The emitter.
#! @param value The value.
#! @returns Whether it is.
pub def emitter::is_one(&this, value: u32): bool {
val held: origin = this.build.code.origins[value];
return false if held.param;
val made: inst = this.build.code.insts[held.from];
return made.kind == op::iconst && made.imm == 1;
}
# Statements.
#! What a statement holds while it is lowered, which it lets go of once it ends.
pub struct statement_mark {
var cells: u64; #! The temporary cells taken before it.
var kept: u64; #! The values kept before it.
}
#! Begins a statement.
#! @param this The emitter.
#! @returns What it holds, as `end_statement` takes it.
pub def emitter::begin_statement(&this): statement_mark {
return statement_mark { cells = this.taken.length, kept = this.kept.length };
}
#! Ends a statement: closes what it kept, and frees the cells it took.
#! @param this The emitter.
#! @param mark What it held, as `begin_statement` gave it.
pub def emitter::end_statement(&mut this, mark: statement_mark): void {
this.close_kept(mark.kept);
this.release(mark.cells);
}
#! A safe point, where the handlers of the signals that have come run. Only a
#! program handling a signal has them, and only in its own functions, at the
#! start of each and of each pass of each loop, so a handler never finds a
#! container of std in the middle of a change.
#! @param this The emitter.
pub def emitter::safepoint(&mut this): void {
return if this.c.dispatch == no_function;
val held := &this.c.program.functions[this.function];
val decl: u32 = held.decl != 0 ? held.decl : held.outer;
return if decl == 0 || held.builtin != 0 || this.c.in_std(decl);
this.build.effect(op::safepoint, span::<u32>::empty(), this.c.dispatch, 0);
}