Skip to main content

lamina_codegen/x86_64/
frame.rs

1//! x86_64 stack frame management utilities.
2
3/// Stack frame utilities for x86_64 code generation.
4pub struct X86Frame;
5
6impl X86Frame {
7    /// Generates the function prologue: saves frame pointer and allocates stack space.
8    pub fn generate_prologue<W: std::io::Write>(
9        writer: &mut W,
10        stack_size: usize,
11    ) -> Result<(), std::io::Error> {
12        writeln!(writer, "    pushq %rbp")?;
13        writeln!(writer, "    movq %rsp, %rbp")?;
14        if stack_size > 0 {
15            writeln!(writer, "    subq ${}, %rsp", stack_size)?;
16        }
17        Ok(())
18    }
19
20    /// Generates the function epilogue: restores stack and frame pointer, then returns.
21    pub fn generate_epilogue<W: std::io::Write>(
22        writer: &mut W,
23        stack_size: usize,
24    ) -> Result<(), std::io::Error> {
25        if stack_size > 0 {
26            writeln!(writer, "    addq ${}, %rsp", stack_size)?;
27        }
28        writeln!(writer, "    popq %rbp")?;
29        writeln!(writer, "    ret")?;
30        Ok(())
31    }
32
33    /// Calculates the stack slot offset from RBP for a given slot index.
34    pub fn calculate_stack_offset(slot_index: usize) -> i32 {
35        -((slot_index as i32 + 1) * 8)
36    }
37}