wings-codegen 0.0.4

Cranelift AOT machine-code backend for Wings VM
Documentation
use super::*;
use crate::emit::{BudgetVars, ShadowRoots, flush_budget};
use cranelift_frontend::Variable;

pub(super) fn import_runtime_signatures(
    module: &ObjectModule,
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
) -> (SigRef, SigRef, SigRef) {
    let mut slow_signature = module.make_signature();
    slow_signature.params.push(AbiParam::new(pointer_type));
    slow_signature.returns.push(AbiParam::new(types::I32));
    let mut heap_signature = module.make_signature();
    heap_signature.params = vec![
        AbiParam::new(pointer_type),
        AbiParam::new(types::I32),
        AbiParam::new(types::I64),
        AbiParam::new(pointer_type),
    ];
    heap_signature.returns.push(AbiParam::new(types::I32));
    let mut effect_signature = module.make_signature();
    effect_signature.params = vec![
        AbiParam::new(pointer_type),
        AbiParam::new(pointer_type),
        AbiParam::new(pointer_type),
    ];
    effect_signature.returns.push(AbiParam::new(types::I32));
    (
        builder.import_signature(slow_signature),
        builder.import_signature(heap_signature),
        builder.import_signature(effect_signature),
    )
}

pub(super) fn is_heap_op(operation: &Operation) -> bool {
    matches!(
        operation,
        Operation::RecordNew { .. }
            | Operation::RecordField { .. }
            | Operation::Collect
            | Operation::EmptyInts
            | Operation::PrependInt(_, _)
            | Operation::HeadInt(_)
            | Operation::TailInts(_)
            | Operation::IsEmptyInts(_)
            | 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::StringLiteral(_)
            | Operation::FormatString { .. }
            | Operation::BytesLiteral(_)
            | Operation::IntToString(_)
            | Operation::BoolToString(_)
    )
}

pub(super) fn setup_shadow_roots(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    context_ptr: Value,
    capacity: usize,
) -> Option<ShadowRoots> {
    if capacity != 0 {
        let slot = builder.create_sized_stack_slot(StackSlotData::new(
            StackSlotKind::ExplicitSlot,
            (std::mem::size_of::<ShadowFrame>() + capacity * 8) as u32,
            3,
        ));
        let frame = builder.ins().stack_addr(pointer_type, slot, 0);
        let slots = builder.ins().stack_addr(
            pointer_type,
            slot,
            std::mem::size_of::<ShadowFrame>() as i32,
        );
        let previous = Variable::from_u32(2);
        let linked = Variable::from_u32(3);
        builder.declare_var(previous, pointer_type);
        builder.declare_var(linked, types::I8);
        let zero_ptr = builder.ins().iconst(pointer_type, 0);
        let zero_i8 = builder.ins().iconst(types::I8, 0);
        builder.def_var(previous, zero_ptr);
        builder.def_var(linked, zero_i8);
        Some(ShadowRoots {
            context_ptr,
            frame,
            slots,
            previous,
            linked,
        })
    } else {
        None
    }
}

pub(super) fn unlink_shadow_roots(builder: &mut FunctionBuilder<'_>, roots: Option<ShadowRoots>) {
    let Some(roots) = roots else {
        return;
    };
    let is_linked = builder.use_var(roots.linked);
    let do_unlink = builder.create_block();
    builder.set_cold_block(do_unlink);
    let after_unlink = builder.create_block();
    builder
        .ins()
        .brif(is_linked, do_unlink, &[], after_unlink, &[]);
    builder.switch_to_block(do_unlink);
    let prev = builder.use_var(roots.previous);
    builder.ins().store(
        MemFlags::new(),
        prev,
        roots.context_ptr,
        std::mem::offset_of!(ScalarContext, roots) as i32,
    );
    builder.ins().jump(after_unlink, &[]);
    builder.switch_to_block(after_unlink);
}

pub(super) fn setup_call_scratches(
    builder: &mut FunctionBuilder<'_>,
    pointer_type: types::Type,
    function: &Function,
    elided: &[bool],
    uses_heap: bool,
) -> (Option<Value>, Option<Value>) {
    let heap_output = uses_heap.then(|| {
        let scratch_bytes = if function
            .instructions
            .iter()
            .any(|instruction| matches!(instruction.operation, Operation::FormatString { .. }))
        {
            272
        } else if function
            .instructions
            .iter()
            .enumerate()
            .any(|(index, instruction)| {
                !elided[index] && matches!(instruction.operation, Operation::RecordNew { .. })
            })
        {
            80
        } else {
            24
        };
        let slot = builder.create_sized_stack_slot(StackSlotData::new(
            StackSlotKind::ExplicitSlot,
            scratch_bytes,
            3,
        ));
        builder.ins().stack_addr(pointer_type, slot, 0)
    });
    let effect_arguments = function
        .instructions
        .iter()
        .any(|instruction| instruction.operation.is_effect())
        .then(|| {
            let slot = builder.create_sized_stack_slot(StackSlotData::new(
                StackSlotKind::ExplicitSlot,
                64 * 8 + EFFECT_ARGUMENT_OFFSET as u32,
                3,
            ));
            builder.ins().stack_addr(pointer_type, slot, 0)
        });
    (heap_output, effect_arguments)
}

