mun_codegen 0.4.0

LLVM IR code generation for Mun
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
///! This module provides constructs to enable type safe handling of inkwell types.
mod array_value;
mod float_value;
mod function_value;
mod global;
mod int_value;
mod pointer_value;
mod string;
mod tuple_value;

use inkwell::context::Context;
use inkwell::module::Module;
use inkwell::targets::TargetData;

pub use array_value::IterAsIrValue;
pub use global::Global;
pub use string::CanInternalize;

use inkwell::types::{BasicTypeEnum, PointerType, StructType};
use inkwell::values::PointerValue;
use inkwell::AddressSpace;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;

/// Represents a generic inkwell value. This is a wrapper around inkwell types that enforces type
/// safety in the Rust compiler. Rust values that can be converted to inkwell types can be
/// represented as a value. e.g. `Value<u32>`. Internally this holds an `inkwell::values::IntValue`
/// but we maintain the information that it's actually a `u32` value.
///
/// There are several ways to enable a type to be used as a `Value<T>` type through the `AsValue`
/// trait.
///
/// - Implement the [`TransparentValue`] trait which converts the implementor into another
///   `Value<T>` type. Internally the inkwell value is taken from the inner type but a `Value<Self>`
///   is returned. This allows transparent composition. e.g.:
///
///   ```rust
///   # use mun_codegen::value::{AsValue, BytesOrPtr, IrTypeContext, IrValueContext, TransparentValue, Value};
///   struct Foo {
///      value: u32,
///      bar: f32,
///   }
///
///   impl<'ink> TransparentValue<'ink> for Foo {
///       type Target = (u32, f32);
///
///       fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target> {
///           (self.value, self.bar).as_value(context)
///       }
///
///       fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>> {
///           vec![
///               bytemuck::cast_ref::<u32, [u8; 4]>(&self.value).to_vec().into(),
///               bytemuck::cast_ref::<f32, [u8; 4]>(&self.bar).to_vec().into(),
///           ]
///       }
///   }
///   ```
///
///   This will result in an anonymous LLVM type: `type { u32, f32 }`
///
/// - Auto derive the `AsValue` trait e.g.:
///   ```ignore
///   #[macro_use] extern crate mun_codegen_macros;
///
///   #[derive(AsValue)]
///   struct Foo {
///       value: u32,
///       bar: f32
///   }
///   ```
///
///   This will result in a _named_ LLVM type: `%Foo = type { u32, f32 }`
///
/// - You can also add completely custom support by implementing the [`ConcreteValueType`] and
///   [`AsValue`] traits. Optionally you might also want to implement the [`SizedValueType`] and
///   [`PointerValueType`] traits.
pub struct Value<'ink, T: ConcreteValueType<'ink> + ?Sized> {
    pub value: T::Value,
}

/// When implemented enables the conversion from a value to a `Value<T>`.
pub trait AsValue<'ink, T: ConcreteValueType<'ink> + ?Sized> {
    /// Creates a `Value<T>` from an instance.
    fn as_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, T>;
}

/// A `TransparentValue` is something that can be represented as a `Value<T>` but which is actually
/// a rewritten version of another type.
pub trait TransparentValue<'ink> {
    type Target: ConcreteValueType<'ink> + ?Sized;

    /// Converts the instance to the target value
    fn as_target_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, Self::Target>;

    /// Converts the instance to bytes and pointers. All pointers remain pointer values, whereas
    /// all other value types are converted to bytes.
    fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>>;
}

/// Contains either a value converted to bytes or a pointer to the value.
///
/// This is used for generating constant enum types.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BytesOrPtr<'ink> {
    Bytes(Vec<u8>),
    UntypedPtr(PointerValue<'ink>),
}

impl<'ink> From<Vec<u8>> for BytesOrPtr<'ink> {
    fn from(bytes: Vec<u8>) -> Self {
        BytesOrPtr::Bytes(bytes)
    }
}

impl<'ink> From<PointerValue<'ink>> for BytesOrPtr<'ink> {
    fn from(ptr: PointerValue<'ink>) -> Self {
        BytesOrPtr::UntypedPtr(ptr)
    }
}

