Skip to main content

code_transpiler/
native_abi.rs

1use crate::ir::Type;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4#[repr(u64)]
5pub enum NativeValueTag {
6    Invalid = 0,
7    Integer = 1,
8    Unsigned = 2,
9    Float = 3,
10    Bool = 4,
11    String = 5,
12    Pointer = 6,
13}
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct NativeValue {
16    pub tag: NativeValueTag,
17    pub payload: u64,
18}
19impl NativeValue {
20    pub fn integer(v: i64) -> Self {
21        Self {
22            tag: NativeValueTag::Integer,
23            payload: v as u64,
24        }
25    }
26    pub fn unsigned(v: u64) -> Self {
27        Self {
28            tag: NativeValueTag::Unsigned,
29            payload: v,
30        }
31    }
32    pub fn pointer(v: usize) -> Self {
33        Self {
34            tag: NativeValueTag::Pointer,
35            payload: v as u64,
36        }
37    }
38    pub fn string_ptr(v: usize) -> Self {
39        Self {
40            tag: NativeValueTag::String,
41            payload: v as u64,
42        }
43    }
44    pub fn float_bits(v: u64) -> Self {
45        Self {
46            tag: NativeValueTag::Float,
47            payload: v,
48        }
49    }
50    pub fn boolean(v: bool) -> Self {
51        Self {
52            tag: NativeValueTag::Bool,
53            payload: if v { 1 } else { 0 },
54        }
55    }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct NativeTargetProfile {
60    pub os: String,
61    pub isa: String,
62    pub object_format: String,
63    pub abi: String,
64    pub endianness: String,
65    pub system_abi: String,
66    pub pointer_size: usize,
67    pub stack_alignment: usize,
68    pub function_pointer_alignment: usize,
69    pub index_bit_width: usize,
70    pub legal_integer_widths: Vec<usize>,
71}
72pub fn native_windows_x64_target_profile() -> NativeTargetProfile {
73    NativeTargetProfile {
74        os: "windows".into(),
75        isa: "x86_64".into(),
76        object_format: "PE32+".into(),
77        abi: "microsoft-x64".into(),
78        endianness: "little".into(),
79        system_abi: "kernel32".into(),
80        pointer_size: 8,
81        stack_alignment: 16,
82        function_pointer_alignment: 8,
83        index_bit_width: 64,
84        legal_integer_widths: vec![8, 16, 32, 64],
85    }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum NativeRepresentation {
90    Scalar,
91    Address,
92    Pair,
93    Descriptor,
94    Aggregate,
95    OwnedRegion,
96    FunctionReference,
97    ClosureValue,
98}
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum NativeAbiContext {
101    Value,
102    Argument,
103    Result,
104    Capture,
105}
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct NativeLayout {
108    pub representation: NativeRepresentation,
109    pub size_bits: usize,
110    pub size_bytes: usize,
111    pub abi_alignment: usize,
112    pub preferred_alignment: usize,
113    pub field_offsets: Vec<usize>,
114    pub stride: usize,
115    pub index_bit_width: usize,
116    pub pointer_size: usize,
117    pub stack_alignment: usize,
118    pub endianness: String,
119    pub memory_space: String,
120}
121
122pub fn solve_native_layout(
123    profile: &NativeTargetProfile,
124    ty: &Type,
125    _context: NativeAbiContext,
126) -> Result<NativeLayout, String> {
127    if profile.pointer_size == 0 || profile.stack_alignment == 0 {
128        return Err("invalid target profile".into());
129    }
130    let pointer = profile.pointer_size;
131    let mut l = NativeLayout {
132        representation: NativeRepresentation::Scalar,
133        size_bits: 0,
134        size_bytes: 0,
135        abi_alignment: 1,
136        preferred_alignment: 1,
137        field_offsets: Vec::new(),
138        stride: 0,
139        index_bit_width: profile.index_bit_width,
140        pointer_size: pointer,
141        stack_alignment: profile.stack_alignment,
142        endianness: profile.endianness.clone(),
143        memory_space: "default".into(),
144    };
145    match ty {
146        Type::Unit => {
147            l.size_bits = pointer * 8;
148            l.size_bytes = pointer;
149            l.abi_alignment = pointer;
150            l.preferred_alignment = pointer;
151        }
152        Type::Bool => {
153            l.size_bits = 8;
154            l.size_bytes = 1;
155        }
156        Type::Int | Type::UInt => {
157            l.size_bits = profile.index_bit_width;
158            l.size_bytes = profile.index_bit_width / 8;
159            l.abi_alignment = l.size_bytes.min(pointer);
160            l.preferred_alignment = l.abi_alignment;
161        }
162        Type::Int8 | Type::UInt8 => {
163            l.size_bits = 8;
164            l.size_bytes = 1;
165        }
166        Type::Int16 | Type::UInt16 => {
167            l.size_bits = 16;
168            l.size_bytes = 2;
169            l.abi_alignment = 2.min(pointer);
170            l.preferred_alignment = l.abi_alignment;
171        }
172        Type::Int32 | Type::UInt32 | Type::Float32 => {
173            l.size_bits = 32;
174            l.size_bytes = 4;
175            l.abi_alignment = 4.min(pointer);
176            l.preferred_alignment = l.abi_alignment;
177        }
178        Type::Int64 | Type::UInt64 | Type::Float64 => {
179            l.size_bits = 64;
180            l.size_bytes = 8;
181            l.abi_alignment = 8.min(pointer);
182            l.preferred_alignment = l.abi_alignment;
183        }
184        Type::String => {
185            l.representation = NativeRepresentation::Pair;
186            l.size_bits = pointer * 16;
187            l.size_bytes = pointer * 2;
188            l.abi_alignment = pointer;
189            l.preferred_alignment = pointer;
190            l.field_offsets = vec![0, pointer];
191        }
192        Type::Slice(_) | Type::Map(_, _) => {
193            l.representation = NativeRepresentation::Descriptor;
194            l.size_bits = pointer * 16;
195            l.size_bytes = pointer * 2;
196            l.abi_alignment = pointer;
197            l.preferred_alignment = pointer;
198            l.field_offsets = vec![0, pointer];
199        }
200        Type::Tuple(items) => {
201            let mut offset = 0usize;
202            let mut max_align = 1usize;
203            l.representation = NativeRepresentation::Aggregate;
204            for item in items {
205                let field = solve_native_layout(profile, item, _context)?;
206                let align = field.abi_alignment.max(1);
207                offset = offset.div_ceil(align) * align;
208                l.field_offsets.push(offset);
209                offset += field.size_bytes;
210                max_align = max_align.max(align);
211            }
212            offset = offset.div_ceil(max_align) * max_align;
213            l.size_bytes = offset;
214            l.size_bits = offset * 8;
215            l.abi_alignment = max_align;
216            l.preferred_alignment = max_align;
217        }
218        Type::Named(name) => {
219            return Err(format!(
220                "NATIVE_LAYOUT_GAP: named type {name:?} requires resolved semantic layout"
221            ))
222        }
223    }
224    l.stride = l.size_bytes;
225    if l.preferred_alignment < l.abi_alignment {
226        return Err("invalid layout alignment".into());
227    }
228    Ok(l)
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum NativeStorageDecision {
233    Static,
234    Stack,
235    OwnedRegion,
236    Unresolved,
237}
238#[derive(Debug, Clone, PartialEq, Eq, Default)]
239pub struct NativeStorageRequest {
240    pub escapes: bool,
241    pub program_static: bool,
242    pub ownership_known: bool,
243    pub alias_mutation_safe: bool,
244    pub dynamic_size: bool,
245    pub lifetime: String,
246}
247pub fn decide_native_storage(r: &NativeStorageRequest) -> NativeStorageDecision {
248    if r.program_static && !r.escapes && !r.dynamic_size {
249        return NativeStorageDecision::Static;
250    }
251    if !r.escapes && matches!(r.lifetime.as_str(), "frame" | "block") && r.alias_mutation_safe {
252        return NativeStorageDecision::Stack;
253    }
254    if r.escapes && r.ownership_known && r.alias_mutation_safe {
255        return NativeStorageDecision::OwnedRegion;
256    }
257    NativeStorageDecision::Unresolved
258}