edlc_codegen_cranelift 0.2.16

Cranelift codegen backend for the EDL compiler
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/*
 *     EDLc, a compiler for the EDL programming language.
 *     Copyright (C) 2026  Adrian Paskert
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
pub mod stack_frame;
pub mod sysv;

use std::sync::Arc;

use edlc_core::prelude::mir_type::abi::{AbiConfig, AbiLayout, ByteLayout};
use edlc_core::prelude::mir_type::{MirTypeId, MirTypeRegistry};
use edlc_core::prelude::{MirError, MirPhase};
use cranelift::prelude::FunctionBuilder;
use cranelift_codegen::ir::{types, InstBuilder, Type, Value};

use crate::codegen::{CompileValue, IntoValue, ShortVec};
use crate::compiler::JIT;

/// Contains the SSA representation of a MIR type.
#[derive(Debug, Clone)]
pub struct SSARepr {
    pub id: MirTypeId,
    pub layout: ByteLayout,
    pub members: Vec<Type>,
}

macro_rules! impl_plain(
    ($($name:ident),*) => ($(
        pub fn $name<Runtime: 'static>(phase: &MirPhase, abi: Arc<AbiConfig>) -> Self {
            Self::abi_repr::<Runtime>(phase.types.$name(), abi, &phase.types).unwrap()
        }
    )*);
);

impl SSARepr {
    pub fn ptr<Runtime: 'static>(phase: &MirPhase, abi: Arc<AbiConfig>) -> Self {
        Self::abi_repr::<Runtime>(phase.types.usize(), abi, &phase.types).unwrap()
    }

    pub fn sub_layout(&self, offset: usize, size: usize, abi: Arc<AbiConfig>) -> AbiLayout {
        let mut abi_layout = AbiLayout::new(abi);
        abi_layout.push_bytes(self.layout.derive_sub_layout(offset, size));
        abi_layout
    }

    impl_plain!(
        u8, u16, u32, u64, u128, usize,
        i8, i16, i32, i64, i128, isize,
        f32, f64,
        bool, char, str, empty
    );

    /// Checks if the type should be treated as a large aggregated type.
    pub fn is_large_aggregated_type(
        &self,
        abi: &AbiConfig
    ) -> bool {
        self.layout.size > abi.large_aggregate_bytes
    }

    /// Returns the size in bytes of the SSA type.
    pub fn byte_size(&self) -> usize {
        self.layout.size
    }

    /// Returns the alignment of the SSA type.
    pub fn alignment(&self) -> usize {
        let mut align: usize = 1;
        for m in self.members.iter() {
            align = usize::max(align, m.bytes() as usize);
        }
        align
    }

    pub fn abi_layout(&self, abi: Arc<AbiConfig>) -> AbiLayout {
        let mut abi_layout = AbiLayout::new(abi);
        abi_layout.push_bytes(self.layout.clone());
        abi_layout
    }

    /// Returns the ABI layout for the type as it is passed as a parameter.
    ///
    /// # Working principle
    ///
    /// Currently, only the SystemV ABI is supported and parameters are formatted as follows:
    /// If the parameter size aligned to 8-byte boundaries is smaller than or equal to two times
    /// the size of a pointer (64-bit vs. 32-bit) then the type is passed by value.
    /// Otherwise, the data is layed out on the stack (within the stack-frame of the caller) and
    /// a pointer to the data is passed as the argument instead.
    ///
    /// In turn, this method returns the ABI layout returned by `self.abi_layout(..)` if the type
    /// is small enough and the abi layout of a pointer
    ///
    /// ```rust
    /// use std::sync::Arc;
    /// use edlc_core::prelude::mir_type::abi::{AbiConfig, AbiLayout};
    /// use edlc_core::prelude::MirPhase;
    /// use eqlang_cranelift::prelude::SSARepr;
    ///
    /// fn foo(phase: &MirPhase, abi: Arc<AbiConfig>) -> AbiLayout {
    ///     SSARepr::usize(phase, abi.clone()).abi_layout(abi)
    /// }
    /// ```
    ///
    /// otherwise.
    pub fn parameter_layout<Runtime: 'static>(
        &self,
        phase: &MirPhase,
        abi: Arc<AbiConfig>
    ) -> AbiLayout {
        if self.byte_size() > abi.large_aggregate_bytes {
            // return abi layout for pointer types
            Self::usize::<Runtime>(phase, abi.clone()).abi_layout(abi)
        } else {
            self.abi_layout(abi)
        }
    }

    pub fn align(size: usize, alignment: usize) -> usize {
        assert!(alignment.is_power_of_two());
        if size == 0 {
            0
        } else {
            ((size - 1) / alignment + 1) * alignment
        }
    }

    /// Returns the base SSA type that is used to build an aggregate type with the specified
    /// alignment value `align`.
    /// Since alignment values > 8 bytes (64 bits) are not representable wiht a since SSA value,
    /// multiple SSA types are required to represent the base building blocks for the type.
    /// To notify this, the second tuple argument of the return type of this function is the number
    /// of SSA types (indicated by the first argument) that are required to build the base
    /// alignment.
    pub fn itype_for_alignment(align: usize) -> (Type, usize) {
        match align {
            1 => (types::I8, 1),
            2 => (types::I16, 1),
            4 => (types::I32, 1),
            8 => (types::I64, 1),
            o if o > 8 && usize::is_power_of_two(o) => (types::I64, o / 8),
            o => panic!("Invalid alignment value {}", o),
        }
    }

    pub fn ftype_for_alignment(align: usize) -> (Type, usize) {
        match align {
            4 => (types::F32, 1),
            8 => (types::F64, 1),
            o if o > 8 && usize::is_power_of_two(o) => (types::F64, o / 8),
            o => panic!("Invalid alignment value {}", o),
        }
    }

    /// Returns the minimal amount of SSA types required to represent an aggregate type of the
    /// specified size.
    pub fn minimal_repr(mut size: usize, mut align: usize) -> Vec<Type> {
        assert!(usize::is_power_of_two(align), "alignment must be a valid power of 2");
        align = usize::min(8, align);

        let mut out = Vec::new();
        while size != 0 {
            let ty = match align {
                1 => types::I8,
                2 => types::I16,
                4 => types::I32,
                8 => types::I64,
                _ => unreachable!(),
            };

            while size >= align {
                out.push(ty);
                size -= align;
            }
            align >>= 1;
        }
        out
    }

    /// Returns the minimal amount of SSA types required to represent an aggregate type of the
    /// specified size.
    pub fn fminimal_repr(mut size: usize, mut align: usize) -> Vec<Type> {
        assert!(usize::is_power_of_two(align), "alignment must be a valid power of 2");
        assert_eq!(size & 0x1, 0, "no floating point type with 1 byte in size suppor");
        align = usize::min(8, align);
        
        let mut out = Vec::new();
        while size != 0 {
            let ty = match align {
                2 => types::F16,
                4 => types::F32,
                8 => types::F64,
                _ => unreachable!(),
            };

            while size >= align {
                out.push(ty);
                size -= align;
            }
            align >>= 1;
        }
        out
    }

    pub fn push_member(&mut self, ty: Type) {
        self.members.push(ty);
    }

    pub fn push(&mut self, member: &SSARepr) {
        for ty in member.members.iter() {
            self.members.push(*ty);
        }
    }

    pub fn zero_value<Runtime>(
        ty: Type,
        builder: &mut FunctionBuilder,
    ) -> Result<Value, MirError<JIT<Runtime>>> {
        match ty {
            ty if ty == types::I8
                || ty == types::I16
                || ty == types::I32
                || ty == types::I64 => Ok(builder.ins().iconst(ty, 0)),
            ty if ty == types::I128 => {
                let zero = builder.ins().iconst(types::I64, 0);
                Ok(builder.ins().iconcat(zero, zero))
            }
            ty if ty == types::F32 => Ok(builder.ins().f32const(0.0)),
            ty if ty == types::F64 => Ok(builder.ins().f64const(0.0)),
            _ => unimplemented!()
        }
    }

    /// Returns a value matching the type described by this SSA structure initialized to zero.
    pub fn zeros<Runtime>(
        &self,
        builder: &mut FunctionBuilder
    ) -> Result<CompileValue, MirError<JIT<Runtime>>> {
        let mut values = Vec::new();
        for &ty in self.members.iter() {
            values.push(Self::zero_value(ty, builder)?);
        }
        Ok(values.into_value(self.id))
    }

    pub fn abi_repr<Runtime>(
        ty: MirTypeId,
        abi: Arc<AbiConfig>,
        types: &MirTypeRegistry,
    ) -> Result<SSARepr, MirError<JIT<Runtime>>> {
        let layout = types.abi_layout(abi, ty)
            .ok_or(MirError::UnknownType(ty))?;
        Ok(Self {
            members: Self::eightbyte_types(layout),
            id: ty,
            layout: types.byte_layout(ty).ok_or(MirError::UnknownType(ty))?
        })
    }

    /// Decomposes the type layout to a number of eightbytes which are represented through their
    /// respective AbiTypes.
    pub fn eightbyte_types(layout: AbiLayout) -> Vec<Type> {
        let mut members = Vec::new();
        for i in 0..layout.num_blocks() {
            let type_bytes = layout.block_bytes(i).unwrap();
            if layout.is_float_block(i) {
                let (t, n) = Self::ftype_for_alignment(type_bytes);
                (0..n).for_each(|_| members.push(t));
            } else {
                let (t, n) = Self::itype_for_alignment(type_bytes);
                (0..n).for_each(|_| members.push(t));
            }
        }
        members
    }

    pub fn iter_eightbytes(layout: &AbiLayout) -> EightbyteIter<'_> {
        EightbyteIter {
            layout,
            block: 0,
            i: 0,
        }
    }

    pub fn single_eightbyte(layout: &AbiLayout) -> Option<Type> {
        let mut iter = Self::iter_eightbytes(layout);
        let out = iter.next();
        assert!(iter.next().is_none());
        out
    }

    /// Single plain old data type.
    /// Compared to eightbytes, a pod type may be larger than 8 bytes.
    /// Examples of bigger data types include i128, u128, f128 and SIMD vector lane types.
    pub fn pod(ty: &MirTypeId, reg: &MirTypeRegistry) -> Option<Type> {
        match ty {
            ty if *ty == reg.i8() || *ty == reg.u8() || *ty == reg.bool() => Some(types::I8),
            ty if *ty == reg.i16() || *ty == reg.u16() => Some(types::I16),
            ty if *ty == reg.i32() || *ty == reg.u32() || *ty == reg.char() => Some(types::I32),
            ty if *ty == reg.i64() || *ty == reg.u64() => Some(types::I64),
            ty if *ty == reg.i128() || *ty == reg.u128() => Some(types::I128),
            ty if *ty == reg.usize() || *ty == reg.isize() => {
                match reg.byte_size(*ty) {
                    Some(4) => Some(types::I32),
                    Some(8) => Some(types::I64),
                    _ => panic!("invalid pointer usize/isize byte count"),
                }
            },
            ty if *ty == reg.f32() => Some(types::F32),
            ty if *ty == reg.f64() => Some(types::F64),
            ty if reg.is_ref(ty) || *ty == reg.str() => {
                match reg.byte_size(*ty) {
                    Some(4) => Some(types::I32),
                    Some(8) => Some(types::I64),
                    Some(16) => Some(types::I128),
                    _ => panic!("invalid pointer size"),
                }
            },
            ty if *ty == reg.empty() || *ty == reg.never() => None,
            ty => {
                panic!("not a POD data type: {ty}")
            },
        }
    }

    /// Sums the amount of RXX and XMM bytes in the ABI layout.
    /// The first returned value is the amount of RXX bytes, while the second parameter is the
    /// amount of XMM bytes in the layout.
    pub fn sum_block_type_eightbytes(layout: &AbiLayout) -> (u32, u32) {
        let mut rxx_sum = 0u32;
        let mut xmm_sum = 0u32;
        for i in 0..layout.num_blocks() {
            // let type_bytes = layout.block_bytes(i).unwrap();
            if layout.is_float_block(i) {
                xmm_sum += 1;
            } else {
                rxx_sum += 1;
            }
        }
        (rxx_sum, xmm_sum)
    }

    pub fn len(&self) -> usize {
        self.members.len()
    }
}

pub struct EightbyteIter<'a> {
    layout: &'a AbiLayout,
    block: usize,
    i: usize,
}

impl<'a> Iterator for EightbyteIter<'a> {
    type Item = Type;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(type_bytes) = self.layout.block_bytes(self.block) {
            let (t, n) = if self.layout.is_float_block(self.block) {
                SSARepr::ftype_for_alignment(type_bytes)
            } else {
                SSARepr::itype_for_alignment(type_bytes)
            };
            if self.i < n {
                self.i += 1;
                Some(t)
            } else {
                self.block += 1;
                self.i = 0;
                self.next()
            }
        } else {
            None
        }
    }
}

pub struct ParameterLayout {
    pub size: usize,
    pub types: ShortVec<Type>,
}




#[cfg(test)]
mod test {
    use edlc_core::prelude::edl_type::EdlMaybeType;
    use edlc_core::prelude::mir_type::layout::{Layout, MirLayout, StructLayoutBuilder};
    use edlc_core::prelude::mir_type::MirTypeRegistry;

    use crate::prelude::{CraneliftJIT, SSARepr};

    #[test]
    fn test_layout() -> Result<(), anyhow::Error> {
        let _ = crate::setup_logger();
        let mut compiler = CraneliftJIT::<()>::default();
        compiler.init()?;
        compiler.compiler.prepare_module(&vec!["std"].into())?;

        // create some test data & check layout
        #[repr(C)]
        struct Data {
            a: u8,
            a_: u16,
            b: u32,
            c: f32,
        }
        impl MirLayout for Data {
            fn layout(types: &MirTypeRegistry) -> Layout {
                let mut builder = StructLayoutBuilder::default();
                builder.add("a".to_string(), types.u8(), types);
                builder.add("a_".to_string(), types.u16(), types);
                builder.add("b".to_string(), types.u32(), types);
                builder.add("c".to_string(), types.f32(), types);
                builder.make::<Self>()
            }
        }

        // get SSA repr
        compiler.compiler.parse_and_insert_type_def(edlc_core::inline_code!("Data"), edlc_core::inline_code!("<>"))?;
        compiler.compiler.insert_type_instance::<Data>(edlc_core::inline_code!("Data"))?;
        let EdlMaybeType::Fixed(id) = compiler.compiler.parse_type(edlc_core::inline_code!("Data"))? else {
            panic!();
        };
        let mir_type = compiler.compiler.mir_phase.types
            .mir_id(&id, &compiler.compiler.phase.types)?;

        let ssa_repr = SSARepr::abi_repr::<()>(mir_type, compiler.backend.abi.clone(), &compiler.compiler.mir_phase.types)?;
        println!("SSA representation: {:#?}", ssa_repr);

        Ok(())
    }

    #[test]
    fn test_layout_2() -> Result<(), anyhow::Error> {
        let _ = crate::setup_logger();
        let mut compiler = CraneliftJIT::<()>::default();
        compiler.init()?;
        compiler.compiler.prepare_module(&vec!["std"].into())?;

        // create some test data & check layout
        #[repr(C)]
        struct Data {
            a: u8,
            b: u64,
            c: u8,
            d: u8,
        }
        impl MirLayout for Data {
            fn layout(types: &MirTypeRegistry) -> Layout {
                let mut builder = StructLayoutBuilder::default();
                builder.add("a".to_string(), types.u8(), types);
                builder.add("b".to_string(), types.u64(), types);
                builder.add("c".to_string(), types.u8(), types);
                builder.add("d".to_string(), types.u8(), types);
                builder.make::<Self>()
            }
        }

        // get SSA repr
        compiler.compiler.parse_and_insert_type_def(edlc_core::inline_code!("Data"), edlc_core::inline_code!("<>"))?;
        compiler.compiler.insert_type_instance::<Data>(edlc_core::inline_code!("Data"))?;
        let EdlMaybeType::Fixed(id) = compiler.compiler.parse_type(edlc_core::inline_code!("Data"))? else {
            panic!();
        };
        let mir_type = compiler.compiler.mir_phase.types
            .mir_id(&id, &compiler.compiler.phase.types)?;

        let ssa_repr = SSARepr::abi_repr::<()>(mir_type, compiler.backend.abi.clone(), &compiler.compiler.mir_phase.types)?;
        println!("SSA representation: {:#?}", ssa_repr);
        Ok(())
    }
}