#[allow(clippy::too_many_arguments)]
pub(super) fn emit_epilogue(
    mut builder: FunctionBuilder<'_>,
    kind: BodyKind,
    function: &Function,
    registers: &[Value],
    exit: Block,
    roots: Option<ShadowRoots>,
    context_ptr: Value,
    budget: BudgetVars,
    block_terminated: bool,
) {
    match kind {
        BodyKind::Handler | BodyKind::LeafHandler | BodyKind::InlineLeafHandler { .. } => {
            let output_offset = std::mem::offset_of!(ScalarContext, output) as i32;
            builder.ins().store(
                MemFlags::new(),
                registers[function.state],
                context_ptr,
                output_offset,
            );
            builder.ins().store(
                MemFlags::new(),
                registers[function.reply],
                context_ptr,
                output_offset + 8,
            );
            let status = builder.ins().iconst(types::I32, 0);
            builder.ins().jump(exit, &[status]);
            builder.switch_to_block(exit);
            let status = builder.block_params(exit)[0];
            flush_budget(&mut builder, context_ptr, budget);
            unlink_shadow_roots(&mut builder, roots);
            builder.ins().return_(&[status]);
        }
        BodyKind::Procedure { .. } => {
            if !block_terminated {
                flush_budget(&mut builder, context_ptr, budget);
                unlink_shadow_roots(&mut builder, roots);
                let ok = builder.ins().iconst(types::I32, 0);
                builder.ins().return_(&[ok, registers[function.reply]]);
            }
            builder.switch_to_block(exit);
            let status = builder.block_params(exit)[0];
            flush_budget(&mut builder, context_ptr, budget);
            unlink_shadow_roots(&mut builder, roots);
            let zero = builder.ins().iconst(types::I64, 0);
            builder.ins().return_(&[status, zero]);
        }
    }
    builder.seal_all_blocks();
    builder.finalize();
}

pub(super) fn finalize_function(
    module: &mut ObjectModule,
    identifier: FuncId,
    context: &mut cranelift_codegen::Context,
    name: &str,
    max_frame_bytes: u32,
) -> Result<(FuncId, u32), String> {
    module
        .define_function(identifier, context)
        .map_err(|error| error.to_string())?;
    let frame_bytes = context
        .compiled_code()
        .ok_or("backend did not produce scalar machine code")?
        .frame_size;
    if frame_bytes > max_frame_bytes {
        return Err(format!(
            "scalar stack frame for {name} requires {frame_bytes} bytes, limit is {max_frame_bytes}"
        ));
    }
    module.clear_context(context);
    Ok((identifier, frame_bytes))
}

/// Compiles `context` and defines `identifier` only when its stack frame fits
/// within `max_frame_bytes`. Returns `Ok(None)` without defining `identifier`
/// when the frame exceeds the inline margin so the caller can fall back to the
/// trampoline + `LeafHandler` path.
pub(super) fn try_finalize_inline_function(
    module: &mut ObjectModule,
    identifier: FuncId,
    context: &mut cranelift_codegen::Context,
    max_frame_bytes: u32,
) -> Result<Option<(FuncId, u32)>, String> {
    let mut ctrl_plane = cranelift_codegen::control::ControlPlane::default();
    let compiled = context
        .compile(module.isa(), &mut ctrl_plane)
        .map_err(|error| format!("{error:?}"))?;
    let frame_bytes = compiled.frame_size;
    if frame_bytes > max_frame_bytes {
        module.clear_context(context);
        return Ok(None);
    }
    module
        .define_function(identifier, context)
        .map_err(|error| error.to_string())?;
    module.clear_context(context);
    Ok(Some((identifier, frame_bytes)))
}

pub(super) fn configure_body_signature(
    signature: &mut cranelift_codegen::ir::Signature,
    kind: BodyKind,
    pointer_type: types::Type,
) {
    match kind {
        BodyKind::Handler => {
            signature.params = vec![
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(pointer_type),
            ];
            signature.returns = vec![AbiParam::new(types::I32)];
        }
        BodyKind::LeafHandler | BodyKind::InlineLeafHandler { .. } => {
            signature.params = vec![
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(types::I64),
                AbiParam::new(pointer_type),
                AbiParam::new(pointer_type),
            ];
            signature.returns = vec![AbiParam::new(types::I32)];
        }
        BodyKind::Procedure { arity, .. } => {
            signature.call_conv = cranelift_codegen::isa::CallConv::Tail;
            signature.params = vec![AbiParam::new(types::I64); arity];
            signature.returns = vec![AbiParam::new(types::I32), AbiParam::new(types::I64)];
        }
    }
}