mod calls;
mod effects;
mod frame;
mod literals;
mod superblock;
use super::*;
use crate::emit::{
ScalarParams, emit_heap_op, emit_pure_scalar, init_budget, is_deferrable_op,
is_inline_alloc_op, needs_inline_roots, poll_control, publish_roots_incremental,
};
#[derive(Clone, Copy)]
pub(super) enum BodyKind {
Handler,
LeafHandler,
InlineLeafHandler {
linkage: Linkage,
declared_id: Option<FuncId>,
},
Procedure {
index: usize,
arity: usize,
},
}
pub(super) struct BodyContext<'a> {
pub(super) procedures: &'a [FuncId],
pub(super) literal_pool: &'a mut std::collections::HashMap<Vec<u8>, cranelift_module::DataId>,
pub(super) analysis: &'a mut crate::sra::RecordAnalysis,
}
pub(super) fn compile_body(
module: &mut ObjectModule,
name: &str,
function: &Function,
kind: BodyKind,
max_frame_bytes: u32,
ctx: &mut BodyContext<'_>,
) -> Result<(FuncId, u32), String> {
try_compile_inline_body(module, name, function, kind, max_frame_bytes, ctx)?
.ok_or_else(|| format!("scalar stack frame for {name} exceeded limit {max_frame_bytes}"))
}
pub(super) fn try_compile_inline_body(
module: &mut ObjectModule,
name: &str,
function: &Function,
kind: BodyKind,
max_frame_bytes: u32,
ctx: &mut BodyContext<'_>,
) -> Result<Option<(FuncId, u32)>, String> {
let BodyContext {
procedures,
literal_pool,
analysis,
} = ctx;
let mut context = module.make_context();
let pointer_type = module.target_config().pointer_type();
frame::configure_body_signature(&mut context.func.signature, kind, pointer_type);
let identifier = match kind {
BodyKind::InlineLeafHandler {
declared_id: Some(id),
..
} => id,
BodyKind::InlineLeafHandler {
linkage,
declared_id: None,
} => module
.declare_function(name, linkage, &context.func.signature)
.map_err(|error| error.to_string())?,
_ => module
.declare_function(
&format!("{name}_body"),
Linkage::Local,
&context.func.signature,
)
.map_err(|error| error.to_string())?,
};
let callees: Vec<_> = procedures
.iter()
.map(|identifier| module.declare_func_in_func(*identifier, &mut context.func))
.collect();
let literals = literals::declare_literals(module, &mut context.func, function, literal_pool)?;
let mut builder_context = FunctionBuilderContext::new();
let plan = analysis.plan_for_body(function, matches!(kind, BodyKind::Procedure { .. }));
let reuse_donors = analysis.compute_reuse_donors(function, &plan);
let uses_heap = function
.instructions
.iter()
.enumerate()
.any(|(index, instruction)| {
!analysis.is_no_op_heap(index) && frame::is_heap_op(&instruction.operation)
});
let mut builder = FunctionBuilder::new(&mut context.func, &mut builder_context);
let (slow_signature, heap_signature, effect_signature) =
frame::import_runtime_signatures(module, &mut builder, pointer_type);
let entry = builder.create_block();
builder.append_block_params_for_function_params(entry);
builder.switch_to_block(entry);
let mut parameters = builder.block_params(entry).to_vec();
let context_ptr = match kind {
BodyKind::LeafHandler | BodyKind::InlineLeafHandler { .. } => parameters[5],
BodyKind::Handler | BodyKind::Procedure { .. } => {
builder.ins().get_pinned_reg(pointer_type)
}
};
if matches!(kind, BodyKind::InlineLeafHandler { .. }) {
let limit = builder.ins().load(
pointer_type,
MemFlags::new(),
context_ptr,
std::mem::offset_of!(ScalarContext, stack_limit) as i32,
);
let missing = builder.ins().icmp_imm(IntCC::Equal, limit, 0);
fail_if(&mut builder, missing, STATUS_STACK_EXHAUSTED);
let stack_pointer = builder.ins().get_stack_pointer(pointer_type);
let below_limit = builder
.ins()
.icmp(IntCC::UnsignedLessThan, stack_pointer, limit);
fail_if(&mut builder, below_limit, STATUS_STACK_EXHAUSTED);
let available = builder.ins().isub(stack_pointer, limit);
let insufficient = builder.ins().icmp_imm(
IntCC::UnsignedLessThan,
available,
i64::from(max_frame_bytes + ENTRY_STACK_MARGIN),
);
fail_if(&mut builder, insufficient, STATUS_STACK_EXHAUSTED);
}
let readonly = MemFlags::new().with_readonly();
let control_ptr = builder.ins().load(
pointer_type,
readonly,
context_ptr,
std::mem::offset_of!(ScalarContext, control) as i32,
);
let budget = init_budget(&mut builder, context_ptr);
let exit = builder.create_block();
builder.append_block_param(exit, types::I32);
let roots = frame::setup_shadow_roots(&mut builder, pointer_type, context_ptr, plan.capacity);
let (heap_output, effect_arguments) = frame::setup_call_scratches(
&mut builder,
pointer_type,
function,
&analysis.elided,
uses_heap,
);
let mut registers = Vec::new();
let mut branches: Vec<(Block, Block, bool)> = Vec::new();
let mut loops = Vec::new();
let mut block_terminated = false;
const DEFER_POLL_MAX: usize = 16;
let mut deferred_steps = 0usize;
let mut published_roots: Option<&[usize]> = Some(&[]);
let mut index = 0;
let mut tail_polled = false;
let self_loop_header = calls::setup_procedure_entry(
&mut builder,
function,
kind,
&mut parameters,
&mut registers,
&mut published_roots,
&mut deferred_steps,
&mut index,
);
while index < function.instructions.len() {
if !block_terminated {
if let Some(sb) = superblock::try_emit_superblock(
&mut builder,
pointer_type,
context_ptr,
control_ptr,
budget,
slow_signature,
exit,
roots,
function,
kind,
¶meters,
analysis,
&plan,
&mut registers,
&mut published_roots,
&mut deferred_steps,
index,
) {
index = sb.next_index;
if sb.tail_polled {
tail_polled = true;
}
continue;
}
}
macro_rules! emit_poll {
($live:expr, $steps:expr) => {
poll_control(
&mut builder,
pointer_type,
context_ptr,
control_ptr,
budget,
slow_signature,
exit,
roots,
$live,
®isters,
$steps,
);
};
}
let instruction = &function.instructions[index];
let early_count = match instruction.operation {
Operation::Loop(ref initials) => {
if !block_terminated && deferred_steps > 0 {
let pre_live =
crate::emit::remap_pre_loop_roots(&plan.at[index], index, initials);
emit_poll!(&pre_live, deferred_steps as i64);
deferred_steps = 0;
}
let header = builder.create_block();
let after = builder.create_block();
let arity = initials.len();
for _ in 0..arity {
builder.append_block_param(header, types::I64);
builder.append_block_param(after, types::I64);
}
let args: Vec<Value> = initials.iter().map(|®| registers[reg]).collect();
builder.ins().jump(header, &args);
builder.switch_to_block(header);
published_roots = None;
loops.push((header, after, index, arity));
registers.extend_from_slice(builder.block_params(header));
arity
}
Operation::EndIf(ref values) => {
let (_, merge_block, mut merge_reachable) =
branches.pop().ok_or("missing validated branch")?;
if !block_terminated {
if deferred_steps > 0 {
let pre_merge_live =
crate::emit::remap_pre_loop_roots(&plan.at[index], index, values);
emit_poll!(&pre_merge_live, deferred_steps as i64);
deferred_steps = 0;
}
let args: Vec<Value> = values.iter().map(|®| registers[reg]).collect();
builder.ins().jump(merge_block, &args);
merge_reachable = true;
}
builder.switch_to_block(merge_block);
block_terminated = !merge_reachable;
published_roots = None;
registers.extend_from_slice(builder.block_params(merge_block));
if !merge_reachable {
builder
.ins()
.trap(cranelift_codegen::ir::TrapCode::unwrap_user(1));
}
values.len()
}
_ => 0usize,
};
let no_op_heap = analysis.is_no_op_heap(index);
let tail_call = matches!(instruction.operation, Operation::Call { .. })
&& calls::is_tail_call(function, kind, index);
if block_terminated {
deferred_steps = 0;
} else if !tail_call
&& (is_deferrable_op(&instruction.operation) || no_op_heap)
&& deferred_steps < DEFER_POLL_MAX
{
deferred_steps += 1;
} else {
let step_charge = (deferred_steps + 1 + usize::from(tail_call)) as i64;
emit_poll!(&plan.at[index], step_charge);
if published_roots != Some(plan.at[index].as_slice()) {
published_roots = None;
}
deferred_steps = 0;
}
if no_op_heap {
let value = if let Some(target) = analysis.forwarded[index] {
registers[target]
} else {
builder.ins().iconst(types::I64, 0)
};
registers.push(value);
index += 1;
continue;
}
let inline_alloc = is_inline_alloc_op(function, &instruction.operation);
if needs_inline_roots(&instruction.operation) && !inline_alloc && !tail_call {
let live = plan.at[index].as_slice();
publish_roots_incremental(
&mut builder,
pointer_type,
roots,
live,
published_roots,
®isters,
);
published_roots = Some(live);
} else if inline_alloc && published_roots != Some(plan.at[index].as_slice()) {
published_roots = None;
}
let value = match instruction.operation {
Operation::Call {
function: callee_idx,
ref arguments,
} => calls::emit_call_op(
&mut builder,
pointer_type,
context_ptr,
budget,
roots,
function,
&callees,
callee_idx,
arguments,
®isters,
exit,
tail_call,
self_loop_header,
&mut block_terminated,
),
Operation::SendSelf { .. }
| Operation::SendAfterSelf { .. }
| Operation::Send { .. }
| Operation::SendActor { .. }
| Operation::SendAfter { .. }
| Operation::SendAfterActor { .. }
| Operation::Monitor { .. }
| Operation::Hostcall { .. }
| Operation::SelfPid
| Operation::SpawnSelf
| Operation::SpawnActor(_)
| Operation::Request { .. }
| Operation::RequestActor { .. }
| Operation::CancelRequest(_) => effects::emit_effect_op(
&mut builder,
pointer_type,
context_ptr,
budget,
effect_signature,
effect_arguments,
function,
&instruction.operation,
®isters,
exit,
)?,
Operation::Loop(_) => builder.ins().iconst(types::I64, 0),
Operation::While(condition, ref exit_values) => {
let (_, after, _, _) = *loops.last().ok_or("missing validated loop")?;
let body = builder.create_block();
let exit_args: Vec<Value> = exit_values.iter().map(|®| registers[reg]).collect();
builder
.ins()
.brif(registers[condition], body, &[], after, &exit_args);
builder.switch_to_block(body);
builder.ins().iconst(types::I64, 0)
}
Operation::EndLoop(ref values) => {
let (header, after, _, _) = loops.pop().ok_or("missing validated loop")?;
let args: Vec<Value> = values.iter().map(|®| registers[reg]).collect();
builder.ins().jump(header, &args);
builder.switch_to_block(after);
published_roots = None;
registers.extend_from_slice(builder.block_params(after));
index += values.len();
continue;
}
Operation::If(condition) => {
let then_block = builder.create_block();
let else_block = builder.create_block();
let merge_block = builder.create_block();
builder
.ins()
.brif(registers[condition], then_block, &[], else_block, &[]);
builder.switch_to_block(then_block);
branches.push((else_block, merge_block, false));
builder.ins().iconst(types::I64, 0)
}
Operation::Else(ref values) => {
let (else_block, merge_block, merge_reachable) =
branches.last_mut().ok_or("missing validated branch")?;
let else_block = *else_block;
let merge_block = *merge_block;
for _ in 0..values.len() {
builder.append_block_param(merge_block, types::I64);
}
if !block_terminated {
let args: Vec<Value> = values.iter().map(|®| registers[reg]).collect();
builder.ins().jump(merge_block, &args);
*merge_reachable = true;
}
builder.switch_to_block(else_block);
block_terminated = false;
published_roots = None;
builder.ins().iconst(types::I64, 0)
}
Operation::EndIf(_) => {
if block_terminated {
context_ptr
} else {
builder.ins().iconst(types::I64, 0)
}
}
Operation::PhiValue(_) => unreachable!("phi values are consumed with owner op"),
Operation::Constant(_)
| Operation::NullPid
| Operation::State
| Operation::Argument(_)
| Operation::Negate(_)
| Operation::Compare(_, _, _)
| Operation::Binary(_, _, _) => emit_pure_scalar(
&mut builder,
&instruction.operation,
match kind {
BodyKind::Handler
| BodyKind::LeafHandler
| BodyKind::InlineLeafHandler { .. } => ScalarParams::Handler {
state: parameters[0],
inline_args: [parameters[1], parameters[2], parameters[3]],
args_ptr: parameters[4],
},
BodyKind::Procedure { .. } => ScalarParams::Procedure(¶meters),
},
®isters,
exit,
),
Operation::StringLiteral(ref value) => literals::emit_literal_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output,
literals[index],
wings_abi::HEAP_STRING_LITERAL,
value.len(),
exit,
)?,
Operation::FormatString {
ref blob,
ref pieces,
ref arguments,
} => literals::emit_format_string_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output,
literals[index],
function,
blob.len(),
pieces,
arguments,
index,
analysis,
&plan.at[index + 1],
®isters,
exit,
)?,
Operation::BytesLiteral(ref value) => literals::emit_literal_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output,
literals[index],
wings_abi::HEAP_BYTES_LITERAL,
value.len(),
exit,
)?,
Operation::IntToString(operand) => literals::emit_to_string_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output,
wings_abi::HEAP_INT_TO_STRING,
registers[operand],
exit,
)?,
Operation::BoolToString(operand) => literals::emit_to_string_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output,
wings_abi::HEAP_BOOL_TO_STRING,
registers[operand],
exit,
)?,
Operation::FillBytes(_, _)
| Operation::BytesLen(_)
| Operation::ByteAt(_, _)
| Operation::ReplaceByte(_)
| Operation::ReadI64Be(_, _)
| Operation::ReplaceI64Be(_)
| Operation::StringFromBytes(_)
| Operation::StringBytes(_)
| Operation::StringLen(_)
| Operation::StringAt(_, _)
| Operation::StringSlice(_)
| Operation::ConcatStrings(_, _)
| Operation::EqualStrings(_, _)
| Operation::RecordNew { .. }
| Operation::RecordField { .. }
| Operation::PrependInt(_, _)
| Operation::HeadInt(_)
| Operation::TailInts(_)
| Operation::IsEmptyInts(_)
| Operation::Collect
| Operation::EmptyInts => emit_heap_op(
&mut builder,
pointer_type,
context_ptr,
budget,
heap_signature,
heap_output.ok_or("missing heap operation scratch")?,
function,
&instruction.operation,
index,
analysis,
reuse_donors[index].map(|reg| registers[reg]),
roots,
&plan.at[index],
&plan.at[index + 1],
®isters,
exit,
),
};
if early_count == 0 {
registers.push(value);
index += 1;
} else {
index += early_count;
}
}
if !tail_polled && !block_terminated {
poll_control(
&mut builder,
pointer_type,
context_ptr,
control_ptr,
budget,
slow_signature,
exit,
roots,
&plan.at[function.instructions.len()],
®isters,
(deferred_steps + 1) as i64,
);
}
frame::emit_epilogue(
builder,
kind,
function,
®isters,
exit,
roots,
context_ptr,
budget,
block_terminated,
);
if matches!(kind, BodyKind::InlineLeafHandler { .. }) {
frame::try_finalize_inline_function(module, identifier, &mut context, max_frame_bytes)
} else {
frame::finalize_function(module, identifier, &mut context, name, max_frame_bytes).map(Some)
}
}