/// Converts a value to its raw byte representation, while leaving pointers intact.
pub trait AsBytesAndPtrs<'ink> {
    /// Converts the instance to bytes and pointers.  All pointers remain pointer values, whereas
    /// all other value types are converted to bytes.
    fn as_bytes_and_ptrs(&self, context: &IrTypeContext<'ink, '_>) -> Vec<BytesOrPtr<'ink>>;
}

/// Signals whether the instance can construct a matching LLVM constant IR value.
pub trait HasConstValue {
    /// Returns whether the instance can be converted into an LLVM IR value.
    fn has_const_value() -> bool;
}

/// The context in which an `IrType` operates.
pub struct IrTypeContext<'ink, 'a> {
    pub context: &'ink Context,
    pub target_data: &'a TargetData,
    pub struct_types: &'a RefCell<HashMap<&'static str, StructType<'ink>>>,
}

/// The context in which an `IrValue` exists.
pub struct IrValueContext<'ink, 'a, 'b> {
    pub context: &'ink Context,
    pub type_context: &'b IrTypeContext<'ink, 'a>,
    pub module: &'b Module<'ink>,
}

/// A trait that represents that a concrete type can be used as `Value<T>` type generic. A type must
/// implement this trait to be able to be represented as a `Value<Self>`.
pub trait ConcreteValueType<'ink> {
    type Value: ValueType<'ink>;
}

/// If we take a pointer of value T, which type can it return? This trait dictates that.
pub trait AddressableType<'ink, T: ?Sized> {
    /// Cast the pointer if required
    fn ptr_cast(
        value: PointerValue<'ink>,
        _context: &IrValueContext<'ink, '_, '_>,
    ) -> PointerValue<'ink> {
        value
    }
}

/// A trait implemented for types that can determine the IR type of a value without an instance.
pub trait SizedValueType<'ink>: ConcreteValueType<'ink> + Sized {
    /// Returns the IR type of a value of this type.
    fn get_ir_type(
        context: &IrTypeContext<'ink, '_>,
    ) -> <<Self as ConcreteValueType<'ink>>::Value as ValueType<'ink>>::Type;
}

/// A trait that returns the pointer type of the specified value.
pub trait PointerValueType<'ink> {
    /// Returns the pointer type of the value
    fn get_ptr_type(
        context: &IrTypeContext<'ink, '_>,
        address_space: Option<AddressSpace>,
    ) -> inkwell::types::PointerType<'ink>;
}

/// A trait that enables the conversion from an inkwell type to a corresponding value type. (e.g.
/// IntType -> IntValue)
pub trait TypeValue<'ink> {
    type Value: inkwell::values::AnyValue<'ink>;
}

/// A trait that enables the conversion from an inkwell value to a corresponding type. (e.g.
/// IntValue -> IntType)
pub trait ValueType<'ink>: Clone + Debug + Copy + Eq + PartialEq + Hash {
    type Type: inkwell::types::AnyType<'ink>;

    /// Returns the type of the value
    fn get_type(&self) -> Self::Type;
}

/// A trait that is implemented for types that can also be represented as a pointer.
pub trait AddressableTypeValue<'ink>: TypeValue<'ink> {
    fn ptr_type(&self, address_space: AddressSpace) -> inkwell::types::PointerType<'ink>;
}

/// A macro that implements basic traits for inkwell types.
macro_rules! impl_value_type_value {
    ($($ty:ty => $val:ty),+) => {
        $(
            impl<'ink> TypeValue<'ink> for $ty {
                type Value = $val;
            }
            impl<'ink> ValueType<'ink> for $val {
                type Type = $ty;

                fn get_type(&self) -> Self::Type {
                    Self::get_type(*self)
                }
            }
        )*
    }
}

impl_value_type_value! (
    inkwell::types::IntType<'ink> => inkwell::values::IntValue<'ink>,
    inkwell::types::FloatType<'ink> => inkwell::values::FloatValue<'ink>,
    inkwell::types::ArrayType<'ink> => inkwell::values::ArrayValue<'ink>,
    inkwell::types::VectorType<'ink> => inkwell::values::VectorValue<'ink>,
    inkwell::types::StructType<'ink> => inkwell::values::StructValue<'ink>,
    inkwell::types::PointerType<'ink> => inkwell::values::PointerValue<'ink>,
    inkwell::types::FunctionType<'ink> => inkwell::values::FunctionValue<'ink>
);

