waffle/src/ir.rs

471 lines
13 KiB
Rust
Raw Normal View History

2021-11-13 00:16:54 -06:00
//! Intermediate representation for Wasm.
2022-11-01 22:43:47 -05:00
use crate::entity;
use crate::entity::{EntityRef, EntityVec};
use crate::{frontend, Operator};
2021-11-13 19:52:30 -06:00
use anyhow::Result;
2022-10-27 00:15:15 -05:00
use fxhash::FxHashSet;
2022-11-01 22:43:47 -05:00
use wasmparser::FuncType;
2021-11-13 00:16:54 -06:00
2022-11-01 22:43:47 -05:00
pub use wasmparser::Type;
2021-11-13 00:16:54 -06:00
2022-11-01 22:43:47 -05:00
entity!(Signature, "sig");
entity!(Func, "func");
entity!(Block, "block");
entity!(Local, "local");
entity!(Global, "global");
entity!(Table, "table");
entity!(Memory, "memory");
entity!(Value, "value");
2021-11-13 16:23:22 -06:00
#[derive(Clone, Debug, Default)]
2021-11-13 04:32:05 -06:00
pub struct Module<'a> {
2022-10-27 00:15:15 -05:00
orig_bytes: &'a [u8],
funcs: Vec<FuncDecl>,
signatures: Vec<FuncType>,
globals: Vec<Type>,
tables: Vec<Type>,
2022-11-01 22:43:47 -05:00
dirty_funcs: FxHashSet<Func>,
2022-10-27 00:15:15 -05:00
}
impl<'a> Module<'a> {
pub(crate) fn with_orig_bytes(orig_bytes: &'a [u8]) -> Module<'a> {
let mut m = Module::default();
m.orig_bytes = orig_bytes;
m
}
}
impl<'a> Module<'a> {
2022-11-01 22:43:47 -05:00
pub fn func<'b>(&'b self, id: Func) -> &'b FuncDecl {
&self.funcs[id.index()]
2022-10-27 00:15:15 -05:00
}
2022-11-01 22:43:47 -05:00
pub fn func_mut<'b>(&'b mut self, id: Func) -> &'b mut FuncDecl {
2022-10-27 00:15:15 -05:00
self.dirty_funcs.insert(id);
2022-11-01 22:43:47 -05:00
&mut self.funcs[id.index()]
2022-10-27 00:15:15 -05:00
}
2022-11-01 22:43:47 -05:00
pub fn signature<'b>(&'b self, id: Signature) -> &'b FuncType {
&self.signatures[id.index()]
2022-10-27 00:15:15 -05:00
}
2022-11-01 22:43:47 -05:00
pub fn global_ty(&self, id: Global) -> Type {
self.globals[id.index()]
2022-10-27 00:15:15 -05:00
}
2022-11-01 22:43:47 -05:00
pub fn table_ty(&self, id: Table) -> Type {
self.tables[id.index()]
2022-10-27 00:15:15 -05:00
}
pub(crate) fn frontend_add_signature(&mut self, ty: FuncType) {
self.signatures.push(ty);
}
pub(crate) fn frontend_add_func(&mut self, body: FuncDecl) {
self.funcs.push(body);
}
pub(crate) fn frontend_add_table(&mut self, ty: Type) {
self.tables.push(ty);
}
pub(crate) fn frontend_add_global(&mut self, ty: Type) {
self.globals.push(ty);
}
2021-11-13 00:16:54 -06:00
}
#[derive(Clone, Debug)]
2021-11-22 01:12:07 -06:00
pub enum FuncDecl {
2022-11-01 22:43:47 -05:00
Import(Signature),
Body(Signature, FunctionBody),
2021-11-13 04:32:05 -06:00
}
2021-11-22 01:12:07 -06:00
impl FuncDecl {
2022-11-01 22:43:47 -05:00
pub fn sig(&self) -> Signature {
2021-11-13 04:32:05 -06:00
match self {
2021-11-13 05:49:19 -06:00
FuncDecl::Import(sig) => *sig,
FuncDecl::Body(sig, ..) => *sig,
2021-11-13 04:32:05 -06:00
}
}
2022-10-27 00:15:15 -05:00
pub fn body(&self) -> Option<&FunctionBody> {
match self {
FuncDecl::Body(_, body) => Some(body),
_ => None,
}
}
pub fn body_mut(&mut self) -> Option<&mut FunctionBody> {
match self {
FuncDecl::Body(_, body) => Some(body),
_ => None,
}
}
2021-11-13 00:16:54 -06:00
}
#[derive(Clone, Debug, Default)]
2021-11-22 01:12:07 -06:00
pub struct FunctionBody {
2022-10-29 17:19:26 -05:00
/// How many parameters the function has. (Their types are the
/// first `n_params` values in `locals`.)
2021-12-24 17:17:38 -06:00
pub n_params: usize,
2022-10-29 17:19:26 -05:00
/// Return types of the function.
2021-12-24 15:20:30 -06:00
pub rets: Vec<Type>,
2022-10-29 17:19:26 -05:00
/// Local types, *including* args.
2022-11-01 22:43:47 -05:00
pub locals: EntityVec<Local, Type>,
/// Entry block.
pub entry: Block,
/// Block bodies.
pub blocks: EntityVec<Block, BlockDef>,
2022-10-29 17:19:26 -05:00
/// Value definitions, indexed by `Value`.
2022-11-01 22:43:47 -05:00
pub values: EntityVec<Value, ValueDef>,
}
2021-12-03 01:33:04 -06:00
impl FunctionBody {
2022-11-01 22:43:47 -05:00
pub fn add_block(&mut self) -> Block {
let id = self.blocks.push(BlockDef::default());
2021-12-12 00:25:12 -06:00
log::trace!("add_block: block {}", id);
2021-12-03 01:33:04 -06:00
id
}
2022-11-01 22:43:47 -05:00
pub fn add_edge(&mut self, from: Block, to: Block) {
2021-12-03 01:33:04 -06:00
let succ_pos = self.blocks[from].succs.len();
let pred_pos = self.blocks[to].preds.len();
self.blocks[from].succs.push(to);
self.blocks[to].preds.push(from);
self.blocks[from].pos_in_succ_pred.push(pred_pos);
self.blocks[to].pos_in_pred_succ.push(succ_pos);
2021-12-12 00:25:12 -06:00
log::trace!("add_edge: from {} to {}", from, to);
2021-11-15 01:56:56 -06:00
}
2022-11-01 04:26:21 -05:00
pub fn add_value(&mut self, value: ValueDef) -> Value {
log::trace!("add_value: def {:?}", value);
2022-11-01 22:43:47 -05:00
self.values.push(value)
}
pub fn set_alias(&mut self, value: Value, to: Value) {
2021-12-12 00:25:12 -06:00
log::trace!("set_alias: value {:?} to {:?}", value, to);
// Resolve the `to` value through all existing aliases.
2021-12-12 22:11:28 -06:00
let to = self.resolve_and_update_alias(to);
// Disallow cycles.
if to == value {
panic!("Cannot create an alias cycle");
}
2022-11-01 22:43:47 -05:00
self.values[value] = ValueDef::Alias(to);
}
pub fn resolve_alias(&self, value: Value) -> Value {
let mut result = value;
loop {
2022-11-01 22:43:47 -05:00
if let &ValueDef::Alias(to) = &self.values[result] {
result = to;
} else {
break;
}
}
result
}
2022-11-01 04:26:21 -05:00
pub fn add_mutable_inst(&mut self, def: ValueDef) -> Value {
let value = Value(self.values.len() as u32);
self.values.push(def);
value
}
2022-11-01 22:43:47 -05:00
pub fn add_blockparam(&mut self, block: Block, ty: Type) -> Value {
2021-12-12 12:34:19 -06:00
let index = self.blocks[block].params.len();
2022-11-01 04:26:21 -05:00
let value = self.add_value(ValueDef::BlockParam(block, index, ty));
2021-12-19 15:57:34 -06:00
self.blocks[block].params.push((ty, value));
value
}
pub fn add_placeholder(&mut self, ty: Type) -> Value {
2022-11-01 04:26:21 -05:00
self.add_mutable_inst(ValueDef::Placeholder(ty))
}
2022-11-01 22:43:47 -05:00
pub fn replace_placeholder_with_blockparam(&mut self, block: Block, value: Value) {
let index = self.blocks[block].params.len();
2022-11-01 22:43:47 -05:00
let ty = match &self.values[value] {
2022-11-01 04:26:21 -05:00
&ValueDef::Placeholder(ty) => ty,
_ => unreachable!(),
};
2021-12-19 15:57:34 -06:00
self.blocks[block].params.push((ty, value));
2022-11-01 22:43:47 -05:00
self.values[value] = ValueDef::BlockParam(block, index, ty);
}
pub fn resolve_and_update_alias(&mut self, value: Value) -> Value {
let to = self.resolve_alias(value);
// Short-circuit the chain, union-find-style.
2022-11-01 22:43:47 -05:00
if let &ValueDef::Alias(orig_to) = &self.values[value] {
if orig_to != to {
2022-11-01 22:43:47 -05:00
self.values[value] = ValueDef::Alias(to);
}
}
to
2021-11-15 01:56:56 -06:00
}
2022-11-01 22:43:47 -05:00
pub fn append_to_block(&mut self, block: Block, value: Value) {
2021-12-03 01:33:04 -06:00
self.blocks[block].insts.push(value);
2021-11-15 01:56:56 -06:00
}
2022-11-01 22:43:47 -05:00
pub fn end_block(&mut self, block: Block, terminator: Terminator) {
2021-12-03 01:33:04 -06:00
terminator.visit_successors(|succ| {
self.add_edge(block, succ);
});
self.blocks[block].terminator = terminator;
2021-11-15 01:56:56 -06:00
}
2022-11-01 22:43:47 -05:00
pub fn add_local(&mut self, ty: Type) -> Local {
self.locals.push(ty)
2021-11-22 01:12:07 -06:00
}
}
2021-12-03 01:33:04 -06:00
#[derive(Clone, Debug, Default)]
2022-11-01 22:43:47 -05:00
pub struct BlockDef {
/// Instructions in this block.
2021-12-03 01:33:04 -06:00
pub insts: Vec<Value>,
/// Terminator: branch or return.
pub terminator: Terminator,
/// Successor blocks.
2022-11-01 22:43:47 -05:00
pub succs: Vec<Block>,
2021-12-03 01:33:04 -06:00
/// For each successor block, our index in its `preds` array.
pub pos_in_succ_pred: Vec<usize>,
/// Predecessor blocks.
2022-11-01 22:43:47 -05:00
pub preds: Vec<Block>,
2021-12-03 01:33:04 -06:00
/// For each predecessor block, our index in its `succs` array.
pub pos_in_pred_succ: Vec<usize>,
2021-12-19 15:57:34 -06:00
/// Type and Value for each blockparam.
pub params: Vec<(Type, Value)>,
2021-11-13 16:23:22 -06:00
}
2021-12-03 01:33:04 -06:00
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ValueDef {
2022-11-01 04:26:21 -05:00
Arg(usize, Type),
2022-11-01 22:43:47 -05:00
BlockParam(Block, usize, Type),
2022-11-01 04:26:21 -05:00
Operator(Operator, Vec<Value>, Vec<Type>),
PickOutput(Value, usize, Type),
Alias(Value),
2022-11-01 04:26:21 -05:00
Placeholder(Type),
2021-12-03 01:33:04 -06:00
}
2021-11-21 19:15:26 -06:00
2021-12-03 01:33:04 -06:00
impl ValueDef {
pub fn visit_uses<F: FnMut(Value)>(&self, mut f: F) {
match self {
2021-12-03 01:34:57 -06:00
&ValueDef::Arg { .. } => {}
&ValueDef::BlockParam { .. } => {}
2022-11-01 04:26:21 -05:00
&ValueDef::Operator(_, ref args, _) => {
2021-12-03 01:33:04 -06:00
for &arg in args {
f(arg);
}
}
&ValueDef::PickOutput(from, ..) => f(from),
&ValueDef::Alias(value) => f(value),
2022-11-01 04:26:21 -05:00
&ValueDef::Placeholder(_) => {}
2021-11-21 19:15:26 -06:00
}
}
2021-11-22 01:12:07 -06:00
2021-12-03 01:33:04 -06:00
pub fn update_uses<F: FnMut(&mut Value)>(&mut self, mut f: F) {
match self {
2021-12-03 01:34:57 -06:00
&mut ValueDef::Arg { .. } => {}
&mut ValueDef::BlockParam { .. } => {}
2022-11-01 04:26:21 -05:00
&mut ValueDef::Operator(_, ref mut args, _) => {
2021-12-03 01:34:57 -06:00
for arg in args {
2021-12-03 01:33:04 -06:00
f(arg);
}
}
&mut ValueDef::PickOutput(ref mut from, ..) => f(from),
&mut ValueDef::Alias(ref mut value) => f(value),
2022-11-01 04:26:21 -05:00
&mut ValueDef::Placeholder(_) => {}
2021-11-21 19:15:26 -06:00
}
}
}
#[derive(Clone, Debug)]
pub struct BlockTarget {
2022-11-01 22:43:47 -05:00
pub block: Block,
pub args: Vec<Value>,
}
2021-11-13 05:38:47 -06:00
#[derive(Clone, Debug)]
2021-11-14 02:00:34 -06:00
pub enum Terminator {
2021-11-13 05:38:47 -06:00
Br {
target: BlockTarget,
2021-11-13 05:38:47 -06:00
},
CondBr {
2021-11-21 19:15:26 -06:00
cond: Value,
if_true: BlockTarget,
if_false: BlockTarget,
2021-11-13 05:38:47 -06:00
},
Select {
2021-11-21 19:15:26 -06:00
value: Value,
targets: Vec<BlockTarget>,
default: BlockTarget,
2021-11-13 05:38:47 -06:00
},
Return {
2021-11-21 19:15:26 -06:00
values: Vec<Value>,
2021-11-13 05:38:47 -06:00
},
None,
}
2021-11-14 02:00:34 -06:00
impl std::default::Default for Terminator {
2021-11-13 05:38:47 -06:00
fn default() -> Self {
Terminator::None
}
}
2021-11-13 19:52:30 -06:00
2021-11-14 02:00:34 -06:00
impl Terminator {
pub fn visit_targets<F: FnMut(&BlockTarget)>(&self, mut f: F) {
2021-11-14 02:00:34 -06:00
match self {
2021-12-03 01:33:04 -06:00
Terminator::Return { .. } => {}
Terminator::Br { ref target, .. } => f(target),
2021-11-14 02:00:34 -06:00
Terminator::CondBr {
ref if_true,
ref if_false,
..
2021-11-14 02:00:34 -06:00
} => {
f(if_true);
f(if_false);
2021-11-14 02:00:34 -06:00
}
2021-11-13 22:59:37 -06:00
Terminator::Select {
ref targets,
ref default,
..
} => {
f(default);
for target in targets {
f(target);
}
}
Terminator::None => {}
}
}
pub fn update_targets<F: FnMut(&mut BlockTarget)>(&mut self, mut f: F) {
match self {
Terminator::Return { .. } => {}
Terminator::Br { ref mut target, .. } => f(target),
Terminator::CondBr {
ref mut if_true,
ref mut if_false,
2021-11-13 22:59:37 -06:00
..
} => {
f(if_true);
f(if_false);
}
Terminator::Select {
ref mut targets,
ref mut default,
..
} => {
f(default);
for target in targets {
2021-12-03 01:33:04 -06:00
f(target);
}
2021-11-13 22:59:37 -06:00
}
2021-12-03 01:33:04 -06:00
Terminator::None => {}
2021-11-13 22:59:37 -06:00
}
2021-11-13 19:52:30 -06:00
}
2021-11-22 01:12:07 -06:00
pub fn visit_target<F: FnMut(&BlockTarget)>(&self, index: usize, mut f: F) {
match (index, self) {
(0, Terminator::Br { ref target, .. }) => f(target),
(0, Terminator::CondBr { ref if_true, .. }) => {
f(if_true);
}
(1, Terminator::CondBr { ref if_false, .. }) => {
f(if_false);
}
(0, Terminator::Select { ref default, .. }) => {
f(default);
}
(i, Terminator::Select { ref targets, .. }) if i <= targets.len() => {
f(&targets[i - 1]);
}
_ => panic!("out of bounds"),
}
}
pub fn update_target<F: FnMut(&mut BlockTarget)>(&mut self, index: usize, mut f: F) {
match (index, self) {
(0, Terminator::Br { ref mut target, .. }) => f(target),
(
0,
Terminator::CondBr {
ref mut if_true, ..
},
) => {
f(if_true);
}
(
1,
Terminator::CondBr {
ref mut if_false, ..
},
) => {
f(if_false);
}
(
0,
Terminator::Select {
ref mut default, ..
},
) => {
f(default);
}
(
i,
Terminator::Select {
ref mut targets, ..
},
) if i <= targets.len() => {
f(&mut targets[i - 1]);
}
2021-12-12 00:44:48 -06:00
(i, this) => panic!("out of bounds: index {} term {:?}", i, this),
}
}
2022-11-01 22:43:47 -05:00
pub fn visit_successors<F: FnMut(Block)>(&self, mut f: F) {
self.visit_targets(|target| f(target.block));
}
2021-11-22 01:12:07 -06:00
pub fn visit_uses<F: FnMut(Value)>(&self, mut f: F) {
self.visit_targets(|target| {
for &arg in &target.args {
f(arg);
}
});
2021-11-22 01:12:07 -06:00
match self {
&Terminator::CondBr { cond, .. } => f(cond),
&Terminator::Select { value, .. } => f(value),
&Terminator::Return { ref values, .. } => {
for &value in values {
f(value);
}
}
_ => {}
}
}
pub fn update_uses<F: FnMut(&mut Value)>(&mut self, mut f: F) {
self.update_targets(|target| {
for arg in &mut target.args {
f(arg);
}
});
2021-11-22 01:12:07 -06:00
match self {
&mut Terminator::CondBr { ref mut cond, .. } => f(cond),
&mut Terminator::Select { ref mut value, .. } => f(value),
&mut Terminator::Return { ref mut values, .. } => {
for value in values {
f(value);
}
}
_ => {}
}
}
2021-11-13 19:52:30 -06:00
}
2021-12-03 01:33:04 -06:00
impl<'a> Module<'a> {
pub fn from_wasm_bytes(bytes: &'a [u8]) -> Result<Self> {
frontend::wasm_to_ir(bytes)
}
2022-10-27 00:15:15 -05:00
pub fn to_wasm_bytes(&self) -> Result<Vec<u8>> {
2022-11-01 22:43:47 -05:00
todo!()
2021-12-24 15:00:21 -06:00
}
}