use cranelift_codegen::ir::{self, Block, ExceptionTag, Inst, Value};
use cranelift_frontend::FunctionBuilder;
use std::vec::Vec;
use wasmtime_environ::FrameStackShape;
#[derive(Debug)]
pub enum ElseData {
NoElse {
branch_inst: Inst,
placeholder: Block,
},
WithElse {
else_block: Block,
},
}
#[derive(Debug)]
pub enum ControlStackFrame {
If {
destination: Block,
else_data: ElseData,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
exit_is_branched_to: bool,
blocktype: wasmparser::BlockType,
head_is_reachable: bool,
consequent_ends_reachable: Option<bool>,
},
Block {
destination: Block,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
exit_is_branched_to: bool,
try_table_info: Option<(HandlerStateCheckpoint, Vec<Block>)>,
},
Loop {
destination: Block,
header: Block,
num_param_values: usize,
num_return_values: usize,
original_stack_size: usize,
},
}
impl ControlStackFrame {
pub fn num_return_values(&self) -> usize {
match *self {
Self::If {
num_return_values, ..
}
| Self::Block {
num_return_values, ..
}
| Self::Loop {
num_return_values, ..
} => num_return_values,
}
}
pub fn num_param_values(&self) -> usize {
match *self {
Self::If {
num_param_values, ..
}
| Self::Block {
num_param_values, ..
}
| Self::Loop {
num_param_values, ..
} => num_param_values,
}
}
pub fn following_code(&self) -> Block {
match *self {
Self::If { destination, .. }
| Self::Block { destination, .. }
| Self::Loop { destination, .. } => destination,
}
}
pub fn br_destination(&self) -> Block {
match *self {
Self::If { destination, .. } | Self::Block { destination, .. } => destination,
Self::Loop { header, .. } => header,
}
}
fn original_stack_size(&self) -> usize {
match *self {
Self::If {
original_stack_size,
..
}
| Self::Block {
original_stack_size,
..
}
| Self::Loop {
original_stack_size,
..
} => original_stack_size,
}
}
pub fn is_loop(&self) -> bool {
match *self {
Self::If { .. } | Self::Block { .. } => false,
Self::Loop { .. } => true,
}
}
pub fn exit_is_branched_to(&self) -> bool {
match *self {
Self::If {
exit_is_branched_to,
..
}
| Self::Block {
exit_is_branched_to,
..
} => exit_is_branched_to,
Self::Loop { .. } => false,
}
}
pub fn set_branched_to_exit(&mut self) {
match *self {
Self::If {
ref mut exit_is_branched_to,
..
}
| Self::Block {
ref mut exit_is_branched_to,
..
} => *exit_is_branched_to = true,
Self::Loop { .. } => {}
}
}
pub fn truncate_value_stack_to_else_params(
&self,
stack: &mut Vec<Value>,
stack_shape: &mut Vec<FrameStackShape>,
) {
debug_assert!(matches!(self, &ControlStackFrame::If { .. }));
stack.truncate(self.original_stack_size());
stack_shape.truncate(self.original_stack_size());
}
pub fn truncate_value_stack_to_original_size(
&self,
stack: &mut Vec<Value>,
stack_shape: &mut Vec<FrameStackShape>,
) {
let num_duplicated_params = match self {
&ControlStackFrame::If {
num_param_values, ..
} => {
debug_assert!(num_param_values <= self.original_stack_size());
num_param_values
}
_ => 0,
};
let new_len = self.original_stack_size() - num_duplicated_params;
stack.truncate(new_len);
stack_shape.truncate(new_len);
}
pub fn restore_catch_handlers(
&self,
handlers: &mut HandlerState,
builder: &mut FunctionBuilder,
) {
match self {
ControlStackFrame::Block {
try_table_info: Some((ckpt, catch_blocks)),
..
} => {
handlers.restore_checkpoint(*ckpt);
for block in catch_blocks {
builder.seal_block(*block);
}
}
_ => {}
}
}
}
pub struct FuncTranslationStacks {
pub(crate) stack: Vec<Value>,
pub(crate) stack_shape: Vec<FrameStackShape>,
pub(crate) control_stack: Vec<ControlStackFrame>,
pub(crate) handlers: HandlerState,
pub(crate) reachable: bool,
}
impl FuncTranslationStacks {
#[inline]
pub fn reachable(&self) -> bool {
self.reachable
}
}
impl FuncTranslationStacks {
pub(crate) fn new() -> Self {
Self {
stack: Vec::new(),
stack_shape: Vec::new(),
control_stack: Vec::new(),
handlers: HandlerState::default(),
reachable: true,
}
}
fn clear(&mut self) {
debug_assert!(self.stack.is_empty());
debug_assert!(self.stack_shape.is_empty());
debug_assert!(self.control_stack.is_empty());
debug_assert!(self.handlers.is_empty());
self.reachable = true;
}
pub(crate) fn initialize(&mut self, sig: &ir::Signature, exit_block: Block) {
self.clear();
self.push_block(
exit_block,
0,
sig.returns
.iter()
.filter(|arg| arg.purpose == ir::ArgumentPurpose::Normal)
.count(),
);
}
pub(crate) fn push1(&mut self, val: Value) {
self.stack.push(val);
}
pub(crate) fn push2(&mut self, val1: Value, val2: Value) {
self.stack.push(val1);
self.stack.push(val2);
}
pub(crate) fn pushn(&mut self, vals: &[Value]) {
self.stack.extend_from_slice(vals);
}
pub(crate) fn pop1(&mut self) -> Value {
self.pop_stack_shape(1);
self.stack
.pop()
.expect("attempted to pop a value from an empty stack")
}
pub(crate) fn peek1(&self) -> Value {
*self
.stack
.last()
.expect("attempted to peek at a value on an empty stack")
}
pub(crate) fn pop2(&mut self) -> (Value, Value) {
self.pop_stack_shape(2);
let v2 = self.stack.pop().unwrap();
let v1 = self.stack.pop().unwrap();
(v1, v2)
}
pub(crate) fn pop3(&mut self) -> (Value, Value, Value) {
self.pop_stack_shape(3);
let v3 = self.stack.pop().unwrap();
let v2 = self.stack.pop().unwrap();
let v1 = self.stack.pop().unwrap();
(v1, v2, v3)
}
pub(crate) fn pop4(&mut self) -> (Value, Value, Value, Value) {
self.pop_stack_shape(4);
let v4 = self.stack.pop().unwrap();
let v3 = self.stack.pop().unwrap();
let v2 = self.stack.pop().unwrap();
let v1 = self.stack.pop().unwrap();
(v1, v2, v3, v4)
}
pub(crate) fn pop5(&mut self) -> (Value, Value, Value, Value, Value) {
self.pop_stack_shape(5);
let v5 = self.stack.pop().unwrap();
let v4 = self.stack.pop().unwrap();
let v3 = self.stack.pop().unwrap();
let v2 = self.stack.pop().unwrap();
let v1 = self.stack.pop().unwrap();
(v1, v2, v3, v4, v5)
}
#[inline]
fn ensure_length_is_at_least(&self, n: usize) {
debug_assert!(
n <= self.stack.len(),
"attempted to access {} values but stack only has {} values",
n,
self.stack.len()
)
}
pub(crate) fn popn(&mut self, n: usize) {
self.ensure_length_is_at_least(n);
let new_len = self.stack.len() - n;
self.stack.truncate(new_len);
self.stack_shape.truncate(new_len);
}
fn pop_stack_shape(&mut self, n: usize) {
let new_len = self.stack.len() - n;
self.stack_shape.truncate(new_len);
}
pub(crate) fn peekn(&self, n: usize) -> &[Value] {
self.ensure_length_is_at_least(n);
&self.stack[self.stack.len() - n..]
}
pub(crate) fn peekn_mut(&mut self, n: usize) -> &mut [Value] {
self.ensure_length_is_at_least(n);
let len = self.stack.len();
&mut self.stack[len - n..]
}
fn push_block_impl(
&mut self,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
try_table_info: Option<(HandlerStateCheckpoint, Vec<Block>)>,
) {
debug_assert!(num_param_types <= self.stack.len());
self.control_stack.push(ControlStackFrame::Block {
destination: following_code,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
exit_is_branched_to: false,
try_table_info,
});
}
pub(crate) fn push_block(
&mut self,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
) {
self.push_block_impl(following_code, num_param_types, num_result_types, None);
}
pub(crate) fn push_try_table_block(
&mut self,
following_code: Block,
catch_blocks: Vec<Block>,
num_param_types: usize,
num_result_types: usize,
checkpoint: HandlerStateCheckpoint,
) {
self.push_block_impl(
following_code,
num_param_types,
num_result_types,
Some((checkpoint, catch_blocks)),
);
}
pub(crate) fn push_loop(
&mut self,
header: Block,
following_code: Block,
num_param_types: usize,
num_result_types: usize,
) {
debug_assert!(num_param_types <= self.stack.len());
self.control_stack.push(ControlStackFrame::Loop {
header,
destination: following_code,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
});
}
pub(crate) fn push_if(
&mut self,
destination: Block,
else_data: ElseData,
num_param_types: usize,
num_result_types: usize,
blocktype: wasmparser::BlockType,
) {
debug_assert!(num_param_types <= self.stack.len());
self.assert_debug_stack_is_synced();
self.stack.reserve(num_param_types);
for i in (self.stack.len() - num_param_types)..self.stack.len() {
let val = self.stack[i];
self.stack.push(val);
if !self.stack_shape.is_empty() {
let shape = self.stack_shape[i];
self.stack_shape.push(shape);
}
}
self.control_stack.push(ControlStackFrame::If {
destination,
else_data,
original_stack_size: self.stack.len() - num_param_types,
num_param_values: num_param_types,
num_return_values: num_result_types,
exit_is_branched_to: false,
head_is_reachable: self.reachable,
consequent_ends_reachable: None,
blocktype,
});
}
pub(crate) fn assert_debug_stack_is_synced(&self) {
debug_assert!(self.stack_shape.is_empty() || self.stack_shape.len() == self.stack.len());
}
}
pub struct HandlerState {
pub(crate) handlers: Vec<(Option<ExceptionTag>, Block)>,
}
impl core::default::Default for HandlerState {
fn default() -> Self {
HandlerState { handlers: vec![] }
}
}
#[derive(Clone, Copy, Debug)]
pub struct HandlerStateCheckpoint(usize);
impl HandlerState {
pub fn add_handler(&mut self, tag: Option<ExceptionTag>, block: Block) {
self.handlers.push((tag, block));
}
pub fn take_checkpoint(&self) -> HandlerStateCheckpoint {
HandlerStateCheckpoint(self.handlers.len())
}
pub fn restore_checkpoint(&mut self, ckpt: HandlerStateCheckpoint) {
assert!(ckpt.0 <= self.handlers.len());
self.handlers.truncate(ckpt.0);
}
pub fn handlers(&self) -> impl Iterator<Item = (Option<ExceptionTag>, Block)> + '_ {
self.handlers
.iter()
.map(|(tag, block)| (*tag, *block))
.rev()
}
pub fn is_empty(&self) -> bool {
self.handlers.is_empty()
}
}