macro_rules! impl_addressable_type_values {
    ($($ty:ty),+) => {
        $(
            impl<'ink> AddressableTypeValue<'ink> for $ty {
                fn ptr_type(&self, address_space: AddressSpace) -> inkwell::types::PointerType<'ink> {
                    Self::ptr_type(*self, address_space)
                }
            }
        )*
    }
}

impl_addressable_type_values!(
    inkwell::types::IntType<'ink>,
    inkwell::types::FloatType<'ink>,
    inkwell::types::ArrayType<'ink>,
    inkwell::types::VectorType<'ink>,
    inkwell::types::StructType<'ink>,
    inkwell::types::PointerType<'ink>,
    inkwell::types::FunctionType<'ink>
);

impl<'ink> AddressableTypeValue<'ink> for inkwell::types::BasicTypeEnum<'ink> {
    fn ptr_type(&self, address_space: AddressSpace) -> PointerType<'ink> {
        match self {
            BasicTypeEnum::ArrayType(ty) => ty.ptr_type(address_space),
            BasicTypeEnum::FloatType(ty) => ty.ptr_type(address_space),
            BasicTypeEnum::IntType(ty) => ty.ptr_type(address_space),
            BasicTypeEnum::PointerType(ty) => ty.ptr_type(address_space),
            BasicTypeEnum::StructType(ty) => ty.ptr_type(address_space),
            BasicTypeEnum::VectorType(ty) => ty.ptr_type(address_space),
        }
    }
}

impl<'ink> TypeValue<'ink> for inkwell::types::BasicTypeEnum<'ink> {
    type Value = inkwell::values::BasicValueEnum<'ink>;
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Value<'ink, T> {
    /// Returns the type of the value.
    pub fn get_type(&self) -> <T::Value as ValueType<'ink>>::Type {
        <T::Value as ValueType>::get_type(&self.value)
    }

    /// Constructs a `Value<T>` from an inkwell value.
    pub(super) fn from_raw(value: T::Value) -> Value<'ink, T> {
        Value { value }
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Value<'ink, *const T>
where
    *const T: SizedValueType<'ink, Value = PointerValue<'ink>>,
    <*const T as ConcreteValueType<'ink>>::Value: ValueType<'ink, Type = PointerType<'ink>>,
{
    /// Constructs a value by casting the specified pointer value to this value
    pub fn with_cast(value: PointerValue<'ink>, context: &IrValueContext<'ink, '_, '_>) -> Self {
        let target_type = <*const T>::get_ir_type(context.type_context);
        Value {
            value: if value.get_type() == target_type {
                value
            } else {
                value.const_cast(target_type)
            },
        }
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Value<'ink, *mut T>
where
    *mut T: SizedValueType<'ink, Value = PointerValue<'ink>>,
    <*mut T as ConcreteValueType<'ink>>::Value: ValueType<'ink, Type = PointerType<'ink>>,
{
    /// Constructs a value by casting the specified pointer value to this value
    pub fn with_cast(value: PointerValue<'ink>, context: &IrValueContext<'ink, '_, '_>) -> Self {
        let target_type = <*mut T>::get_ir_type(context.type_context);
        Value {
            value: if value.get_type() == target_type {
                value
            } else {
                value.const_cast(target_type)
            },
        }
    }
}

impl<'ink, T: SizedValueType<'ink> + ?Sized> Value<'ink, T> {
    /// Returns the inkwell type of this `Value`.
    pub fn get_ir_type(context: &IrTypeContext<'ink, '_>) -> <T::Value as ValueType<'ink>>::Type {
        T::get_ir_type(context)
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> AsValue<'ink, T> for Value<'ink, T> {
    fn as_value(&self, _context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, T> {
        *self
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Clone for Value<'ink, T> {
    fn clone(&self) -> Self {
        Value { value: self.value }
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Copy for Value<'ink, T> {}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> PartialEq for Value<'ink, T> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Eq for Value<'ink, T> {}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> Hash for Value<'ink, T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.value.hash(state)
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> std::fmt::Debug for Value<'ink, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self.value)
    }
}

impl<'ink, T: ConcreteValueType<'ink> + ?Sized> From<Value<'ink, T>>
    for inkwell::values::BasicValueEnum<'ink>
where
    T::Value: Into<inkwell::values::BasicValueEnum<'ink>>,
{
    fn from(value: Value<'ink, T>) -> Self {
        value.value.into()
    }
}

pub trait AsValueInto<'ink, T> {
    fn as_value_into(&self, context: &IrValueContext<'ink, '_, '_>) -> T;
}

impl<'ink, I, T: ConcreteValueType<'ink>> AsValueInto<'ink, I> for Value<'ink, T>
where
    T::Value: Into<I>,
{
    fn as_value_into(&self, _context: &IrValueContext<'ink, '_, '_>) -> I {
        self.value.into()
    }
}

impl<'ink, I, T: ConcreteValueType<'ink> + AsValue<'ink, T>> AsValueInto<'ink, I> for T
where
    T::Value: Into<I>,
{
    fn as_value_into(&self, context: &IrValueContext<'ink, '_, '_>) -> I {
        self.as_value(context).value.into()
    }
}

// A `TransparentValue` can also be represented by a `Value<T>`.
impl<'ink, T: TransparentValue<'ink>> ConcreteValueType<'ink> for T {
    type Value = <T::Target as ConcreteValueType<'ink>>::Value;
}

// A `TransparentValue` is sized if the target is also sized.
impl<'ink, T: TransparentValue<'ink>> SizedValueType<'ink> for T
where
    T::Target: SizedValueType<'ink>,
{
    fn get_ir_type(context: &IrTypeContext<'ink, '_>) -> <Self::Value as ValueType<'ink>>::Type {
        T::Target::get_ir_type(context)
    }
}

// If the target of the transparent value can statically return a pointer type, so can we.
impl<'ink, T: TransparentValue<'ink>> PointerValueType<'ink> for T
where
    T::Target: PointerValueType<'ink>,
{
    fn get_ptr_type(
        context: &IrTypeContext<'ink, '_>,
        address_space: Option<AddressSpace>,
    ) -> PointerType<'ink> {
        T::Target::get_ptr_type(context, address_space)
    }
}

// If the target is addressable as I, the transparent value is also addressable as I.
impl<
        'ink,
        I: ?Sized,
        U: ConcreteValueType<'ink> + ?Sized + AddressableType<'ink, I>,
        T: TransparentValue<'ink, Target = U>,
    > AddressableType<'ink, I> for T
{
    fn ptr_cast(
        value: PointerValue<'ink>,
        context: &IrValueContext<'ink, '_, '_>,
    ) -> PointerValue<'ink> {
        <T::Target as AddressableType<'ink, I>>::ptr_cast(value, context)
    }
}

