Files
sakurac/compiler/optimizer/simplify.sakura
T
2026-12-06 13:52:57 -06:00

1195 lines
42 KiB
Plaintext

#! @file simplify.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the first pass of the optimizer, simplification: an operator of
#! constants becomes the constant it gives, worked out exactly as the machine
#! works it out; an operator whose result its operands already say becomes
#! that, as `x + 0` is `x` and `x == x` is 1; a multiplication, division, or
#! remainder of an unsigned word by a power of two becomes a shift or a mask;
#! a comparison with the least or greatest word says what it says of every
#! word, or asks only whether a word is one; a constant added to a word with a
#! constant added becomes one sum; a read of a datum, which is never written,
#! becomes what its bytes hold; a condition another says the opposite of is
#! read through it; a `select` whose choice is known is what it chooses; and a
#! check of what is known to hold goes.
#!
#! Then what LLVM's simplifying does besides, where it gives what it did: a
#! constant applied to a word a constant was applied to by the same operator
#! is applied once, as `(x * 3) * 5` is `x * 15`; a sum of a constant read once,
#! multiplied or shifted, is the sum of the products, and a constant added
#! within a sum is added last, so `xs[i + 1]` is read at an offset from where
#! `xs[i]` is; a comparison of a sum with a constant compares what the constant
#! was added to, as `x + 1 == 5` is `x == 4`; `(x + y) - y` is `x`; and, as IEEE
#! 754 works them out exactly, a product with 1 is the real and with -1 its
#! negation, a quotient by a power of two is the product with its reciprocal,
#! and an `f32` negated or chosen is not rounded again.
module sakura::compiler;
#! Simplifies the code, as the file says, in one walk of its blocks.
#! @param this The code.
#! @param data The program's datums, which reads of them are read from.
#! @returns Whether anything changed.
pub def code::simplify(&mut this, data: span<datum>): bool {
var done := rewrite::new();
var order := vector::<u32>::new(scratch());
var number := vector::<u32>::new(scratch());
var uses := vector::<u32>::new(scratch());
this.block_order(&mut order, &mut number);
for &block in order {
var walk := this.walk(block);
while walk.more() {
this.simplify_inst(walk.next(), data, &mut uses, &mut done);
}
}
this.apply(&done);
return done.changed;
}
#! Whether a value is read once, as how often each value was read where the
#! pass began says, worked out the first time it is asked. What the pass
#! replaced since may be read more, which only makes a rewrite asking this
#! leave a value worked out twice.
#! @param this The code.
#! @param value The value.
#! @param uses How often each value is read, or empty before it is asked.
#! @returns Whether it is.
def code::read_once(&this, value: u32, uses: &mut vector<u32>): bool {
if uses.length == 0 {
uses.extend(this.use_counts().span);
}
return (value as u64) < uses.length && uses[value] == 1;
}
#! Simplifies one instruction.
#! @param this The code.
#! @param index The instruction.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::simplify_inst(&mut this, index: u32, data: span<datum>, uses: &mut vector<u32>, done: &mut rewrite): void {
val held: inst = this.insts[index];
val kind := held.kind;
val number := kind as u32;
# Operands read what replaced them, so what is worked out of one value is
# worked out of what it was replaced by.
for i in 0..held.argc {
val at := held.args as u64 + i as u64;
this.operands[at] = done.resolve(this.operands[at]);
}
if number >= op::add as u32 && number <= op::leus as u32 {
this.simplify_word(index, uses, done);
return;
}
if number >= op::fadd as u32 && number <= op::fle as u32 {
var x: u64 = 0;
var y: u64 = 0;
val known_x := this.real_constant(this.arg(index, 0), &mut x);
val known_y := this.real_constant(this.arg(index, 1), &mut y);
if known_x && known_y {
var made: u64 = 0;
if fold_real(kind, x, y, &mut made) {
if number >= op::feq as u32 {
this.become_word(index, made);
} else {
this.become_real(index, made);
}
done.changed = true;
}
} else if known_y {
this.simplify_real(index, this.arg(index, 0), y, done);
} else if known_x && (kind == op::fadd || kind == op::fmul) {
this.simplify_real(index, this.arg(index, 1), x, done);
}
return;
}
if number >= op::neg as u32 && number <= op::bswap as u32 {
this.simplify_unary(index, done);
return;
}
match kind {
op::wrap => this.simplify_wrap(index, done);
op::check => {
var bits: u64 = 0;
val cond := this.arg(index, 0);
if this.word_constant(cond, &mut bits) && bits != 0 {
done.remove(index);
return;
}
# The address of a cell, the globals, or a datum is never null.
val made := this.defining(cond);
if made != 0 && (this.insts[made].kind == op::cell || this.insts[made].kind == op::global || this.insts[made].kind == op::datum) {
done.remove(index);
return;
}
# A check of whether a word is not zero checks the word.
val inner := this.defining(cond);
if inner != 0 && this.insts[inner].kind == op::ne && this.is_zero(this.arg(inner, 1)) {
this.operands[held.args] = this.arg(inner, 0);
done.changed = true;
}
}
op::branch => this.simplify_branch(index, done);
op::select => this.simplify_select(index, done);
op::load => {
this.fold_offset(index, done);
this.read_datum(index, data, done);
}
op::store => {
this.fold_offset(index, done);
this.simplify_store(index, done);
}
else => {}
}
}
#! The offsets a read or write may be given by folding: a page, less the widest
#! access.
const folded_reach: u64 = 4096 - 32;
#! Folds a constant added to the address a read or write is given into its
#! offset, so it is addressed as `[base + offset]` and a cell read at a field is
#! read at that offset of the cell. Only offsets within the page no program
#! maps, which reaching through null faults in on its own; one past it would
#! need an executable to test the base first.
#! @param this The code.
#! @param index The `load` or `store`.
#! @param done What the pass changes.
def code::fold_offset(&mut this, index: u32, done: &mut rewrite): void {
val inner := this.defining(this.arg(index, 0));
return if inner == 0 || this.insts[inner].kind != op::add;
var bits: u64 = 0;
var base: u32 = 0;
if this.word_constant(this.arg(inner, 1), &mut bits) {
base = this.arg(inner, 0);
} else if this.word_constant(this.arg(inner, 0), &mut bits) {
base = this.arg(inner, 1);
} else {
return;
}
val offset := this.insts[index].imm + bits;
return if bits >= folded_reach || offset >= folded_reach;
this.operands[this.insts[index].args as u64] = base;
this.insts[index].imm = offset;
done.changed = true;
}
#! Reads while compiling what a read of a datum reads, since a datum is never
#! written: the word or real its bytes hold, or, for a whole word where a
#! relocation is, the address it holds. A read of an `f32`, of lanes, or across
#! part of an address stays.
#! @param this The code.
#! @param index The `load`.
#! @param data The program's datums.
#! @param done What the pass changes.
def code::read_datum(&mut this, index: u32, data: span<datum>, done: &mut rewrite): void {
val from := this.defining(this.arg(index, 0));
return if from == 0 || this.insts[from].kind != op::datum;
val target: u64 = this.insts[from].aux;
return if target >= data.length;
val held := &data[target];
val how := this.insts[index].aux as access;
return if how == access::f32 || how == access::bytes || how.value_type().lanes();
val width := how.width();
val start := this.insts[from].imm + this.insts[index].imm;
return if start >= held.bytes.length || width > held.bytes.length - start;
for &each in held.relocations {
continue if each.at + word_size <= start || each.at >= start + width;
return if each.at != start || how != access::i64;
this.become(index, op::datum, span::<u32>::blank(), each.target, each.addend);
done.changed = true;
return;
}
var bits: u64 = 0;
for i in 0..width {
bits = bits | ((held.bytes[start + i as u64] as u64) << (8 * i as u64));
}
match how {
access::i8 => bits = wrap_word(bits, 8, true);
access::i16 => bits = wrap_word(bits, 16, true);
access::i32 => bits = wrap_word(bits, 32, true);
access::f64 => {
this.become_real(index, bits);
done.changed = true;
return;
}
else => {}
}
this.become_word(index, bits);
done.changed = true;
}
#! Simplifies a write of a narrow value: one narrowed to at least as many bits
#! as the write keeps, or an `f32` rounded already, is written as it was.
#! @param this The code.
#! @param index The `store`.
#! @param done What the pass changes.
def code::simplify_store(&mut this, index: u32, done: &mut rewrite): void {
val value := this.arg(index, 1);
val inner := this.defining(value);
return if inner == 0;
val how := this.insts[index].aux as access;
val kind := this.insts[inner].kind;
if kind == op::fsingle && how == access::f32 {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
return;
}
return if kind != op::wrap || how == access::f32 || how == access::f64 || how == access::bytes;
if this.insts[inner].aux as u64 >= 8 * how.width() {
this.operands[this.insts[index].args as u64 + 1] = this.arg(inner, 0);
done.changed = true;
}
}
#! Whether a value is known to have every bit of a word set: the processor's
#! instruction sets, where a version knows which it has.
#! @param this The code.
#! @param value The value.
#! @param bits The bits.
#! @returns Whether it is.
def code::holds_bits(&this, value: u32, bits: u64): bool {
val made := this.defining(value);
return made != 0 && this.insts[made].kind == op::cpu && (bits & ~this.insts[made].imm) == 0;
}
#! Simplifies an operator of a real and a constant where IEEE 754 says exactly
#! what it gives from the real: a product with 1, or a quotient by 1, is the
#! real, and with -1 its negation; a sum with -0, or a difference with 0, is
#! the real; and a quotient by a power of two whose reciprocal is a normal real
#! is the product with that reciprocal, which rounds the same, as dividing costs
#! several times what multiplying does.
#! @param this The code.
#! @param index The `fadd`, `fsub`, `fmul`, or `fdiv`.
#! @param x The real.
#! @param c The bits of the constant: of the right operand, or of the
#! left of a sum or product.
#! @param done What the pass changes.
def code::simplify_real(&mut this, index: u32, x: u32, c: u64, done: &mut rewrite): void {
val kind := this.insts[index].kind;
match kind {
op::fmul, op::fdiv => {
if c == real_one {
this.forward_to(index, x, done);
return;
}
if c == (real_one | real_sign) {
var operands: u32[1] = [x];
this.become(index, op::fneg, operands[0:1], 0, 0);
done.changed = true;
return;
}
return if kind != op::fdiv;
val exponent := (c >> 52) & 0x7FF;
return if (c & 0xFFFFFFFFFFFFF) != 0 || exponent == 0 || exponent >= 2046;
var operands: u32[2] = [x, this.real_value((c & real_sign) | ((2046 - exponent) << 52))];
this.become(index, op::fmul, operands[0:2], 0, 0);
done.changed = true;
}
op::fadd => {
if c == real_sign {
this.forward_to(index, x, done);
}
}
op::fsub => {
if c == 0 {
this.forward_to(index, x, done);
}
}
else => {}
}
}
#! The bits of the real 1.
const real_one: u64 = 0x3FF0000000000000u;
#! The sign bit of a real, which is also the bits of -0.
const real_sign: u64 = 0x8000000000000000u;
#! Simplifies an operator of two words.
#! @param this The code.
#! @param index The instruction.
#! @param uses How often each value is read, as `read_once` works it out.
#! @param done What the pass changes.
def code::simplify_word(&mut this, index: u32, uses: &mut vector<u32>, done: &mut rewrite): void {
val kind := this.insts[index].kind;
var a := this.arg(index, 0);
var b := this.arg(index, 1);
var x: u64 = 0;
var y: u64 = 0;
val known_a := this.word_constant(a, &mut x);
val known_b := this.word_constant(b, &mut y);
if known_a && known_b {
var made: u64 = 0;
if fold_word(kind, x, y, &mut made) {
this.become_word(index, made);
done.changed = true;
}
return;
}
# A constant goes on the right of what does not mind which side it is on.
var right := known_b;
if known_a && !known_b && commutes(kind) {
var swapped: u32[2] = [b, a];
this.become(index, kind, swapped[0:2], 0, 0);
a = swapped[0];
b = swapped[1];
y = x;
right = true;
done.changed = true;
}
# What the operands say whatever they are.
if a == b {
match kind {
op::sub, op::bxor, op::ne, op::ltu, op::lts => {
this.become_word(index, 0);
done.changed = true;
return;
}
op::eq, op::leu, op::les => {
this.become_word(index, 1);
done.changed = true;
return;
}
op::band, op::bor => {
this.forward_to(index, a, done);
return;
}
else => {}
}
}
# A never-zero address compared with zero.
if (kind == op::eq || kind == op::ne) && this.is_zero(b) && this.never_zero(a) {
this.become_word(index, kind == op::ne ? 1 : 0);
done.changed = true;
return;
}
if known_a && !right {
this.simplify_left_order(index, b, x, done);
return;
}
if !right {
this.simplify_values(index, a, b, uses, done);
return;
}
match kind {
op::add, op::sub => {
if y == 0 {
this.forward_to(index, a, done);
} else {
this.combine_steps(index, a, kind == op::add ? y : 0 - y, done);
}
}
op::bor, op::bxor, op::shl, op::shru, op::shrs => {
if y == 0 {
this.forward_to(index, a, done);
} else if kind != op::shl || !this.distribute(index, a, y, uses, done) {
this.reassociate(index, a, y, done);
}
}
op::mul => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.forward_to(index, a, done);
} else if is_power(y) {
this.become_shift(index, op::shl, a, log2(y));
done.changed = true;
} else if !this.distribute(index, a, y, uses, done) {
this.reassociate(index, a, y, done);
}
}
op::eq, op::ne => this.simplify_equality(index, a, y, done);
op::divs, op::divu => {
if y == 1 {
this.forward_to(index, a, done);
} else if kind == op::divu && is_power(y) {
this.become_shift(index, op::shru, a, log2(y));
done.changed = true;
}
}
op::rems, op::remu => {
if y == 1 {
this.become_word(index, 0);
done.changed = true;
} else if kind == op::remu && is_power(y) {
var operands: u32[2] = [a, this.word_value(y - 1)];
this.become(index, op::band, operands[0:2], 0, 0);
done.changed = true;
}
}
op::band => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 0xFFFFFFFFFFFFFFFFu {
this.forward_to(index, a, done);
} else if this.holds_bits(a, y) {
this.become_word(index, y);
done.changed = true;
} else {
this.reassociate(index, a, y, done);
}
}
op::ltu => {
if y == 0 {
this.become_word(index, 0);
done.changed = true;
} else if y == 1 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::leu => {
if y == greatest_unsigned {
this.become_word(index, 1);
done.changed = true;
} else if y == 0 {
this.become_compare(index, op::eq, a, 0);
done.changed = true;
}
}
op::lts => {
if y == least_signed {
this.become_word(index, 0);
done.changed = true;
} else if y == least_signed + 1 {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
op::les => {
if y == greatest_signed {
this.become_word(index, 1);
done.changed = true;
} else if y == least_signed {
this.become_compare(index, op::eq, a, least_signed);
done.changed = true;
}
}
else => {}
}
}
#! Simplifies an operator of two words neither known, as LLVM's simplifying
#! does: a sum less what it added is what it added to, `(x + y) - y` being `x`,
#! and a difference plus what it took away is what it took from; and a sum
#! adding a constant within another sum adds it last, as
#! `a + (b + 8)` is `(a + b) + 8`, so an address so worked out steps by the
#! constant from the rest, which a read or write takes as its offset.
#! @param this The code.
#! @param index The instruction.
#! @param a Its left operand.
#! @param b Its right operand.
#! @param uses How often each value is read, as `read_once` works it out.
#! @param done What the pass changes.
def code::simplify_values(&mut this, index: u32, a: u32, b: u32, uses: &mut vector<u32>, done: &mut rewrite): void {
match this.insts[index].kind {
op::sub => {
val inner := this.defining(a);
if inner != 0 && this.insts[inner].kind == op::add {
if this.arg(inner, 1) == b {
this.forward_to(index, this.arg(inner, 0), done);
return;
}
if this.arg(inner, 0) == b {
this.forward_to(index, this.arg(inner, 1), done);
return;
}
}
val taken := this.defining(b);
if taken != 0 && this.insts[taken].kind == op::sub && this.arg(taken, 0) == a {
this.forward_to(index, this.arg(taken, 1), done);
}
}
op::add => {
var sides: u32[2] = [a, b];
for k in 0..2u {
val inner := this.defining(sides[k]);
if inner != 0 && this.insts[inner].kind == op::sub && this.arg(inner, 1) == sides[1 - k] {
this.forward_to(index, this.arg(inner, 0), done);
return;
}
}
for k in 0..2u {
val inner := this.defining(sides[k]);
continue if inner == 0 || this.insts[inner].kind != op::add || !this.read_once(sides[k], uses);
var step: u64 = 0;
continue if !this.word_constant(this.arg(inner, 1), &mut step);
var gives: vt[1] = [vt::word];
var operands: u32[2] = [sides[1 - k], this.arg(inner, 0)];
val rest := this.detached(op::add, operands[0:2], gives[0:1], 0, 0, this.insts[index].at, this.insts[index].site);
this.link_before(rest, index);
var sum: u32[2] = [this.insts[rest].result, this.arg(inner, 1)];
this.become(index, op::add, sum[0:2], 0, 0);
done.changed = true;
return;
}
}
else => {}
}
}
#! Folds an operator of a word and a constant into the same operator of a
#! constant that gave the word, as `(x * 3) * 5` is `x * 15` and
#! `(x << 2) << 3` is `x << 5`, so one operator does what two did.
#! @param this The code.
#! @param index The `mul`, `band`, `bor`, `bxor`, or shift.
#! @param a The word.
#! @param y The constant.
#! @param done What the pass changes.
def code::reassociate(&mut this, index: u32, a: u32, y: u64, done: &mut rewrite): void {
val kind := this.insts[index].kind;
val inner := this.defining(a);
return if inner == 0 || this.insts[inner].kind != kind;
var c: u64 = 0;
return if !this.word_constant(this.arg(inner, 1), &mut c);
var folded: u64 = 0;
match kind {
op::mul => folded = c * y;
op::band => folded = c & y;
op::bor => folded = c | y;
op::bxor => folded = c ^ y;
op::shl, op::shru => {
return if c >= 64 || y >= 64 || c + y >= 64;
folded = c + y;
}
op::shrs => {
# Shifting a signed word right past its bits leaves its sign throughout,
# as shifting it by 63 does.
return if c >= 64 || y >= 64;
folded = c + y >= 64 ? 63 : c + y;
}
else => return;
}
var operands: u32[2] = [this.arg(inner, 0), this.word_value(folded)];
this.become(index, kind, operands[0:2], 0, 0);
done.changed = true;
}
#! Multiplies or shifts a sum of a word and a constant, which nothing else
#! reads, as the sum of the word multiplied or shifted and the constant
#! multiplied or shifted, so `(i + 1) << 3` is `(i << 3) + 8`: the element after
#! `i`'s is then addressed from `i`'s, at an offset, and the two addresses are
#! worked out once.
#! @param this The code.
#! @param index The `mul` or `shl`.
#! @param a The sum.
#! @param y The constant multiplied or shifted by.
#! @param uses How often each value is read, as `read_once` works it out.
#! @param done What the pass changes.
#! @returns Whether it was.
def code::distribute(&mut this, index: u32, a: u32, y: u64, uses: &mut vector<u32>, done: &mut rewrite): bool {
val kind := this.insts[index].kind;
return false if kind == op::shl && y >= 64;
val inner := this.defining(a);
return false if inner == 0 || this.insts[inner].kind != op::add;
var c: u64 = 0;
return false if !this.word_constant(this.arg(inner, 1), &mut c) || !this.read_once(a, uses);
var gives: vt[1] = [vt::word];
var operands: u32[2] = [this.arg(inner, 0), this.arg(index, 1)];
val scaled := this.detached(kind, operands[0:2], gives[0:1], 0, 0, this.insts[index].at, this.insts[index].site);
this.link_before(scaled, index);
var sum: u32[2] = [this.insts[scaled].result, this.word_value(kind == op::shl ? c << y : c * y)];
this.become(index, op::add, sum[0:2], 0, 0);
done.changed = true;
return true;
}
#! Compares with a constant what a constant was added to, taken from, or
#! flipped by, rather than what that gave, so `x + 1 == n` asks whether `x` is
#! `n - 1`, as `match`es of words worked out so do.
#! @param this The code.
#! @param index The `eq` or `ne`.
#! @param a What it compares.
#! @param y The constant it compares with.
#! @param done What the pass changes.
def code::simplify_equality(&mut this, index: u32, a: u32, y: u64, done: &mut rewrite): void {
val inner := this.defining(a);
return if inner == 0;
val kind := this.insts[inner].kind;
return if kind != op::add && kind != op::sub && kind != op::bxor;
var c: u64 = 0;
return if !this.word_constant(this.arg(inner, 1), &mut c);
var target: u64 = 0;
match kind {
op::add => target = y - c;
op::sub => target = y + c;
else => target = y ^ c;
}
this.become_compare(index, this.insts[index].kind, this.arg(inner, 0), target);
done.changed = true;
}
#! Whether a real is known to be an `f32`, as what rounds to one, reads one, or
#! negates or chooses between those gives, so rounding it again changes
#! nothing.
#! @param this The code.
#! @param value The real.
#! @param depth How far back through negations and choices it is looked for.
#! @returns Whether it is.
def code::is_single(&this, value: u32, depth: u32): bool {
val made := this.defining(value);
return false if made == 0 || depth == 0;
val held: inst = this.insts[made];
match held.kind {
op::fsingle => return true;
op::load => return held.aux == access::f32 as u32;
op::fconst => return bits_of_real((real_of(held.imm) as f32) as f64) == held.imm;
op::fneg => return this.is_single(this.arg(made, 0), depth - 1);
op::select => return this.is_single(this.arg(made, 1), depth - 1) && this.is_single(this.arg(made, 2), depth - 1);
else => return false;
}
return false;
}
#! The greatest unsigned word.
const greatest_unsigned: u64 = 0xFFFFFFFFFFFFFFFFu;
#! The least signed word, as its bits.
const least_signed: u64 = 0x8000000000000000u;
#! The greatest signed word, as its bits.
const greatest_signed: u64 = 0x7FFFFFFFFFFFFFFFu;
#! Simplifies an order whose left operand is a constant, which stays on the
#! left: one no word comes after, or every word does, says what it says of
#! every word, as `MAX < x` is 0, and one only a single word comes after asks
#! whether the word is that one, as `0 < x` asks whether `x` is not zero.
#! @param this The code.
#! @param index The comparison.
#! @param b Its right operand.
#! @param x The constant on its left.
#! @param done What the pass changes.
def code::simplify_left_order(&mut this, index: u32, b: u32, x: u64, done: &mut rewrite): void {
match this.insts[index].kind {
op::ltu => {
if x == greatest_unsigned {
this.become_word(index, 0);
} else if x == 0 {
this.become_compare(index, op::ne, b, 0);
} else {
return;
}
}
op::leu => {
if x == 0 {
this.become_word(index, 1);
} else if x == greatest_unsigned {
this.become_compare(index, op::eq, b, greatest_unsigned);
} else {
return;
}
}
op::lts => {
if x == greatest_signed {
this.become_word(index, 0);
} else if x == least_signed {
this.become_compare(index, op::ne, b, least_signed);
} else {
return;
}
}
op::les => {
if x == least_signed {
this.become_word(index, 1);
} else if x == greatest_signed {
this.become_compare(index, op::eq, b, greatest_signed);
} else {
return;
}
}
else => return;
}
done.changed = true;
}
#! Makes an instruction a comparison of a word with a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The comparison.
#! @param a The word.
#! @param bits The constant.
def code::become_compare(&mut this, index: u32, kind: op, a: u32, bits: u64): void {
var operands: u32[2] = [a, this.word_value(bits)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Adds a constant to a word that is itself a word with a constant added or
#! taken away, as one sum of both, so `(x + 4) + 8` is `x + 12`, and the inner
#! one goes where nothing else reads it.
#! @param this The code.
#! @param index The `add` or `sub`.
#! @param a The word it adds to.
#! @param step What it adds, as a wrapping word: what a `sub` takes away, negated.
#! @param done What the pass changes.
def code::combine_steps(&mut this, index: u32, a: u32, step: u64, done: &mut rewrite): void {
val inner := this.defining(a);
return if inner == 0;
val kind := this.insts[inner].kind;
return if kind != op::add && kind != op::sub;
var bits: u64 = 0;
return if !this.word_constant(this.arg(inner, 1), &mut bits);
val total := step + (kind == op::add ? bits : 0 - bits);
val base := this.arg(inner, 0);
if total == 0 {
this.forward_to(index, base, done);
return;
}
var operands: u32[2] = [base, this.word_value(total)];
this.become(index, op::add, operands[0:2], 0, 0);
done.changed = true;
}
#! Makes an instruction a shift of a word by a constant.
#! @param this The code.
#! @param index The instruction.
#! @param kind The shift.
#! @param a The word.
#! @param by How far it shifts.
def code::become_shift(&mut this, index: u32, kind: op, a: u32, by: u64): void {
var operands: u32[2] = [a, this.word_value(by)];
this.become(index, kind, operands[0:2], 0, 0);
}
#! Replaces what an instruction gives with a value, taking the instruction out.
#! @param this The code.
#! @param index The instruction.
#! @param value The value its result is.
#! @param done What the pass changes.
def code::forward_to(&mut this, index: u32, value: u32, done: &mut rewrite): void {
done.replace(this.insts[index].result, value);
done.remove(index);
}
#! Whether a value is the word zero.
#! @param this The code.
#! @param value The value.
#! @returns Whether it is.
def code::is_zero(&this, value: u32): bool {
var bits: u64 = 0;
return this.word_constant(value, &mut bits) && bits == 0;
}
#! Simplifies an operator of one value.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_unary(&mut this, index: u32, done: &mut rewrite): void {
val kind := this.insts[index].kind;
val a := this.arg(index, 0);
var bits: u64 = 0;
val word := this.word_constant(a, &mut bits);
val real := !word && this.real_constant(a, &mut bits);
if word || real {
var made: u64 = 0;
val gives_real := kind == op::fneg || kind == op::itof || kind == op::utof || kind == op::fsingle || kind == op::fsqrt;
if fold_unary(kind, bits, &mut made) {
if gives_real {
this.become_real(index, made);
} else {
this.become_word(index, made);
}
done.changed = true;
}
return;
}
val inner := this.defining(a);
return if inner == 0;
val from: inst = this.insts[inner];
match kind {
# The opposite of a comparison is the comparison that says it.
op::lnot => {
var flipped := op::count;
var swap := false;
match from.kind {
op::eq => flipped = op::ne;
op::ne => flipped = op::eq;
op::ltu => { flipped = op::leu; swap = true; }
op::leu => { flipped = op::ltu; swap = true; }
op::lts => { flipped = op::les; swap = true; }
op::les => { flipped = op::lts; swap = true; }
op::ltsu => { flipped = op::leus; swap = true; }
op::lesu => { flipped = op::ltus; swap = true; }
op::ltus => { flipped = op::lesu; swap = true; }
op::leus => { flipped = op::ltsu; swap = true; }
op::lnot => {
if this.is_flag(this.arg(inner, 0)) {
this.forward_to(index, this.arg(inner, 0), done);
}
return;
}
else => return;
}
val x := this.arg(inner, 0);
val y := this.arg(inner, 1);
var operands: u32[2] = swap ? [y, x] : [x, y];
this.become(index, flipped, operands[0:2], 0, 0);
done.changed = true;
}
op::fsingle => {
if this.is_single(a, 4) {
this.forward_to(index, a, done);
}
}
op::neg, op::bnot, op::fneg => {
if from.kind == kind {
this.forward_to(index, this.arg(inner, 0), done);
}
}
else => {}
}
}
#! Whether a word is 0 or 1, as a comparison gives.
#! @param this The code.
#! @param value The word.
#! @returns Whether it is.
def code::is_flag(&this, value: u32): bool {
var bits: u64 = 0;
return bits <= 1 if this.word_constant(value, &mut bits);
val index := this.defining(value);
return false if index == 0;
val number := this.insts[index].kind as u32;
return (number >= op::eq as u32 && number <= op::leus as u32)
|| (number >= op::feq as u32 && number <= op::fle as u32)
|| number == op::lnot as u32;
}
#! Simplifies the narrowing of a word, which goes where the word is already as
#! narrow, and narrows what was narrowed less where it narrows more, or the
#! same, the other way: `wrap(wrap(x, 32, unsigned), 32, signed)` is
#! `wrap(x, 32, signed)`.
#! @param this The code.
#! @param index The instruction.
#! @param done What the pass changes.
def code::simplify_wrap(&mut this, index: u32, done: &mut rewrite): void {
val held: inst = this.insts[index];
val a := this.arg(index, 0);
val bits := held.aux;
val signed := held.imm != 0;
if bits >= 64 {
this.forward_to(index, a, done);
return;
}
var value: u64 = 0;
if this.word_constant(a, &mut value) {
this.become_word(index, wrap_word(value, bits, signed));
done.changed = true;
return;
}
# The bits a word is held in already, and whether they are signed.
var held_bits: u32 = 64;
var held_signed := false;
val inner := this.defining(a);
if inner != 0 {
val from: inst = this.insts[inner];
match from.kind {
op::wrap => {
held_bits = from.aux;
held_signed = from.imm != 0;
# Narrowing more than what was narrowed, or as much the other way, narrows
# the word itself.
if bits < held_bits || (bits == held_bits && signed != held_signed) {
var operands: u32[1] = [this.arg(inner, 0)];
this.become(index, op::wrap, operands[0:1], bits, held.imm);
done.changed = true;
return;
}
}
op::load, op::atomic => {
match from.kind == op::load ? from.aux as access : atomic_access(from.imm) {
access::u8 => held_bits = 8;
access::i8 => { held_bits = 8; held_signed = true; }
access::u16 => held_bits = 16;
access::i16 => { held_bits = 16; held_signed = true; }
access::u32 => held_bits = 32;
access::i32 => { held_bits = 32; held_signed = true; }
else => {}
}
}
else => {
if this.is_flag(a) {
held_bits = 1;
}
}
}
}
if (signed == held_signed && bits >= held_bits) || (!held_signed && bits > held_bits) || this.param_narrow(a, bits, signed) {
this.forward_to(index, a, done);
}
}
#! Whether a block's parameter is a word as narrow as a narrowing makes it
#! already: every edge into the block gives it one so narrowed, or the
#! parameter itself, as a loop keeps a field of `i32` it adds to.
#! @param this The code.
#! @param value The parameter.
#! @param bits The bits it would be narrowed to.
#! @param signed Whether it would be extended by its sign.
#! @returns Whether it is.
def code::param_narrow(&this, value: u32, bits: u32, signed: bool): bool {
return false if value == 0 || (value as u64) >= this.origins.length;
val held: origin = this.origins[value];
return false if !held.param;
val preds := &this.blocks[held.from].preds;
return false if preds.length == 0;
for &e in preds.span {
val given: u32 = this.edges[e as u64].args[held.index as u64];
continue if given == value;
val made := this.defining(given);
return false if made == 0;
val from: inst = this.insts[made];
var fits := false;
if from.kind == op::wrap {
fits = (from.imm != 0) == signed ? from.aux <= bits : from.imm == 0 && from.aux < bits;
} else if from.kind == op::iconst {
fits = wrap_word(from.imm, bits, signed) == from.imm;
}
return false if !fits;
}
return true;
}
#! Simplifies a `branch`: one on a condition's opposite goes the other way on
#! the condition, and one on whether a word is not zero branches on the word.
#! @param this The code.
#! @param index The `branch`.
#! @param done What the pass changes.
def code::simplify_branch(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
if from.kind == op::lnot {
this.operands[this.insts[index].args] = this.arg(inner, 0);
this.swap_branch(index);
done.changed = true;
continue;
}
return if (from.kind != op::ne && from.kind != op::eq) || !this.is_zero(this.arg(inner, 1));
this.operands[this.insts[index].args] = this.arg(inner, 0);
if from.kind == op::eq {
this.swap_branch(index);
}
done.changed = true;
}
}
#! Simplifies a `select`: one on a constant, or between one value either way,
#! is the value it chooses; one on a condition's opposite, or on whether a word
#! is not zero, chooses on the condition or the word the other way round or the
#! same; one choosing 1 or 0 by a word is whether the word is not zero, which
#! is the word where it is 0 or 1, or is zero; and one choosing the condition
#! itself or 0 is the condition.
#! @param this The code.
#! @param index The `select`.
#! @param done What the pass changes.
def code::simplify_select(&mut this, index: u32, done: &mut rewrite): void {
var steps := 0;
while steps < 8 {
steps++;
val cond := this.arg(index, 0);
val a := this.arg(index, 1);
val b := this.arg(index, 2);
var bits: u64 = 0;
if this.word_constant(cond, &mut bits) {
this.forward_to(index, bits != 0 ? a : b, done);
return;
}
if a == b || (a == cond && this.is_zero(b)) {
this.forward_to(index, a, done);
return;
}
var x: u64 = 0;
var y: u64 = 0;
if this.word_constant(a, &mut x) && this.word_constant(b, &mut y) {
if x == 1 && y == 0 && this.is_flag(cond) {
this.forward_to(index, cond, done);
return;
}
if x == 1 && y == 0 {
var operands: u32[2] = [cond, this.word_value(0)];
this.become(index, op::ne, operands[0:2], 0, 0);
done.changed = true;
return;
}
if x == 0 && y == 1 {
var operands: u32[1] = [cond];
this.become(index, op::lnot, operands[0:1], 0, 0);
done.changed = true;
return;
}
}
# A condition worked out from another is read through it.
val inner := this.defining(cond);
return if inner == 0;
val from: inst = this.insts[inner];
val opposite := from.kind == op::lnot || (from.kind == op::eq && this.is_zero(this.arg(inner, 1)));
return if !opposite && (from.kind != op::ne || !this.is_zero(this.arg(inner, 1)));
var operands: u32[3] = opposite ? [this.arg(inner, 0), b, a] : [this.arg(inner, 0), a, b];
this.become(index, op::select, operands[0:3], 0, 0);
done.changed = true;
}
}
#! Whether an operator of two words gives the same whichever side each is on.
#! @param kind The operator.
#! @returns Whether it does.
def commutes(kind: op): bool {
return kind == op::add || kind == op::mul || kind == op::band || kind == op::bor || kind == op::bxor
|| kind == op::eq || kind == op::ne;
}
#! Whether a word is a power of two.
#! @param bits The word.
#! @returns Whether it is.
def is_power(bits: u64): bool {
return bits != 0 && (bits & (bits - 1)) == 0;
}
#! Which power of two a word is.
#! @param bits The word, a power of two.
#! @returns The power.
def log2(bits: u64): u64 {
var at := bits;
var power: u64 = 0;
while at > 1 {
at = at >> 1;
power++;
}
return power;
}
#! A word narrowed to a number of bits, as the machine narrows it.
#! @param value The word.
#! @param bits How many bits it keeps.
#! @param signed Whether it is sign-extended rather than zero-extended.
#! @returns The word narrowed.
pub def wrap_word(value: u64, bits: u32, signed: bool): u64 {
return value if bits >= 64;
val mask := (1u << bits as u64) - 1;
var made := value & mask;
if signed && (made >> (bits as u64 - 1)) != 0 {
made = made | ~mask;
}
return made;
}
#! What an operator of two words gives, as the machine works it out.
#! @param kind The operator.
#! @param a The first word.
#! @param b The second word.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything: not where it divides by zero, which
#! stops the program.
pub def fold_word(kind: op, a: u64, b: u64, made: &mut u64): bool {
match kind {
op::add => made = a + b;
op::sub => made = a - b;
op::mul => made = a * b;
op::divs, op::divu, op::rems, op::remu => {
return false if b == 0;
if kind == op::divu {
made = a / b;
} else if kind == op::remu {
made = a % b;
} else if (b as i64) == -1 {
made = kind == op::divs ? 0 - a : 0;
} else if kind == op::divs {
made = ((a as i64) / (b as i64)) as u64;
} else {
made = ((a as i64) % (b as i64)) as u64;
}
}
op::band => made = a & b;
op::bor => made = a | b;
op::bxor => made = a ^ b;
op::shl => made = a << b;
op::shru => made = a >> b;
op::shrs => made = ((a as i64) >> b) as u64;
op::eq => made = a == b ? 1 : 0;
op::ne => made = a != b ? 1 : 0;
op::lts => made = (a as i64) < (b as i64) ? 1 : 0;
op::ltu => made = a < b ? 1 : 0;
op::les => made = (a as i64) <= (b as i64) ? 1 : 0;
op::leu => made = a <= b ? 1 : 0;
op::eqsu => made = (a as i64) >= 0 && a == b ? 1 : 0;
op::ltsu => made = (a as i64) < 0 || a < b ? 1 : 0;
op::lesu => made = (a as i64) < 0 || a <= b ? 1 : 0;
op::ltus => made = (b as i64) >= 0 && a < b ? 1 : 0;
op::leus => made = (b as i64) >= 0 && a <= b ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of two reals gives, as the machine works it out: a real's
#! bits, or a word of 0 or 1 for a comparison.
#! @param kind The operator.
#! @param a The bits of the first real.
#! @param b The bits of the second real.
#! @param made Where what it gives is written.
#! @returns Whether it gives anything.
pub def fold_real(kind: op, a: u64, b: u64, made: &mut u64): bool {
val x := real_of(a);
val y := real_of(b);
match kind {
op::fadd => made = bits_of_real(x + y);
op::fsub => made = bits_of_real(x - y);
op::fmul => made = bits_of_real(x * y);
op::fdiv => made = bits_of_real(x / y);
op::frem => made = bits_of_real(x % y);
op::feq => made = x == y ? 1 : 0;
op::fne => made = x != y ? 1 : 0;
op::flt => made = x < y ? 1 : 0;
op::fle => made = x <= y ? 1 : 0;
else => return false;
}
return true;
}
#! What an operator of one value gives, as the machine works it out.
#! @param kind The operator.
#! @param a The bits of the word or real it takes.
#! @param made Where the bits of what it gives are written.
#! @returns Whether it gives anything.
pub def fold_unary(kind: op, a: u64, made: &mut u64): bool {
match kind {
op::neg => made = 0 - a;
op::bnot => made = ~a;
op::lnot => made = a == 0 ? 1 : 0;
op::fneg => made = bits_of_real(-real_of(a));
op::itof => made = bits_of_real((a as i64) as f64);
op::utof => made = bits_of_real(a as f64);
op::ftoi => made = (real_of(a) as i64) as u64;
op::ftou => made = real_of(a) as u64;
op::fsingle => made = bits_of_real((real_of(a) as f32) as f64);
op::fsqrt => made = bits_of_real(root_of(real_of(a)));
op::ones => made = ones_of(a);
op::clz => made = leading_zeros_of(a);
op::ctz => made = trailing_zeros_of(a);
op::bswap => made = bytes_swapped(a);
else => return false;
}
return true;
}