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

576 lines
23 KiB
Plaintext

#! @file optimizer.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the optimizer, which runs passes over the code of each function
#! once the program is lowered. Each pass is small, in a file of its own, and
#! leaves the code well formed, which the verifier checks after each where
#! lowering verifies. `-O0` runs none, `-O1` simplification, control flow
#! cleanup, value numbering, and dead code removal, and `-O2` those with
#! inlining and the promotion of cells to values. Below `-O2`, calls of
#! `@inline` functions are inlined all the same, and nothing else is, so at
#! `-O0` the code is as written but for those, each local of the code copied
#! still in a cell of its own. The slots the passes leave are compacted away
#! at the end, which the backends and the functions inlining the code read.
#! Functions are optimized after the functions they call, so a function
#! inlined is already optimized.
#! At `-O2`, a function of an executable asking which vector instructions the
#! processor has is given a version for x86-64-v3's, as `versions.sakura` says.
import std::containers;
module sakura::compiler;
#! The passes, as a problem a pass leaves names them.
pub enum pass : u8 {
simplify, #! Folding constants and simplifying operations.
dead, #! Taking out what nothing needs.
control, #! Cleaning up how control flows.
inline, #! Inlining calls of small functions.
promote, #! Promoting cells to values.
numbering, #! Numbering values.
hoist, #! Moving constants into the entry.
memory, #! Cleaning up the memory of cells.
loops, #! Rotating loops and moving out of them what they work out the same each time round.
sink, #! Moving what is read past one way out of a block into that way.
count, #! How many passes there are; not a pass itself.
}
#! The name of a pass, as a problem names it.
#! @param this The pass.
#! @returns Its name.
pub def pass::name(&this): strview {
return match this {
pass::simplify => "simplification",
pass::dead => "dead code removal",
pass::control => "control flow cleanup",
pass::inline => "inlining",
pass::promote => "promotion",
pass::numbering => "value numbering",
pass::hoist => "constant hoisting",
pass::memory => "memory cleanup",
pass::loops => "loop optimization",
pass::sink => "code sinking",
else => "a pass"
};
}
#! Optimizes every function lowered and not yet optimized, as its level says,
#! each after those it calls, but for those calling each other, which go in the
#! order met. The order is worked out first, walking the calls, and a function
#! inlines only those before it, so what each is made into is the same however
#! many threads optimize them: as many as the options say work at once, each
#! taking a function once those before it that it calls are done. A function
#! the one calling it alone copies whole is optimized there, so only the passes
#! up to inlining run on it before, and the rest after, where something still
#! reaches it, as a cold call does. The versions of those asking which
#! instructions the processor has are made after, in the order, as each reads
#! what came before its function.
#! @param this The compiler.
pub def lowerer::optimize(&mut this): void {
return if this.options.level == 0 && !this.copies_marked();
var plan := this.plan_optimizing();
val count := plan.order.length;
# What verifying each function finds, kept by its place in the order, so it
# is noted in that order whichever thread found it.
var found := vector::<vector<string>>::new();
found.resize(count);
val compiler := &mut this;
share_out_ordered(count, this.options.threads, &plan.waiting, def(place: u64): void {
compiler.optimize_at(&plan, place, &mut found[place]);
});
# Those left for the function calling them that something still reaches, as
# one whose call is cold, have the rest of their passes run, each on its own,
# whichever optimizing left them.
var finishing := this.left_unfinished();
var alone := groups::<u32>::new(0);
alone.reset(finishing.length);
alone.seal();
var noted := vector::<vector<string>>::new();
noted.resize(finishing.length);
share_out_ordered(finishing.length, this.options.threads, &alone, def(k: u64): void {
compiler.finish_unfinished(finishing[k], &plan.ranks, &mut noted[k]);
});
for &each in found {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
for &each in noted {
for &text in each {
this.problems.append(string::copy_of(&text));
}
}
if this.versions_made() {
for place in 0..count {
this.make_version(plan.order[place], &mut plan.ranks, (2 * place + 3) as u32);
}
}
this.merge_all();
}
#! Merges the stores filling 16 bytes of a cell, in each function of an
#! executable optimized, once nothing more is inlined, as `merge.sakura` says.
#! @param this The compiler.
def lowerer::merge_all(&mut this): void {
for i in 0..this.program.functions.length {
val function := &mut this.program.functions[i];
continue if !function.optimized || !function.body.vectors;
val point := mark_scratch();
if function.body.merge_stores() {
function.body.compact();
if this.options.verify {
val verdict := function.body.verify();
for &each in verdict.problems {
this.problems.append($"{function.name}: after merging stores: {each}");
}
}
}
release_scratch(point);
}
}
#! Whether calls of `@inline` functions are inlined below `-O2`, which inlines
#! nothing else: but where the program evaluates constants, or runs with its
#! memory checked, as each function's locals end where its frame does then.
#! @param this The compiler.
#! @returns Whether they are.
def lowerer::inlines_marked(&this): bool {
return !this.options.evaluating && !this.options.checks;
}
#! Whether `-O0`, which optimizes nothing, has calls to inline all the same:
#! where a function lowered is `@inline`.
#! @param this The compiler.
#! @returns Whether it has.
def lowerer::copies_marked(&this): bool {
return false if !this.inlines_marked();
for &each in this.program.functions {
return true if each.inline && each.lowered;
}
return false;
}
#! Where a function never optimized is in the order functions are optimized in.
const unranked: u32 = 0xFFFFFFFF;
#! The order functions are optimized in, and what each waits for.
struct optimizing {
var order: vector<u32>; #! The functions, each after those it calls, but for those calling each other.
var ranks: vector<u32>; #! Of each function, `2k + 2` where it is the `k`th in the order, `2k + 3` where it is the version of that one, 0 where it was optimized before, and `unranked` where it is not optimized.
var waiting: groups<u32>; #! The places in the order of those waiting on each, by its place: each calls it, and comes after it.
}
#! A function on the walk of the calls that orders functions to be optimized.
struct calling {
var function: u32; #! The function.
var begin: u64; #! Where the functions it calls begin among the calls of those on the walk.
var end: u64; #! Where they end.
var next: u64; #! The next of them to walk.
}
#! Works out the order functions are optimized in: walking the calls from each
#! function lowered and not yet optimized, each once those it calls are, but
#! for those calling each other, which go in the order met. Each waits for the
#! functions before it that it calls.
#! @param this The compiler.
#! @returns The order.
def lowerer::plan_optimizing(&mut this): optimizing {
val count := this.program.functions.length;
var plan := optimizing {
order = vector::<u32>::new(),
ranks = vector::<u32>::new(),
waiting = groups::<u32>::new(0)
};
var seen := vector::<bool>::new();
seen.resize(count);
plan.ranks.resize(count);
for i in 0..count {
if this.program.functions[i].optimized {
seen[i] = true;
this.ready_to_inline(i as u32);
} else {
plan.ranks[i] = unranked;
}
}
# The functions on the walk, each with the functions it calls in `calls`.
# The callees of each function in the order are kept in `callees`, a run of
# each.
var stack := vector::<calling>::new();
var calls := vector::<u32>::new();
var callees := runs::<u32>::new();
var callee_runs := vector::<u32>::new();
for root in 0..count {
continue if seen[root] || !this.program.functions[root].lowered;
this.walk_into(root as u32, &mut seen, &mut stack, &mut calls);
while stack.length != 0 {
# The top is written before a callee is pushed, which may move it.
val top := &mut stack.last();
if top.next < top.end {
val callee: u32 = calls[top.next];
top.next++;
if !seen[callee] && this.program.functions[callee].lowered {
this.walk_into(callee, &mut seen, &mut stack, &mut calls);
}
continue;
}
callee_runs.append(callees.add(span::<u32>::over(calls.view().data + top.begin, top.end - top.begin)));
plan.ranks[top.function] = (2 * plan.order.length + 2) as u32;
plan.order.append(top.function);
calls.resize(top.begin);
stack.truncate();
}
}
# Each function waits for those before it that it calls, each once, as the
# functions counted for it say.
val placed := plan.order.length;
var counted := stamped_set::new(placed, nothing {});
var pairs := vector::<u64>::new();
plan.waiting.reset(placed);
for p in 0..placed {
counted.next_round();
for &callee in callees.view(callee_runs[p]) {
val rank: u32 = plan.ranks[callee];
continue if rank == 0 || rank == unranked;
val q := (rank - 2) / 2;
continue if q as u64 >= p || !counted.insert(q);
pairs.append(pair_key(q, p as u32));
plan.waiting.count(q);
}
}
plan.waiting.seal();
for &pair in pairs {
plan.waiting.put(pair_high(pair), pair_low(pair));
}
this.find_sole_calls(&plan.order);
# A call of a function this one waits for is settled, and stays so where it is
# inlined into another, which waited for this one.
for p in 0..placed {
val function: u32 = plan.order[p];
val body := &mut this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
continue if body.insts[at].kind != op::call;
val rank: u32 = plan.ranks[body.insts[at].aux];
body.insts[at].imm = rank != 0 && rank != unranked && rank < plan.ranks[function] ? call_settled : 0;
}
}
return plan;
}
#! Puts a function on the walk, with the functions it calls.
#! @param this The compiler.
#! @param function The function.
#! @param seen Whether each function was put on the walk.
#! @param stack The functions on the walk.
#! @param calls The callees of the functions on the walk.
def lowerer::walk_into(&mut this, function: u32, seen: &mut vector<bool>, stack: &mut vector<calling>, calls: &mut vector<u32>): void {
seen[function] = true;
val begin := calls.length;
val body := &this.program.functions[function].body;
var walk := body.walk_all();
while walk.more() {
val at := walk.next();
if body.insts[at].kind == op::call {
calls.append(body.insts[at].aux);
}
}
# A function named as a value may be called directly once the value is known,
# so it is waited for as one called is.
for &named in this.program.functions[function].named.view() {
calls.append(named);
}
stack.append(calling { function = function, begin = begin, end = calls.length, next = begin });
}
#! Optimizes the function of a place in the order, then readies it to be
#! inlined.
#! @param this The compiler.
#! @param plan The order.
#! @param place The place.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_at(&mut this, plan: &optimizing, place: u64, found: &mut vector<string>): void {
val function: u32 = plan.order[place];
this.optimize_function(function, &plan.ranks, (2 * place + 2) as u32, found);
this.program.functions[function].optimized = true;
this.ready_to_inline(function);
}
#! Finds the functions left unfinished that something still reaches.
#! @param this The compiler.
#! @returns The functions, in order.
def lowerer::left_unfinished(&mut this): vector<u32> {
var left := vector::<u32>::new();
val count := this.program.functions.length;
var any := false;
for i in 0..count {
any = any || this.program.functions[i].unfinished;
}
return left if !any;
val point := mark_scratch();
var reached := worklist::new(count, scratch());
this.reach_functions(&mut reached);
for i in 0..count {
if this.program.functions[i].unfinished && reached.has(i as u32) {
left.append(i as u32);
}
}
release_scratch(point);
return left;
}
#! Runs the rest of the passes on a function left unfinished, then readies it
#! to be inlined again, as its code changed.
#! @param this The compiler.
#! @param function The function.
#! @param ranks Where each function is in the order functions are
#! optimized in, which none of the passes left inlines by.
#! @param found Where what verifying it finds is noted.
def lowerer::finish_unfinished(&mut this, function: u32, ranks: &vector<u32>, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = 0, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
this.finish_function(function, &mut sweep);
val held := &mut this.program.functions[function];
held.unfinished = false;
held.inlining = inline_facts { sole = held.inlining.sole };
held.order.clear();
this.ready_to_inline(function);
}
#! Works out what inlining an optimized function asks of it, as its code no
#! longer changes, rather than leave that to the first function inlining it,
#! as several may at once on threads of their own: what inlining knows of it,
#! and where it may be copied, the order its blocks are copied in.
#! @param this The compiler.
#! @param function The function.
def lowerer::ready_to_inline(&mut this, function: u32): void {
# Below `-O2`, only `@inline` functions are.
return if this.options.level < 2 && !this.program.functions[function].inline;
val point := mark_scratch();
if this.inline_facts(function).fits {
this.order_blocks(function);
}
release_scratch(point);
}
#! Optimizes one function, as its level says. A pass that found nothing to
#! change is not run again until another changes something.
#! @param this The compiler.
#! @param index The function.
#! @param ranks Where each function is in the order functions are optimized
#! in, as `optimizing` says: those before it are inlined.
#! @param rank Where the function is.
#! @param found Where what verifying it finds is noted.
def lowerer::optimize_function(&mut this, index: u32, ranks: &vector<u32>, rank: u32, found: &mut vector<string>): void {
var sweep := passes { ranks = ranks, rank = rank, found = found, compacted = 0xFFFFFFFF };
for i in 0..pass::count as u64 {
sweep.clean[i] = 0xFFFFFFFF;
}
# `-O0` inlines the calls of `@inline` functions, and changes nothing else.
if this.options.level == 0 {
this.sweep(index, &mut sweep, pass::inline);
if sweep.changes != 0 {
this.compact_function(index, &mut sweep);
}
return;
}
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
if this.options.level < 2 && this.inlines_marked() {
this.sweep(index, &mut sweep, pass::inline);
}
if this.options.level >= 2 {
this.sweep(index, &mut sweep, pass::dead);
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# Promoting may show which function a value calls, which is then called and
# inlined as any other.
this.sweep(index, &mut sweep, pass::inline);
this.sweep(index, &mut sweep, pass::promote);
this.sweep(index, &mut sweep, pass::simplify);
this.sweep(index, &mut sweep, pass::control);
# The function calling it copies it whole and optimizes it there, so the
# rest is left until then, and run after only where it is still called.
if this.awaits_caller(index) {
this.program.functions[index].unfinished = true;
return;
}
}
this.finish_function(index, &mut sweep);
}
#! Runs the passes after inlining on a function's code, then compacts it.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::finish_function(&mut this, index: u32, sweep: &mut passes): void {
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::memory);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::loops);
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::simplify);
this.sweep(index, sweep, pass::control);
this.sweep(index, sweep, pass::sink);
# What sinking moved past a branch, as a `select` on the condition the branch
# tests, is numbered again where the branch decided it.
this.sweep(index, sweep, pass::numbering);
this.sweep(index, sweep, pass::dead);
this.sweep(index, sweep, pass::hoist);
this.compact_function(index, sweep);
}
#! Whether a function, its calls inlined, is left for the function calling it
#! to optimize: that alone calls it, and copies it whole, as it may be copied,
#! asks nothing of the processor, and leaves that function room to grow.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether it is.
def lowerer::awaits_caller(&this, index: u32): bool {
val held := &this.program.functions[index];
return false if held.inlining.sole == 0 || held.closure || held.evaluation != 0;
var size: u32 = 0;
var walk := held.body.walk_all();
while walk.more() {
match held.body.insts[walk.next()].kind {
op::frame, op::ready, op::reach, op::same, op::cpu => { return false; }
else => {}
}
size++;
}
return size <= sole_growth;
}
#! What optimizing one function knows of the passes run on it.
struct passes {
var ranks: &vector<u32>; #! Where each function is in the order functions are optimized in.
var rank: u32; #! Where the function is.
var found: &mut vector<string>; #! What verifying it finds.
var changes: u32; #! How many passes changed something.
var compacted: u32; #! How many passes had changed something when the code was last compacted, or `0xFFFFFFFF` before it was.
var clean: u32[pass::count as u64]; #! How many passes had changed something when each last found nothing to change.
}
#! Runs a pass over a function's code, but where it found nothing to change
#! since any pass last changed something.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
#! @param which The pass.
def lowerer::sweep(&mut this, index: u32, sweep: &mut passes, which: pass): void {
return if sweep.clean[which as u64] == sweep.changes;
if this.run_pass(index, which, sweep) {
sweep.changes++;
} else {
sweep.clean[which as u64] = sweep.changes;
}
}
#! Compacts a function's code where a pass changed it since it was last
#! compacted, then verifies it where lowering verifies.
#! @param this The compiler.
#! @param index The function.
#! @param sweep What is known of the passes run on it.
def lowerer::compact_function(&mut this, index: u32, sweep: &mut passes): void {
return if sweep.compacted == sweep.changes;
sweep.compacted = sweep.changes;
val point := mark_scratch();
this.program.functions[index].body.compact();
if this.options.verify {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after compacting: {each}");
}
}
release_scratch(point);
}
#! Cleans up the memory of the cells of a function's code, knowing what each
#! call writes what it returns to.
#! @param this The compiler.
#! @param index The function.
#! @returns Whether anything changed.
def lowerer::clean_memory(&mut this, index: u32): bool {
val writes := this.result_writes(index);
return this.program.functions[index].body.clean_memory(writes.view());
}
#! How many bytes each call of a function's code writes what it returns to, at
#! the address its last operand gives, as `emitter::call_with` passes it. Each
#! instruction is looked at where it lies, those taken out too, which nothing
#! asks of.
#! @param this The compiler.
#! @param index The function.
#! @returns The bytes, by instruction, or 0 for what writes none.
pub def lowerer::result_writes(&this, index: u32): vector<u64> {
val body := &this.program.functions[index].body;
var writes := vector::<u64>::new(scratch());
writes.resize(body.insts.length);
for at in 1..body.insts.length {
val kind := body.insts[at].kind;
val aux: u32 = body.insts[at].aux;
var signature: u32 = no_function;
if kind == op::call {
signature = this.program.functions[aux].signature;
} else if kind == op::call_trait || kind == op::call_value || kind == op::call_c {
signature = aux;
}
continue if signature == no_function;
val shape := this.layout_at(this.program.signatures[signature].result);
if returned_in_memory(&shape) {
writes[at] = shape.size;
}
}
return writes;
}
#! Runs a pass over a function's code, then verifies it where lowering
#! verifies, noting what is wrong with what the pass left.
#! @param this The compiler.
#! @param index The function.
#! @param which The pass.
#! @param sweep What is known of the passes run on it.
#! @returns Whether the pass changed anything.
def lowerer::run_pass(&mut this, index: u32, which: pass, sweep: &mut passes): bool {
# What the pass and the verifier work out is freed as the pass ends.
val point := mark_scratch();
val body := &mut this.program.functions[index].body;
val changed := match which {
pass::simplify => body.simplify(this.program.data.view()),
pass::dead => body.remove_dead(),
pass::control => body.clean_control(),
pass::inline => this.inline_calls(index, sweep.ranks, sweep.rank),
pass::promote => body.promote_cells(),
pass::numbering => this.number_values(index),
pass::hoist => body.hoist_constants(),
pass::memory => this.clean_memory(index),
pass::loops => this.optimize_loops(index),
pass::sink => this.sink_code(index),
else => false
};
# Each pass forgets the order and dominators the code keeps where it changes
# where blocks lead, or works them out anew, as pruning does after inlining,
# so they hold for the code it leaves.
if this.options.verify && changed {
val verdict := this.program.functions[index].body.verify();
for &each in verdict.problems {
sweep.found.append($"{this.program.functions[index].name}: after {which.name()}: {each}");
}
}
release_scratch(point);
return changed;
}