impl<'ink, T> HasConstValue for T
where
    T: TransparentValue<'ink>,
{
    fn has_const_value() -> bool {
        true
    }
}

// Transparent values can also be represented as `Value<Self>`.
impl<'ink, T> AsValue<'ink, T> for T
where
    T: TransparentValue<'ink>,
{
    fn as_value(&self, context: &IrValueContext<'ink, '_, '_>) -> Value<'ink, T> {
        Value::from_raw(self.as_target_value(context).value)
    }
}

#[cfg(test)]
mod tests {
    use super::{AsBytesAndPtrs, HasConstValue};
    use crate::{code_gen::CodeGenContext, mock::MockDatabase, value::IrTypeContext};
    use bytemuck::from_bytes;
    use std::mem::size_of;

    macro_rules! test_as_bytes_and_ptrs_primitive {
        ($($ty:ty),+) => {
            $(
                paste::item! {
                    #[test]
                    fn [<test_has_const_value_ $ty>]() {
                        assert_eq!($ty::has_const_value(), true);
                    }
                }
                paste::item! {
                    #[test]
                    fn [<test_as_bytes_and_ptrs_ $ty>]() {
                        let bytes: Vec<u8> = (0..(size_of::<$ty>() as u8)).collect();
                        let value = from_bytes::<$ty>(&bytes);

                        let inkwell_context = inkwell::context::Context::create();

                        let db = MockDatabase::default();
                        let codegen_context = CodeGenContext::new(&inkwell_context, &db);

                        let target_data = codegen_context.target_machine.get_target_data();
                        let type_context = IrTypeContext {
                            context: &inkwell_context,
                            target_data: &target_data,
                            struct_types: &codegen_context.rust_types,
                        };

                        assert_eq!(
                            value.as_bytes_and_ptrs(&type_context),
                            vec![bytes.into()],
                        );
                    }
                }
            )+
        };
    }

    test_as_bytes_and_ptrs_primitive!(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64);
}