Compare commits

..

20 Commits

Author SHA1 Message Date
David Mak fa04cfcdc8 WIP 2024-03-19 17:38:09 +08:00
David Mak aea52af1a6 core: DO NOT MERGE - Split array values into more traits 2024-03-19 15:58:57 +08:00
David Mak faf7a0f8c0 core: DO NOT MERGE - Add ArrayAllocaValue 2024-03-19 15:58:57 +08:00
David Mak bfb00523c9 core: DO NOT MERGE - Add ArrayLikeValue 2024-03-19 15:58:55 +08:00
David Mak 080e1d7be8 core: DO NOT MERGE - Rename to ndarray_calc_broadcast_sz 2024-03-18 22:54:02 +08:00
David Mak b43f94c477 core: DO NOT MERGE - Complete assertion for calc_broadcast 2024-03-18 16:25:53 +08:00
David Mak 7a7ca65f9d core: Add missing unchecked accessors for NDArrayDimsProxy 2024-03-18 16:16:14 +08:00
David Mak c898639a63 core: Revert unpack_ndarray_tvars 2024-03-18 16:16:14 +08:00
David Mak 1f6e7adc54 core: Add gen_if_callback and gen_if_expr_callback 2024-03-18 16:16:14 +08:00
David Mak d38c4f5ea8 core: Implement elementwise binary operators
Including immediate variants of these operators.
2024-03-14 15:19:08 +08:00
David Mak a1ed5014d4 core: Add handling of ndarrays in gen_binop_expr 2024-03-14 14:40:34 +08:00
David Mak 76fcd06162 core: Implement calculations for broadcasting ndarrays 2024-03-14 14:40:34 +08:00
David Mak 1e71cb818f core: Extract codegen portion of gen_binop_expr
This allows binops to be generated internally using LLVM values as
input. Required in a future change.
2024-03-14 14:40:34 +08:00
David Mak 008a3ffe75 core: Add gen_for_callback_incrementing
Simplifies generation of monotonically increasing for loops.
2024-03-14 14:40:34 +08:00
David Mak 415abcfb0a core: Split numpy into codegen and toplevel 2024-03-14 14:40:34 +08:00
David Mak 1c3037dafc core: Apply clippy suggestions 2024-03-14 14:40:34 +08:00
David Mak 3f6117bd52 core: Fix stringification of generic types
We can now iterate the type variables in order.
2024-03-14 14:40:34 +08:00
David Mak 06eeef0d73 core/classes: Rename get_* functions to remove prefix
As suggested by Rust API Guidelines.
2024-03-13 11:41:25 +08:00
David Mak edb41cd996 core: Rename unsafe functions to unchecked
This is this intended name of the functions.
2024-03-13 11:03:49 +08:00
David Mak da716ff032 meta: Update cargo dependencies 2024-03-13 11:03:49 +08:00
19 changed files with 482 additions and 462 deletions

63
Cargo.lock generated
View File

@ -17,9 +17,9 @@ dependencies = [
[[package]]
name = "aho-corasick"
version = "1.1.3"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
dependencies = [
"memchr",
]
@ -110,9 +110,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
version = "2.5.0"
version = "2.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1"
checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
[[package]]
name = "byteorder"
@ -134,9 +134,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.5.3"
version = "4.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813"
checksum = "b230ab84b0ffdf890d5a10abdbc8b83ae1c4918275daea1ab8801f71536b2651"
dependencies = [
"clap_builder",
"clap_derive",
@ -156,14 +156,14 @@ dependencies = [
[[package]]
name = "clap_derive"
version = "4.5.3"
version = "4.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f"
checksum = "307bc0538d5f0f83b8248db3087aa92fe504e4691294d0c96c0eabc33f47ba47"
dependencies = [
"heck 0.5.0",
"heck",
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -372,12 +372,6 @@ version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "indexmap"
version = "1.9.3"
@ -426,7 +420,7 @@ checksum = "4fa4d8d74483041a882adaa9a29f633253a66dde85055f0495c121620ac484b2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -526,7 +520,7 @@ version = "0.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8"
dependencies = [
"bitflags 2.5.0",
"bitflags 2.4.2",
"libc",
"redox_syscall",
]
@ -616,7 +610,6 @@ name = "nac3core"
version = "0.1.0"
dependencies = [
"crossbeam",
"indexmap 2.2.5",
"indoc",
"inkwell",
"insta",
@ -664,9 +657,9 @@ dependencies = [
[[package]]
name = "new_debug_unreachable"
version = "1.0.6"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
checksum = "e4a24736216ec316047a1fc4252e27dabb04218aa4a3f37c6e7ddbf1f9782b54"
[[package]]
name = "once_cell"
@ -747,7 +740,7 @@ dependencies = [
"phf_shared 0.11.2",
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -848,7 +841,7 @@ dependencies = [
"proc-macro2",
"pyo3-macros-backend",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -857,11 +850,11 @@ version = "0.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c7e9b68bb9c3149c5b0cade5d07f953d6d125eb4337723c4ccdb665f1f96185"
dependencies = [
"heck 0.4.1",
"heck",
"proc-macro2",
"pyo3-build-config",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -981,11 +974,11 @@ dependencies = [
[[package]]
name = "rustix"
version = "0.38.32"
version = "0.38.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65e04861e65f21776e67888bfbea442b3642beaa0138fdb1dd7a84a52dffdb89"
checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949"
dependencies = [
"bitflags 2.5.0",
"bitflags 2.4.2",
"errno",
"libc",
"linux-raw-sys",
@ -1042,7 +1035,7 @@ checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -1082,9 +1075,9 @@ checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
[[package]]
name = "smallvec"
version = "1.13.2"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7"
[[package]]
name = "string-interner"
@ -1129,9 +1122,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.53"
version = "2.0.52"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7383cd0e49fff4b6b90ca5670bfd3e9d6a733b3f90c686605aa7eec8c4996032"
checksum = "b699d15b36d1f02c3e7c69f8ffef53de37aefae075d8488d4ba1a7788d574a07"
dependencies = [
"proc-macro2",
"quote",
@ -1197,7 +1190,7 @@ checksum = "c61f3ba182994efc43764a46c018c347bc492c79f024e705f46567b418f6d4f7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]
[[package]]
@ -1515,5 +1508,5 @@ checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.53",
"syn 2.0.52",
]

View File

@ -7,7 +7,6 @@ edition = "2021"
[dependencies]
itertools = "0.12"
crossbeam = "0.8"
indexmap = "2.2"
parking_lot = "0.12"
rayon = "1.8"
nac3parser = { path = "../nac3parser" }

View File

@ -11,45 +11,15 @@ use crate::codegen::{
stmt::gen_for_callback_incrementing,
};
/// An LLVM value that is array-like, i.e. it contains a contiguous, sequenced collection of
/// elements.
pub trait ArrayLikeValue<'ctx> {
/// Returns the element type of this array-like value.
fn element_type<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> AnyTypeEnum<'ctx>;
/// Returns the base pointer to the array.
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> PointerValue<'ctx>;
/// Returns the size of this array-like value.
fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
) -> IntValue<'ctx>;
/// Returns a [`ArraySliceValue`] representing this value.
fn as_slice_value<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> ArraySliceValue<'ctx> {
ArraySliceValue::from_ptr_val(
self.base_ptr(ctx, generator),
self.size(ctx, generator),
None,
)
}
}
/// An array-like value that can be indexed by memory offset.
pub trait ArrayLikeIndexer<'ctx, Index = IntValue<'ctx>>: ArrayLikeValue<'ctx> {
/// # Safety
///
@ -72,7 +42,6 @@ pub trait ArrayLikeIndexer<'ctx, Index = IntValue<'ctx>>: ArrayLikeValue<'ctx> {
) -> PointerValue<'ctx>;
}
/// An array-like value that can have its array elements accessed as a [`BasicValueEnum`].
pub trait UntypedArrayLikeAccessor<'ctx, Index = IntValue<'ctx>>: ArrayLikeIndexer<'ctx, Index> {
/// # Safety
///
@ -101,7 +70,6 @@ pub trait UntypedArrayLikeAccessor<'ctx, Index = IntValue<'ctx>>: ArrayLikeIndex
}
}
/// An array-like value that can have its array elements mutated as a [`BasicValueEnum`].
pub trait UntypedArrayLikeMutator<'ctx, Index = IntValue<'ctx>>: ArrayLikeIndexer<'ctx, Index> {
/// # Safety
///
@ -130,10 +98,9 @@ pub trait UntypedArrayLikeMutator<'ctx, Index = IntValue<'ctx>>: ArrayLikeIndexe
}
}
/// An array-like value that can have its array elements accessed as an arbitrary type `T`.
pub trait TypedArrayLikeAccessor<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayLikeAccessor<'ctx, Index> {
/// Casts an element from [`BasicValueEnum`] into `T`.
fn downcast_to_type(&self, ctx: &mut CodeGenContext<'ctx, '_>, value: BasicValueEnum<'ctx>) -> T;
fn downcast_to_type(ctx: &mut CodeGenContext<'ctx, '_>, value: BasicValueEnum<'ctx>) -> T;
/// # Safety
///
@ -146,7 +113,7 @@ pub trait TypedArrayLikeAccessor<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayL
name: Option<&str>,
) -> T {
let value = self.get_unchecked(ctx, generator, idx, name);
self.downcast_to_type(ctx, value)
Self::downcast_to_type(ctx, value)
}
/// Returns the data at the `idx`-th index.
@ -158,14 +125,13 @@ pub trait TypedArrayLikeAccessor<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayL
name: Option<&str>,
) -> T {
let value = self.get(ctx, generator, idx, name);
self.downcast_to_type(ctx, value)
Self::downcast_to_type(ctx, value)
}
}
/// An array-like value that can have its array elements mutated as an arbitrary type `T`.
pub trait TypedArrayLikeMutator<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayLikeMutator<'ctx, Index> {
/// Casts an element from T into [`BasicValueEnum`].
fn upcast_from_type(&self, ctx: &mut CodeGenContext<'ctx, '_>, value: T) -> BasicValueEnum<'ctx>;
fn upcast_from_type(ctx: &mut CodeGenContext<'ctx, '_>, value: T) -> BasicValueEnum<'ctx>;
/// # Safety
///
@ -177,7 +143,7 @@ pub trait TypedArrayLikeMutator<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayLi
idx: Index,
value: T,
) {
let value = self.upcast_from_type(ctx, value);
let value = Self::upcast_from_type(ctx, value);
self.set_unchecked(ctx, generator, idx, value);
}
@ -189,163 +155,55 @@ pub trait TypedArrayLikeMutator<'ctx, T, Index = IntValue<'ctx>>: UntypedArrayLi
idx: Index,
value: T,
) {
let value = self.upcast_from_type(ctx, value);
let value = Self::upcast_from_type(ctx, value);
self.set(ctx, generator, idx, value);
}
}
/// Type alias for a function that casts a [`BasicValueEnum`] into a `T`.
type ValueDowncastFn<'ctx, T> = Box<dyn Fn(&mut CodeGenContext<'ctx, '_>, BasicValueEnum<'ctx>) -> T>;
/// Type alias for a function that casts a `T` into a [`BasicValueEnum`].
type ValueUpcastFn<'ctx, T> = Box<dyn Fn(&mut CodeGenContext<'ctx, '_>, T) -> BasicValueEnum<'ctx>>;
// TODO: Add TypedArrayLikeAccessAdapter and TypedArrayLikeMutateAdapter
/// An adapter for constraining untyped array values as typed values.
#[allow(clippy::type_complexity)]
pub struct TypedArrayLikeAdapter<'ctx, T, Adapted: ArrayLikeValue<'ctx>> {
adapted: Adapted,
downcast_fn: ValueDowncastFn<'ctx, T>,
upcast_fn: ValueUpcastFn<'ctx, T>,
}
impl<'ctx, T, Adapted> TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: ArrayLikeValue<'ctx> {
/// Creates a [`TypedArrayLikeAdapter`].
///
/// * `adapted` - The value to be adapted.
/// * `downcast_fn` - The function converting a [`BasicValueEnum`] into a `T`.
/// * `upcast_fn` - The function converting a T into a [`BasicValueEnum`].
fn from(
adapted: Adapted,
downcast_fn: ValueDowncastFn<'ctx, T>,
upcast_fn: ValueUpcastFn<'ctx, T>,
) -> Self {
TypedArrayLikeAdapter { adapted, downcast_fn, upcast_fn }
}
}
impl<'ctx, T, Adapted> ArrayLikeValue<'ctx> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: ArrayLikeValue<'ctx> {
fn element_type<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> AnyTypeEnum<'ctx> {
self.adapted.element_type(ctx, generator)
}
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> PointerValue<'ctx> {
self.adapted.base_ptr(ctx, generator)
}
fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> IntValue<'ctx> {
self.adapted.size(ctx, generator)
}
}
impl<'ctx, T, Index, Adapted> ArrayLikeIndexer<'ctx, Index> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: ArrayLikeIndexer<'ctx, Index> {
unsafe fn ptr_offset_unchecked<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
idx: Index,
name: Option<&str>,
) -> PointerValue<'ctx> {
self.adapted.ptr_offset_unchecked(ctx, generator, idx, name)
}
fn ptr_offset<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
idx: Index,
name: Option<&str>,
) -> PointerValue<'ctx> {
self.adapted.ptr_offset(ctx, generator, idx, name)
}
}
impl<'ctx, T, Index, Adapted> UntypedArrayLikeAccessor<'ctx, Index> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: UntypedArrayLikeAccessor<'ctx, Index> {}
impl<'ctx, T, Index, Adapted> UntypedArrayLikeMutator<'ctx, Index> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: UntypedArrayLikeMutator<'ctx, Index> {}
impl<'ctx, T, Index, Adapted> TypedArrayLikeAccessor<'ctx, T, Index> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: UntypedArrayLikeAccessor<'ctx, Index> {
fn downcast_to_type(&self, ctx: &mut CodeGenContext<'ctx, '_>, value: BasicValueEnum<'ctx>) -> T {
(self.downcast_fn)(ctx, value)
}
}
impl<'ctx, T, Index, Adapted> TypedArrayLikeMutator<'ctx, T, Index> for TypedArrayLikeAdapter<'ctx, T, Adapted>
where Adapted: UntypedArrayLikeMutator<'ctx, Index> {
fn upcast_from_type(&self, ctx: &mut CodeGenContext<'ctx, '_>, value: T) -> BasicValueEnum<'ctx> {
(self.upcast_fn)(ctx, value)
}
}
/// An LLVM value representing an array slice, consisting of a pointer to the data and the size of
/// the slice.
#[derive(Copy, Clone)]
pub struct ArraySliceValue<'ctx>(PointerValue<'ctx>, IntValue<'ctx>, Option<&'ctx str>);
pub struct ArrayAllocaValue<'ctx>(PointerValue<'ctx>, IntValue<'ctx>, Option<&'ctx str>);
impl<'ctx> ArraySliceValue<'ctx> {
/// Creates an [`ArraySliceValue`] from a [`PointerValue`] and its size.
impl<'ctx> ArrayAllocaValue<'ctx> {
/// Creates an [`ListValue`] from a [`PointerValue`].
#[must_use]
pub fn from_ptr_val(
ptr: PointerValue<'ctx>,
size: IntValue<'ctx>,
name: Option<&'ctx str>,
) -> Self {
ArraySliceValue(ptr, size, name)
}
}
impl<'ctx> From<ArraySliceValue<'ctx>> for PointerValue<'ctx> {
fn from(value: ArraySliceValue<'ctx>) -> Self {
value.0
}
}
impl<'ctx> ArrayLikeValue<'ctx> for ArraySliceValue<'ctx> {
fn element_type<G: CodeGenerator + ?Sized>(
&self,
_: &CodeGenContext<'ctx, '_>,
_: &G,
) -> AnyTypeEnum<'ctx> {
self.0.get_type().get_element_type()
ArrayAllocaValue(ptr, size, name)
}
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
_: &CodeGenContext<'ctx, '_>,
_: &G,
) -> PointerValue<'ctx> {
/// Returns the underlying [`PointerValue`] pointing to the `list` instance.
#[must_use]
pub fn as_ptr_value(&self) -> PointerValue<'ctx> {
self.0
}
}
impl<'ctx> From<ArrayAllocaValue<'ctx>> for PointerValue<'ctx> {
fn from(value: ArrayAllocaValue<'ctx>) -> Self {
value.as_ptr_value()
}
}
impl<'ctx> ArrayLikeValue<'ctx> for ArrayAllocaValue<'ctx> {
fn size<G: CodeGenerator + ?Sized>(
&self,
_: &CodeGenContext<'ctx, '_>,
_: &G,
_: &mut CodeGenContext<'ctx, '_>,
_: &mut G,
) -> IntValue<'ctx> {
self.1
}
}
impl<'ctx> ArrayLikeIndexer<'ctx> for ArraySliceValue<'ctx> {
impl<'ctx> ArrayLikeIndexer<'ctx> for ArrayAllocaValue<'ctx> {
unsafe fn ptr_offset_unchecked<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
_: &mut G,
idx: IntValue<'ctx>,
name: Option<&str>,
) -> PointerValue<'ctx> {
@ -354,7 +212,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for ArraySliceValue<'ctx> {
.unwrap_or_default();
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(),
&[idx],
var_name.as_str(),
).unwrap()
@ -386,15 +244,17 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for ArraySliceValue<'ctx> {
}
}
impl<'ctx> UntypedArrayLikeAccessor<'ctx> for ArraySliceValue<'ctx> {}
impl<'ctx> UntypedArrayLikeMutator<'ctx> for ArraySliceValue<'ctx> {}
impl<'ctx> UntypedArrayLikeAccessor<'ctx> for ArrayAllocaValue<'ctx> {}
impl<'ctx> UntypedArrayLikeMutator<'ctx> for ArrayAllocaValue<'ctx> {}
#[cfg(not(debug_assertions))]
pub fn assert_is_list<'ctx>(_value: PointerValue<'ctx>, _llvm_usize: IntType<'ctx>) {}
#[cfg(debug_assertions)]
pub fn assert_is_list<'ctx>(value: PointerValue<'ctx>, llvm_usize: IntType<'ctx>) {
ListValue::is_instance(value, llvm_usize).unwrap();
if let Err(msg) = ListValue::is_instance(value, llvm_usize) {
panic!("{msg}")
}
}
/// Proxy type for accessing a `list` value in LLVM.
@ -503,10 +363,10 @@ impl<'ctx> ListValue<'ctx> {
}
/// Stores the `size` of this `list` into this instance.
pub fn store_size<G: CodeGenerator + ?Sized>(
pub fn store_size(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
generator: &dyn CodeGenerator,
size: IntValue<'ctx>,
) {
debug_assert_eq!(size.get_type(), generator.get_size_type(ctx.ctx));
@ -539,31 +399,22 @@ impl<'ctx> From<ListValue<'ctx>> for PointerValue<'ctx> {
#[derive(Copy, Clone)]
pub struct ListDataProxy<'ctx>(ListValue<'ctx>);
impl<'ctx> ArrayLikeValue<'ctx> for ListDataProxy<'ctx> {
fn element_type<G: CodeGenerator + ?Sized>(
&self,
_: &CodeGenContext<'ctx, '_>,
_: &G,
) -> AnyTypeEnum<'ctx> {
self.0.0.get_type().get_element_type()
}
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
_: &G,
) -> PointerValue<'ctx> {
impl<'ctx> ListDataProxy<'ctx> {
/// Returns the single-indirection pointer to the array.
pub fn as_ptr_value(&self, ctx: &CodeGenContext<'ctx, '_>) -> PointerValue<'ctx> {
let var_name = self.0.1.map(|v| format!("{v}.data")).unwrap_or_default();
ctx.builder.build_load(self.0.pptr_to_data(ctx), var_name.as_str())
.map(BasicValueEnum::into_pointer_value)
.unwrap()
}
}
impl<'ctx> ArrayLikeValue<'ctx> for ListDataProxy<'ctx> {
fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
_: &G,
ctx: &mut CodeGenContext<'ctx, '_>,
_: &mut G,
) -> IntValue<'ctx> {
self.0.load_size(ctx, None)
}
@ -573,7 +424,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for ListDataProxy<'ctx> {
unsafe fn ptr_offset_unchecked<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
_: &mut G,
idx: IntValue<'ctx>,
name: Option<&str>,
) -> PointerValue<'ctx> {
@ -582,7 +433,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for ListDataProxy<'ctx> {
.unwrap_or_default();
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(ctx),
&[idx],
var_name.as_str(),
).unwrap()
@ -617,12 +468,32 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for ListDataProxy<'ctx> {
impl<'ctx> UntypedArrayLikeAccessor<'ctx> for ListDataProxy<'ctx> {}
impl<'ctx> UntypedArrayLikeMutator<'ctx> for ListDataProxy<'ctx> {}
impl<'ctx> TypedArrayLikeAccessor<'ctx, IntValue<'ctx>> for ListDataProxy<'ctx> {
fn downcast_to_type(
_: &mut CodeGenContext<'ctx, '_>,
value: BasicValueEnum<'ctx>,
) -> IntValue<'ctx> {
value.into_int_value()
}
}
impl<'ctx> TypedArrayLikeMutator<'ctx, IntValue<'ctx>> for ListDataProxy<'ctx> {
fn upcast_from_type(
_: &mut CodeGenContext<'ctx, '_>,
value: IntValue<'ctx>,
) -> BasicValueEnum<'ctx> {
value.into()
}
}
#[cfg(not(debug_assertions))]
pub fn assert_is_range(_value: PointerValue) {}
#[cfg(debug_assertions)]
pub fn assert_is_range(value: PointerValue) {
RangeValue::is_instance(value).unwrap();
if let Err(msg) = RangeValue::is_instance(value) {
panic!("{msg}")
}
}
/// Proxy type for accessing a `range` value in LLVM.
@ -791,7 +662,9 @@ pub fn assert_is_ndarray<'ctx>(_value: PointerValue<'ctx>, _llvm_usize: IntType<
#[cfg(debug_assertions)]
pub fn assert_is_ndarray<'ctx>(value: PointerValue<'ctx>, llvm_usize: IntType<'ctx>) {
NDArrayValue::is_instance(value, llvm_usize).unwrap();
if let Err(msg) = NDArrayValue::is_instance(value, llvm_usize) {
panic!("{msg}")
}
}
/// Proxy type for accessing an `NDArray` value in LLVM.
@ -877,10 +750,10 @@ impl<'ctx> NDArrayValue<'ctx> {
}
/// Stores the number of dimensions `ndims` into this instance.
pub fn store_ndims<G: CodeGenerator + ?Sized>(
pub fn store_ndims(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
generator: &dyn CodeGenerator,
ndims: IntValue<'ctx>,
) {
debug_assert_eq!(ndims.get_type(), generator.get_size_type(ctx.ctx));
@ -981,31 +854,22 @@ impl<'ctx> From<NDArrayValue<'ctx>> for PointerValue<'ctx> {
#[derive(Copy, Clone)]
pub struct NDArrayDimsProxy<'ctx>(NDArrayValue<'ctx>);
impl<'ctx> ArrayLikeValue<'ctx> for NDArrayDimsProxy<'ctx> {
fn element_type<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> AnyTypeEnum<'ctx> {
self.0.dim_sizes().base_ptr(ctx, generator).get_type().get_element_type()
}
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
_: &G,
) -> PointerValue<'ctx> {
let var_name = self.0.1.map(|v| format!("{v}.data")).unwrap_or_default();
impl<'ctx> NDArrayDimsProxy<'ctx> {
/// Returns the single-indirection pointer to the array.
pub fn as_ptr_value(&self, ctx: &CodeGenContext<'ctx, '_>) -> PointerValue<'ctx> {
let var_name = self.0.1.map(|v| format!("{v}.dims")).unwrap_or_default();
ctx.builder.build_load(self.0.ptr_to_dims(ctx), var_name.as_str())
.map(BasicValueEnum::into_pointer_value)
.unwrap()
}
}
impl<'ctx> ArrayLikeValue<'ctx> for NDArrayDimsProxy<'ctx> {
fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
_: &G,
ctx: &mut CodeGenContext<'ctx, '_>,
_: &mut G,
) -> IntValue<'ctx> {
self.0.load_ndims(ctx)
}
@ -1015,7 +879,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ctx> {
unsafe fn ptr_offset_unchecked<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
_: &mut G,
idx: IntValue<'ctx>,
name: Option<&str>,
) -> PointerValue<'ctx> {
@ -1024,7 +888,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ctx> {
.unwrap_or_default();
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(ctx),
&[idx],
var_name.as_str(),
).unwrap()
@ -1064,7 +928,6 @@ impl<'ctx> UntypedArrayLikeMutator<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'c
impl<'ctx> TypedArrayLikeAccessor<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ctx> {
fn downcast_to_type(
&self,
_: &mut CodeGenContext<'ctx, '_>,
value: BasicValueEnum<'ctx>,
) -> IntValue<'ctx> {
@ -1074,7 +937,6 @@ impl<'ctx> TypedArrayLikeAccessor<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ct
impl<'ctx> TypedArrayLikeMutator<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ctx> {
fn upcast_from_type(
&self,
_: &mut CodeGenContext<'ctx, '_>,
value: IntValue<'ctx>,
) -> BasicValueEnum<'ctx> {
@ -1086,20 +948,9 @@ impl<'ctx> TypedArrayLikeMutator<'ctx, IntValue<'ctx>> for NDArrayDimsProxy<'ctx
#[derive(Copy, Clone)]
pub struct NDArrayDataProxy<'ctx>(NDArrayValue<'ctx>);
impl<'ctx> ArrayLikeValue<'ctx> for NDArrayDataProxy<'ctx> {
fn element_type<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
) -> AnyTypeEnum<'ctx> {
self.0.data().base_ptr(ctx, generator).get_type().get_element_type()
}
fn base_ptr<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
_: &G,
) -> PointerValue<'ctx> {
impl<'ctx> NDArrayDataProxy<'ctx> {
/// Returns the single-indirection pointer to the array.
pub fn as_ptr_value(&self, ctx: &CodeGenContext<'ctx, '_>) -> PointerValue<'ctx> {
let var_name = self.0.1.map(|v| format!("{v}.data")).unwrap_or_default();
ctx.builder.build_load(self.0.ptr_to_data(ctx), var_name.as_str())
@ -1107,12 +958,24 @@ impl<'ctx> ArrayLikeValue<'ctx> for NDArrayDataProxy<'ctx> {
.unwrap()
}
pub fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
) -> IntValue<'ctx> {
let ndims = self.0.load_ndims(ctx);
let dims = self.0.dim_sizes().as_ptr_value(ctx);
call_ndarray_calc_size(generator, ctx, ndims, dims)
}
}
impl<'ctx> ArrayLikeValue<'ctx> for NDArrayDataProxy<'ctx> {
fn size<G: CodeGenerator + ?Sized>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
generator: &G,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
) -> IntValue<'ctx> {
call_ndarray_calc_size(generator, ctx, &self.as_slice_value(ctx, generator))
self.size(ctx, generator)
}
}
@ -1120,12 +983,12 @@ impl<'ctx> ArrayLikeIndexer<'ctx> for NDArrayDataProxy<'ctx> {
unsafe fn ptr_offset_unchecked<G: CodeGenerator + ?Sized>(
&self,
ctx: &mut CodeGenContext<'ctx, '_>,
generator: &mut G,
_: &mut G,
idx: IntValue<'ctx>,
name: Option<&str>,
) -> PointerValue<'ctx> {
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(ctx),
&[idx],
name.unwrap_or_default(),
).unwrap()
@ -1180,7 +1043,7 @@ impl<'ctx> ArrayLikeIndexer<'ctx, ArrayValue<'ctx>> for NDArrayDataProxy<'ctx> {
unsafe {
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(ctx),
&[index],
name.unwrap_or_default(),
)
@ -1280,7 +1143,7 @@ impl<'ctx, Index: UntypedArrayLikeAccessor<'ctx>> ArrayLikeIndexer<'ctx, Index>
unsafe {
ctx.builder.build_in_bounds_gep(
self.base_ptr(ctx, generator),
self.as_ptr_value(ctx),
&[index],
name.unwrap_or_default(),
).unwrap()

View File

@ -9,7 +9,6 @@ use crate::{
use nac3parser::ast::StrRef;
use std::collections::HashMap;
use indexmap::IndexMap;
pub struct ConcreteTypeStore {
store: Vec<ConcreteTypeEnum>,
@ -51,7 +50,7 @@ pub enum ConcreteTypeEnum {
TObj {
obj_id: DefinitionId,
fields: HashMap<StrRef, (ConcreteType, bool)>,
params: IndexMap<u32, ConcreteType>,
params: HashMap<u32, ConcreteType>,
},
TVirtual {
ty: ConcreteType,

View File

@ -2,14 +2,7 @@ use std::{collections::HashMap, convert::TryInto, iter::once, iter::zip};
use crate::{
codegen::{
classes::{
ArrayLikeIndexer,
ArrayLikeValue,
ListValue,
NDArrayValue,
RangeValue,
UntypedArrayLikeAccessor,
},
classes::{ArrayLikeIndexer, ListValue, NDArrayValue, RangeValue, TypedArrayLikeAccessor, UntypedArrayLikeAccessor},
concrete_type::{ConcreteFuncArg, ConcreteTypeEnum, ConcreteTypeStore},
gen_in_range_check,
get_llvm_type,
@ -60,7 +53,7 @@ pub fn get_subst_key(
params.clone()
})
.unwrap_or_default();
vars.extend(fun_vars);
vars.extend(fun_vars.iter());
let sorted = vars.keys().filter(|id| filter.map_or(true, |v| v.contains(id))).sorted();
sorted
.map(|id| {
@ -199,9 +192,9 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
}
/// See [`get_llvm_abi_type`].
pub fn get_llvm_abi_type<G: CodeGenerator + ?Sized>(
pub fn get_llvm_abi_type(
&mut self,
generator: &mut G,
generator: &mut dyn CodeGenerator,
ty: Type,
) -> BasicTypeEnum<'ctx> {
get_llvm_abi_type(
@ -299,9 +292,9 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
}
/// Generates a binary operation `op` between two integral operands `lhs` and `rhs`.
pub fn gen_int_ops<G: CodeGenerator + ?Sized>(
pub fn gen_int_ops(
&mut self,
generator: &mut G,
generator: &mut dyn CodeGenerator,
op: &Operator,
lhs: BasicValueEnum<'ctx>,
rhs: BasicValueEnum<'ctx>,
@ -504,7 +497,7 @@ impl<'ctx, 'a> CodeGenContext<'ctx, 'a> {
&mut self,
generator: &mut G,
s: S,
) -> BasicValueEnum<'ctx>
) -> BasicValueEnum<'ctx>
where
G: CodeGenerator + ?Sized,
S: Into<String>,
@ -890,7 +883,7 @@ pub fn destructure_range<'ctx>(
/// Returns an instance of [`PointerValue`] pointing to the List structure. The List structure is
/// defined as `type { ty*, size_t }` in LLVM, where the first element stores the pointer to the
/// data, and the second element stores the size of the List.
pub fn allocate_list<'ctx, G: CodeGenerator + ?Sized>(
pub fn allocate_list<'ctx, G: CodeGenerator>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ty: BasicTypeEnum<'ctx>,
@ -990,7 +983,7 @@ pub fn gen_comprehension<'ctx, G: CodeGenerator>(
list_alloc_size.into_int_value(),
Some("listcomp.addr")
);
list_content = list.data().base_ptr(ctx, generator);
list_content = list.data().as_ptr_value(ctx);
let i = generator.gen_store_target(ctx, target, Some("i.addr"))?.unwrap();
ctx.builder
@ -1023,7 +1016,7 @@ pub fn gen_comprehension<'ctx, G: CodeGenerator>(
)
.into_int_value();
list = allocate_list(generator, ctx, elem_ty, length, Some("listcomp"));
list_content = list.data().base_ptr(ctx, generator);
list_content = list.data().as_ptr_value(ctx);
let counter = generator.gen_var_alloc(ctx, size_t.into(), Some("counter.addr"))?;
// counter = -1
ctx.builder.build_store(counter, size_t.const_int(u64::MAX, true)).unwrap();
@ -1386,7 +1379,7 @@ fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>(
};
call_memcpy_generic(
ctx,
ndarray.dim_sizes().base_ptr(ctx, generator),
ndarray.dim_sizes().as_ptr_value(ctx),
v_dims_src_ptr,
ctx.builder
.build_int_mul(ndarray_num_dims, llvm_usize.size_of(), "")
@ -1398,7 +1391,8 @@ fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>(
let ndarray_num_elems = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
ndarray.load_ndims(ctx),
ndarray.dim_sizes().as_ptr_value(ctx),
);
ndarray.create_data(ctx, llvm_ndarray_data_t, ndarray_num_elems);
@ -1410,7 +1404,7 @@ fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>(
);
call_memcpy_generic(
ctx,
ndarray.data().base_ptr(ctx, generator),
ndarray.data().as_ptr_value(ctx),
v_data_src_ptr,
ctx.builder
.build_int_mul(ndarray_num_elems, llvm_ndarray_data_t.size_of().unwrap(), "")
@ -2043,11 +2037,12 @@ pub fn gen_expr<'ctx, G: CodeGenerator>(
[Some(raw_index), Some(len), None],
expr.location,
);
v.data().get(ctx, generator, index, None).into()
v.data().get_typed(ctx, generator, index, None).into()
}
}
TypeEnum::TObj { obj_id, params, .. } if *obj_id == PRIMITIVE_DEF_IDS.ndarray => {
let (ty, ndims) = params.iter()
.sorted_by_key(|(var_id, _)| *var_id)
.map(|(_, ty)| ty)
.collect_tuple()
.unwrap();

View File

@ -1,5 +1,5 @@
use crate::{
codegen::{classes::ArraySliceValue, expr::*, stmt::*, bool_to_i1, bool_to_i8, CodeGenContext},
codegen::{expr::*, stmt::*, bool_to_i1, bool_to_i8, CodeGenContext},
symbol_resolver::ValueEnum,
toplevel::{DefinitionId, TopLevelDef},
typecheck::typedef::{FunSignature, Type},
@ -99,8 +99,8 @@ pub trait CodeGenerator {
ctx: &mut CodeGenContext<'ctx, '_>,
ty: BasicTypeEnum<'ctx>,
size: IntValue<'ctx>,
name: Option<&'ctx str>,
) -> Result<ArraySliceValue<'ctx>, String> {
name: Option<&str>,
) -> Result<PointerValue<'ctx>, String> {
gen_array_var(ctx, ty, size, name)
}

View File

@ -296,7 +296,7 @@ uint64_t __nac3_ndarray_flatten_index64(
return idx;
}
void __nac3_ndarray_calc_broadcast(
void __nac3_ndarray_calc_broadcast_sz(
const uint32_t *lhs_dims,
uint32_t lhs_ndims,
const uint32_t *rhs_dims,
@ -326,7 +326,7 @@ void __nac3_ndarray_calc_broadcast(
}
}
void __nac3_ndarray_calc_broadcast64(
void __nac3_ndarray_calc_broadcast_sz64(
const uint64_t *lhs_dims,
uint64_t lhs_ndims,
const uint64_t *rhs_dims,

View File

@ -1,18 +1,11 @@
use crate::typecheck::typedef::Type;
use super::{
classes::{
ArrayLikeIndexer,
ArraySliceValue,
ArrayLikeValue,
ListValue,
NDArrayValue,
UntypedArrayLikeAccessor,
UntypedArrayLikeMutator,
},
classes::{ListValue, NDArrayValue, TypedArrayLikeAccessor, UntypedArrayLikeAccessor},
CodeGenContext,
CodeGenerator,
llvm_intrinsics,
stmt::{gen_for_callback_incrementing, gen_if_callback},
};
use inkwell::{
attributes::{Attribute, AttributeLoc},
@ -25,6 +18,7 @@ use inkwell::{
};
use itertools::Either;
use nac3parser::ast::Expr;
use crate::codegen::classes::ArrayAllocaValue;
#[must_use]
pub fn load_irrt(ctx: &Context) -> Module {
@ -48,8 +42,8 @@ pub fn load_irrt(ctx: &Context) -> Module {
// repeated squaring method adapted from GNU Scientific Library:
// https://git.savannah.gnu.org/cgit/gsl.git/tree/sys/pow_int.c
pub fn integer_power<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
pub fn integer_power<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
base: IntValue<'ctx>,
exp: IntValue<'ctx>,
@ -90,8 +84,8 @@ pub fn integer_power<'ctx, G: CodeGenerator + ?Sized>(
.unwrap()
}
pub fn calculate_len_for_slice_range<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
pub fn calculate_len_for_slice_range<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
start: IntValue<'ctx>,
end: IntValue<'ctx>,
@ -312,8 +306,8 @@ pub fn handle_slice_index_bound<'ctx, G: CodeGenerator>(
/// This function handles 'end' **inclusively**.
/// Order of tuples `assign_idx` and `value_idx` is ('start', 'end', 'step').
/// Negative index should be handled before entering this function
pub fn list_slice_assignment<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
pub fn list_slice_assignment<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
ty: BasicTypeEnum<'ctx>,
dest_arr: ListValue<'ctx>,
@ -347,7 +341,7 @@ pub fn list_slice_assignment<'ctx, G: CodeGenerator + ?Sized>(
let zero = int32.const_zero();
let one = int32.const_int(1, false);
let dest_arr_ptr = dest_arr.data().base_ptr(ctx, generator);
let dest_arr_ptr = dest_arr.data().as_ptr_value(ctx);
let dest_arr_ptr = ctx.builder.build_pointer_cast(
dest_arr_ptr,
elem_ptr_type,
@ -355,7 +349,7 @@ pub fn list_slice_assignment<'ctx, G: CodeGenerator + ?Sized>(
).unwrap();
let dest_len = dest_arr.load_size(ctx, Some("dest.len"));
let dest_len = ctx.builder.build_int_truncate_or_bit_cast(dest_len, int32, "srclen32").unwrap();
let src_arr_ptr = src_arr.data().base_ptr(ctx, generator);
let src_arr_ptr = src_arr.data().as_ptr_value(ctx);
let src_arr_ptr = ctx.builder.build_pointer_cast(
src_arr_ptr,
elem_ptr_type,
@ -477,8 +471,8 @@ pub fn list_slice_assignment<'ctx, G: CodeGenerator + ?Sized>(
}
/// Generates a call to `isinf` in IR. Returns an `i1` representing the result.
pub fn call_isinf<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
pub fn call_isinf<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &CodeGenContext<'ctx, '_>,
v: FloatValue<'ctx>,
) -> IntValue<'ctx> {
@ -498,8 +492,8 @@ pub fn call_isinf<'ctx, G: CodeGenerator + ?Sized>(
}
/// Generates a call to `isnan` in IR. Returns an `i1` representing the result.
pub fn call_isnan<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
pub fn call_isnan<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &CodeGenContext<'ctx, '_>,
v: FloatValue<'ctx>,
) -> IntValue<'ctx> {
@ -583,14 +577,12 @@ pub fn call_j0<'ctx>(
///
/// * `num_dims` - An [`IntValue`] containing the number of dimensions.
/// * `dims` - A [`PointerValue`] to an array containing the size of each dimension.
pub fn call_ndarray_calc_size<'ctx, G, Dims>(
pub fn call_ndarray_calc_size<'ctx, G: CodeGenerator + ?Sized>(
generator: &G,
ctx: &CodeGenContext<'ctx, '_>,
dims: &Dims,
) -> IntValue<'ctx>
where
G: CodeGenerator + ?Sized,
Dims: ArrayLikeIndexer<'ctx>, {
ctx: &mut CodeGenContext<'ctx, '_>,
num_dims: IntValue<'ctx>,
dims: PointerValue<'ctx>,
) -> IntValue<'ctx> {
let llvm_i64 = ctx.ctx.i64_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
@ -617,8 +609,8 @@ pub fn call_ndarray_calc_size<'ctx, G, Dims>(
.build_call(
ndarray_calc_size_fn,
&[
dims.base_ptr(ctx, generator).into(),
dims.size(ctx, generator).into(),
dims.into(),
num_dims.into(),
],
"",
)
@ -633,12 +625,12 @@ pub fn call_ndarray_calc_size<'ctx, G, Dims>(
/// * `index` - The index to compute the multidimensional index for.
/// * `ndarray` - LLVM pointer to the `NDArray`. This value must be the LLVM representation of an
/// `NDArray`.
pub fn call_ndarray_calc_nd_indices<'ctx, G: CodeGenerator + ?Sized>(
generator: &G,
pub fn call_ndarray_calc_nd_indices<'ctx>(
generator: &dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
index: IntValue<'ctx>,
ndarray: NDArrayValue<'ctx>,
) -> ArraySliceValue<'ctx> {
) -> ArrayAllocaValue<'ctx> {
let llvm_void = ctx.ctx.void_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
@ -677,7 +669,7 @@ pub fn call_ndarray_calc_nd_indices<'ctx, G: CodeGenerator + ?Sized>(
ndarray_calc_nd_indices_fn,
&[
index.into(),
ndarray_dims.base_ptr(ctx, generator).into(),
ndarray_dims.as_ptr_value(ctx).into(),
ndarray_num_dims.into(),
indices.into(),
],
@ -685,18 +677,16 @@ pub fn call_ndarray_calc_nd_indices<'ctx, G: CodeGenerator + ?Sized>(
)
.unwrap();
ArraySliceValue::from_ptr_val(indices, ndarray_num_dims, None)
ArrayAllocaValue::from_ptr_val(indices, ndarray_num_dims, None)
}
fn call_ndarray_flatten_index_impl<'ctx, G, Indices>(
fn call_ndarray_flatten_index_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &G,
ctx: &CodeGenContext<'ctx, '_>,
ndarray: NDArrayValue<'ctx>,
indices: &Indices,
) -> IntValue<'ctx>
where
G: CodeGenerator + ?Sized,
Indices: ArrayLikeIndexer<'ctx>, {
indices: PointerValue<'ctx>,
indices_size: IntValue<'ctx>,
) -> IntValue<'ctx> {
let llvm_i32 = ctx.ctx.i32_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
@ -704,14 +694,14 @@ fn call_ndarray_flatten_index_impl<'ctx, G, Indices>(
let llvm_pusize = llvm_usize.ptr_type(AddressSpace::default());
debug_assert_eq!(
IntType::try_from(indices.element_type(ctx, generator))
IntType::try_from(indices.get_type().get_element_type())
.map(IntType::get_bit_width)
.unwrap_or_default(),
llvm_i32.get_bit_width(),
"Expected i32 value for argument `indices` to `call_ndarray_flatten_index_impl`"
);
debug_assert_eq!(
indices.size(ctx, generator).get_type().get_bit_width(),
indices_size.get_type().get_bit_width(),
llvm_usize.get_bit_width(),
"Expected usize integer value for argument `indices_size` to `call_ndarray_flatten_index_impl`"
);
@ -742,10 +732,10 @@ fn call_ndarray_flatten_index_impl<'ctx, G, Indices>(
.build_call(
ndarray_flatten_index_fn,
&[
ndarray_dims.base_ptr(ctx, generator).into(),
ndarray_dims.as_ptr_value(ctx).into(),
ndarray_num_dims.into(),
indices.base_ptr(ctx, generator).into(),
indices.size(ctx, generator).into(),
indices.into(),
indices_size.into(),
],
"",
)
@ -763,21 +753,25 @@ fn call_ndarray_flatten_index_impl<'ctx, G, Indices>(
/// * `ndarray` - LLVM pointer to the `NDArray`. This value must be the LLVM representation of an
/// `NDArray`.
/// * `indices` - The multidimensional index to compute the flattened index for.
pub fn call_ndarray_flatten_index<'ctx, G, Index>(
pub fn call_ndarray_flatten_index<'ctx, G: CodeGenerator + ?Sized, Index: UntypedArrayLikeAccessor<'ctx>>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray: NDArrayValue<'ctx>,
indices: &Index,
) -> IntValue<'ctx>
where
G: CodeGenerator + ?Sized,
Index: ArrayLikeIndexer<'ctx>, {
) -> IntValue<'ctx> {
let llvm_usize = generator.get_size_type(ctx.ctx);
let indices_size = indices.size(ctx, generator);
let indices_begin = unsafe {
indices.ptr_offset_unchecked(ctx, generator, llvm_usize.const_zero(), None)
};
call_ndarray_flatten_index_impl(
generator,
ctx,
ndarray,
indices,
indices_begin,
indices_size,
)
}
/// Generates a call to `__nac3_ndarray_flatten_index`. Returns the flattened index for the
@ -799,34 +793,34 @@ pub fn call_ndarray_flatten_index_const<'ctx, G: CodeGenerator + ?Sized>(
ctx,
indices.get_type().get_element_type(),
llvm_usize.const_int(indices_size as u64, false),
None,
None
).unwrap();
for i in 0..indices_size {
let v = ctx.builder.build_extract_value(indices, i, "")
.unwrap()
.into_int_value();
unsafe {
indices_alloca.set_unchecked(
ctx,
generator,
ctx.ctx.i32_type().const_int(i as u64, false),
v.into(),
);
}
let elem_ptr = unsafe {
ctx.builder.build_in_bounds_gep(
indices_alloca,
&[ctx.ctx.i32_type().const_int(i as u64, false)],
""
)
}.unwrap();
ctx.builder.build_store(elem_ptr, v).unwrap();
}
call_ndarray_flatten_index_impl(
generator,
ctx,
ndarray,
&indices_alloca,
indices_alloca,
llvm_usize.const_int(indices_size as u64, false),
)
}
/// Generates a call to `__nac3_ndarray_calc_broadcast`. Returns a tuple containing the number of
/// Generates a call to `__nac3_ndarray_calc_broadcast_sz`. Returns a tuple containing the number of
/// dimension and size of each dimension of the resultant `ndarray`.
pub fn call_ndarray_calc_broadcast<'ctx, G: CodeGenerator + ?Sized>(
pub fn call_ndarray_calc_broadcast_sz<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
lhs: NDArrayValue<'ctx>,
@ -836,8 +830,8 @@ pub fn call_ndarray_calc_broadcast<'ctx, G: CodeGenerator + ?Sized>(
let llvm_pusize = llvm_usize.ptr_type(AddressSpace::default());
let ndarray_calc_broadcast_fn_name = match llvm_usize.get_bit_width() {
32 => "__nac3_ndarray_calc_broadcast",
64 => "__nac3_ndarray_calc_broadcast64",
32 => "__nac3_ndarray_calc_broadcast_sz",
64 => "__nac3_ndarray_calc_broadcast_sz64",
bw => unreachable!("Unsupported size type bit width: {}", bw)
};
let ndarray_calc_broadcast_fn = ctx.module.get_function(ndarray_calc_broadcast_fn_name).unwrap_or_else(|| {
@ -857,28 +851,80 @@ pub fn call_ndarray_calc_broadcast<'ctx, G: CodeGenerator + ?Sized>(
let lhs_ndims = lhs.load_ndims(ctx);
let rhs_ndims = rhs.load_ndims(ctx);
let min_ndims = llvm_intrinsics::call_int_umin(ctx, lhs_ndims, rhs_ndims, None);
let max_ndims = llvm_intrinsics::call_int_umax(ctx, lhs_ndims, rhs_ndims, None);
// TODO: Generate assertion checks for whether each dimension is compatible
// gen_for_callback_incrementing(
// generator,
// ctx,
// llvm_usize.const_zero(),
// (max_ndims, false),
// |generator, ctx, idx| {
// let lhs_dim_sz =
//
// let lhs_elem = lhs.get_dims().get(ctx, generator, idx, None);
// let rhs_elem = rhs.get_dims().get(ctx, generator, idx, None);
//
//
// },
// llvm_usize.const_int(1, false),
// ).unwrap();
gen_for_callback_incrementing(
generator,
ctx,
llvm_usize.const_zero(),
(max_ndims, false),
|generator, ctx, idx| {
gen_if_callback(
generator,
ctx,
|_, ctx| {
// Only compare the dimensions of the array with fewer dimensions, since any
// additional dimensions are implicitly broadcasted
let lhs_idx_geq_dim = ctx.builder
.build_int_compare(IntPredicate::UGE, idx, min_ndims, "")
.unwrap();
let rhs_idx_geq_dim = ctx.builder
.build_int_compare(IntPredicate::UGE, idx, min_ndims, "")
.unwrap();
let lhs_dims = lhs.dim_sizes().base_ptr(ctx, generator);
Ok(ctx.builder.build_and(lhs_idx_geq_dim, rhs_idx_geq_dim, "").unwrap())
},
|generator, ctx| {
let ri = ctx.builder
.build_int_sub(min_ndims, idx, "")
.unwrap();
let (lhs_dim, rhs_dim) = unsafe {
(
lhs.dim_sizes().get_typed_unchecked(ctx, generator, ri, None),
rhs.dim_sizes().get_typed_unchecked(ctx, generator, ri, None),
)
};
let lhs_dim_ne_1 = ctx.builder
.build_int_compare(IntPredicate::NE, lhs_dim, lhs_dim.get_type().const_int(1, false), "")
.unwrap();
let rhs_dim_ne_1 = ctx.builder
.build_int_compare(IntPredicate::NE, rhs_dim, rhs_dim.get_type().const_int(1, false), "")
.unwrap();
let lhs_ne_rhs = ctx.builder
.build_int_compare(IntPredicate::NE, lhs_dim, rhs_dim, "")
.unwrap();
let both_dims_ne_1 = ctx.builder
.build_and(lhs_dim_ne_1, rhs_dim_ne_1, "")
.unwrap();
let dims_not_broadcastable = ctx.builder
.build_and(both_dims_ne_1, lhs_ne_rhs, "")
.unwrap();
ctx.make_assert(
generator,
dims_not_broadcastable,
"0:ValueError",
"operands cannot be broadcast together",
[None, None, None],
ctx.current_loc,
);
Ok(())
},
None,
)?;
Ok(())
},
llvm_usize.const_int(1, false),
).unwrap();
let lhs_dims = lhs.dim_sizes().as_ptr_value(ctx);
let lhs_ndims = lhs.load_ndims(ctx);
let rhs_dims = rhs.dim_sizes().base_ptr(ctx, generator);
let rhs_dims = rhs.dim_sizes().as_ptr_value(ctx);
let rhs_ndims = rhs.load_ndims(ctx);
let out_dims = ctx.builder.build_array_alloca(llvm_usize, max_ndims, "").unwrap();
@ -905,8 +951,8 @@ pub fn call_ndarray_calc_broadcast_index<'ctx, G: CodeGenerator + ?Sized, Broadc
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
array: NDArrayValue<'ctx>,
broadcast_idx: &BroadcastIdx,
) -> ArraySliceValue<'ctx> {
broadcast_idx: BroadcastIdx,
) -> ArrayAllocaValue<'ctx> {
let llvm_usize = generator.get_size_type(ctx.ctx);
let llvm_pusize = llvm_usize.ptr_type(AddressSpace::default());
@ -933,9 +979,9 @@ pub fn call_ndarray_calc_broadcast_index<'ctx, G: CodeGenerator + ?Sized, Broadc
let broadcast_size = broadcast_idx.size(ctx, generator);
let out_idx = ctx.builder.build_array_alloca(llvm_usize, broadcast_size, "").unwrap();
let out_idx = ArraySliceValue::from_ptr_val(out_idx, broadcast_size, None);
let out_idx = ArrayAllocaValue::from_ptr_val(out_idx, broadcast_size, None);
let array_dims = array.dim_sizes().base_ptr(ctx, generator);
let array_dims = array.dim_sizes().as_ptr_value(ctx);
let array_ndims = array.load_ndims(ctx);
let broadcast_idx_ptr = unsafe {
broadcast_idx.ptr_offset_unchecked(
@ -953,7 +999,7 @@ pub fn call_ndarray_calc_broadcast_index<'ctx, G: CodeGenerator + ?Sized, Broadc
array_dims.into(),
array_ndims.into(),
broadcast_idx_ptr.into(),
out_idx.base_ptr(ctx, generator).into(),
out_idx.as_ptr_value().into(),
],
"",
)

View File

@ -554,10 +554,10 @@ fn get_llvm_type<'ctx, G: CodeGenerator + ?Sized>(
/// be byte-aligned for the variable to be addressable in memory, whereas there is no such
/// restriction for ABI representations.
#[allow(clippy::too_many_arguments)]
fn get_llvm_abi_type<'ctx, G: CodeGenerator + ?Sized>(
fn get_llvm_abi_type<'ctx>(
ctx: &'ctx Context,
module: &Module<'ctx>,
generator: &mut G,
generator: &mut dyn CodeGenerator,
unifier: &mut Unifier,
top_level: &TopLevelContext,
type_cache: &mut HashMap<Type, BasicTypeEnum<'ctx>>,

View File

@ -8,8 +8,6 @@ use crate::{
codegen::{
classes::{
ArrayLikeIndexer,
ArraySliceValue,
ArrayLikeValue,
ListValue,
NDArrayValue,
TypedArrayLikeAccessor,
@ -18,7 +16,7 @@ use crate::{
CodeGenContext,
CodeGenerator,
irrt::{
call_ndarray_calc_broadcast,
call_ndarray_calc_broadcast_sz,
call_ndarray_calc_nd_indices,
call_ndarray_calc_size,
},
@ -32,6 +30,7 @@ use crate::{
},
typecheck::typedef::{FunSignature, Type},
};
use crate::codegen::classes::ArrayAllocaValue;
/// Creates an `NDArray` instance from a dynamic shape.
///
@ -39,8 +38,8 @@ use crate::{
/// * `shape` - The shape of the `NDArray`.
/// * `shape_len_fn` - A function that retrieves the number of dimensions from `shape`.
/// * `shape_data_fn` - A function that retrieves the size of a dimension from `shape`.
fn create_ndarray_dyn_shape<'ctx, 'a, G, V, LenFn, DataFn>(
generator: &mut G,
fn create_ndarray_dyn_shape<'ctx, 'a, V, LenFn, DataFn>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, 'a>,
elem_ty: Type,
shape: &V,
@ -48,9 +47,8 @@ fn create_ndarray_dyn_shape<'ctx, 'a, G, V, LenFn, DataFn>(
shape_data_fn: DataFn,
) -> Result<NDArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
LenFn: Fn(&mut G, &mut CodeGenContext<'ctx, 'a>, &V) -> Result<IntValue<'ctx>, String>,
DataFn: Fn(&mut G, &mut CodeGenContext<'ctx, 'a>, &V, IntValue<'ctx>) -> Result<IntValue<'ctx>, String>,
LenFn: Fn(&mut dyn CodeGenerator, &mut CodeGenContext<'ctx, 'a>, &V) -> Result<IntValue<'ctx>, String>,
DataFn: Fn(&mut dyn CodeGenerator, &mut CodeGenContext<'ctx, 'a>, &V, IntValue<'ctx>) -> Result<IntValue<'ctx>, String>,
{
let ndarray_ty = make_ndarray_ty(&mut ctx.unifier, &ctx.primitives, Some(elem_ty), None);
@ -131,7 +129,8 @@ fn create_ndarray_dyn_shape<'ctx, 'a, G, V, LenFn, DataFn>(
let ndarray_num_elems = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
ndarray.load_ndims(ctx),
ndarray.dim_sizes().as_ptr_value(ctx),
);
ndarray.create_data(ctx, llvm_ndarray_data_t, ndarray_num_elems);
@ -142,8 +141,8 @@ fn create_ndarray_dyn_shape<'ctx, 'a, G, V, LenFn, DataFn>(
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The shape of the `NDArray`, represented as an LLVM [`ArrayValue`].
fn create_ndarray_const_shape<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn create_ndarray_const_shape<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: ArrayValue<'ctx>
@ -201,18 +200,20 @@ fn create_ndarray_const_shape<'ctx, G: CodeGenerator + ?Sized>(
ctx.builder.build_store(ndarray_dim, shape_dim).unwrap();
}
let ndarray_dims = ndarray.dim_sizes().as_ptr_value(ctx);
let ndarray_num_elems = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
ndarray.load_ndims(ctx),
ndarray_dims,
);
ndarray.create_data(ctx, llvm_ndarray_data_t, ndarray_num_elems);
Ok(ndarray)
}
fn ndarray_zero_value<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn ndarray_zero_value<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
) -> BasicValueEnum<'ctx> {
@ -231,8 +232,8 @@ fn ndarray_zero_value<'ctx, G: CodeGenerator + ?Sized>(
}
}
fn ndarray_one_value<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn ndarray_one_value<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
) -> BasicValueEnum<'ctx> {
@ -257,8 +258,8 @@ fn ndarray_one_value<'ctx, G: CodeGenerator + ?Sized>(
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
fn call_ndarray_empty_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn call_ndarray_empty_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: ListValue<'ctx>,
@ -272,7 +273,7 @@ fn call_ndarray_empty_impl<'ctx, G: CodeGenerator + ?Sized>(
Ok(shape.load_size(ctx, None))
},
|generator, ctx, shape, idx| {
Ok(shape.data().get(ctx, generator, idx, None).into_int_value())
Ok(shape.data().get_typed(ctx, generator, idx, None))
},
)
}
@ -294,7 +295,8 @@ fn ndarray_fill_flattened<'ctx, 'a, G, ValueFn>(
let ndarray_num_elems = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
ndarray.load_ndims(ctx),
ndarray.dim_sizes().as_ptr_value(ctx),
);
gen_for_callback_incrementing(
@ -318,15 +320,14 @@ fn ndarray_fill_flattened<'ctx, 'a, G, ValueFn>(
/// Generates LLVM IR for populating the entire `NDArray` using a lambda with the dimension-indices
/// as its input.
fn ndarray_fill_indexed<'ctx, G, ValueFn>(
generator: &mut G,
fn ndarray_fill_indexed<'ctx, ValueFn>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray: NDArrayValue<'ctx>,
value_fn: ValueFn,
) -> Result<(), String>
where
G: CodeGenerator + ?Sized,
ValueFn: Fn(&mut G, &mut CodeGenContext<'ctx, '_>, ArraySliceValue<'ctx>) -> Result<BasicValueEnum<'ctx>, String>,
ValueFn: Fn(&mut dyn CodeGenerator, &mut CodeGenContext<'ctx, '_>, ArrayAllocaValue<'ctx>) -> Result<BasicValueEnum<'ctx>, String>,
{
ndarray_fill_flattened(
generator,
@ -385,8 +386,8 @@ fn ndarray_broadcast_fill_flattened<'ctx, G, ValueFn>(
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
fn call_ndarray_zeros_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn call_ndarray_zeros_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: ListValue<'ctx>,
@ -421,8 +422,8 @@ fn call_ndarray_zeros_impl<'ctx, G: CodeGenerator + ?Sized>(
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
fn call_ndarray_ones_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn call_ndarray_ones_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: ListValue<'ctx>,
@ -457,8 +458,8 @@ fn call_ndarray_ones_impl<'ctx, G: CodeGenerator + ?Sized>(
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
fn call_ndarray_full_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn call_ndarray_full_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: ListValue<'ctx>,
@ -500,8 +501,8 @@ fn call_ndarray_full_impl<'ctx, G: CodeGenerator + ?Sized>(
/// LLVM-typed implementation for generating the implementation for `ndarray.eye`.
///
/// * `elem_ty` - The element type of the `NDArray`.
fn call_ndarray_eye_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn call_ndarray_eye_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
nrows: IntValue<'ctx>,
@ -569,8 +570,8 @@ fn call_ndarray_eye_impl<'ctx, G: CodeGenerator + ?Sized>(
/// LLVM-typed implementation for generating the implementation for `ndarray.copy`.
///
/// * `elem_ty` - The element type of the `NDArray`.
fn ndarray_copy_impl<'ctx, G: CodeGenerator + ?Sized>(
generator: &mut G,
fn ndarray_copy_impl<'ctx>(
generator: &mut dyn CodeGenerator,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
this: NDArrayValue<'ctx>,
@ -593,7 +594,8 @@ fn ndarray_copy_impl<'ctx, G: CodeGenerator + ?Sized>(
let len = call_ndarray_calc_size(
generator,
ctx,
&ndarray.dim_sizes().as_slice_value(ctx, generator),
ndarray.load_ndims(ctx),
ndarray.dim_sizes().as_ptr_value(ctx),
);
let sizeof_ty = ctx.get_llvm_type(generator, elem_ty);
let len_bytes = ctx.builder
@ -606,8 +608,8 @@ fn ndarray_copy_impl<'ctx, G: CodeGenerator + ?Sized>(
call_memcpy_generic(
ctx,
ndarray.data().base_ptr(ctx, generator),
this.data().base_ptr(ctx, generator),
ndarray.data().as_ptr_value(ctx),
this.data().as_ptr_value(ctx),
len_bytes,
llvm_i1.const_zero(),
);
@ -634,7 +636,7 @@ pub fn ndarray_elementwise_binop_impl<'ctx, G, ValueFn>(
G: CodeGenerator,
ValueFn: Fn(&mut G, &mut CodeGenContext<'ctx, '_>, Type, (BasicValueEnum<'ctx>, BasicValueEnum<'ctx>)) -> Result<BasicValueEnum<'ctx>, String>,
{
let ndarray_dims = call_ndarray_calc_broadcast(generator, ctx, this, other);
let ndarray_dims = call_ndarray_calc_broadcast_sz(generator, ctx, this, other);
let ndarray = res.unwrap_or_else(|| {
create_ndarray_dyn_shape(
generator,

View File

@ -6,7 +6,7 @@ use super::{
};
use crate::{
codegen::{
classes::{ArrayLikeIndexer, ArraySliceValue, ListValue, RangeValue},
classes::{ArrayLikeIndexer, ListValue, RangeValue},
expr::gen_binop_expr,
gen_in_range_check,
},
@ -65,8 +65,8 @@ pub fn gen_array_var<'ctx, 'a, T: BasicType<'ctx>>(
ctx: &mut CodeGenContext<'ctx, 'a>,
ty: T,
size: IntValue<'ctx>,
name: Option<&'ctx str>,
) -> Result<ArraySliceValue<'ctx>, String> {
name: Option<&str>,
) -> Result<PointerValue<'ctx>, String> {
// Restore debug location
let di_loc = ctx.debug_info.0.create_debug_location(
ctx.ctx,
@ -84,7 +84,6 @@ pub fn gen_array_var<'ctx, 'a, T: BasicType<'ctx>>(
ctx.builder.set_current_debug_location(di_loc);
let ptr = ctx.builder.build_array_alloca(ty, size, name.unwrap_or("")).unwrap();
let ptr = ArraySliceValue::from_ptr_val(ptr, size, name);
ctx.builder.position_at_end(current);
ctx.builder.set_current_debug_location(di_loc);
@ -763,6 +762,125 @@ pub fn gen_if<G: CodeGenerator>(
Ok(())
}
/// Generates an `if` construct using lambdas, similar to the following C code:
///
/// ```c
/// if (cond()) {
/// then();
/// } else {
/// if (orelse) orelse();
/// }
/// ```
///
/// * `cond` - A lambda containing IR statements checking whether the `if` body should be executed.
/// The result value must be an `i1` indicating if the loop should continue.
/// * `then` - A lambda containing IR statements executed when `cond` evaluates to `true`.
/// * `orelse` - A lambda containing IR statements executed when `cond` evaluates to `false`. If set
/// to [`None`], implies that the `else` block does not exist.
pub fn gen_if_callback<'ctx, 'a, G, CondFn, BodyFn>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, 'a>,
cond: CondFn,
then: BodyFn,
orelse: Option<BodyFn>,
) -> Result<(), String>
where
G: CodeGenerator + ?Sized,
CondFn: FnOnce(&mut G, &mut CodeGenContext<'ctx, 'a>) -> Result<IntValue<'ctx>, String>,
BodyFn: FnOnce(&mut G, &mut CodeGenContext<'ctx, 'a>) -> Result<(), String>,
{
let current = ctx.builder.get_insert_block().and_then(BasicBlock::get_parent).unwrap();
let then_bb = ctx.ctx.append_basic_block(current, "if.then");
let else_bb = if orelse.is_some() {
Some(ctx.ctx.append_basic_block(current, "if.else"))
} else {
None
};
let cont_bb = ctx.ctx.append_basic_block(current, "if.end");
let cond_v = cond(generator, ctx)?;
ctx.builder
.build_conditional_branch(generator.bool_to_i1(ctx, cond_v), then_bb, else_bb.unwrap_or(cont_bb))
.unwrap();
ctx.builder.position_at_end(then_bb);
then(generator, ctx)?;
ctx.builder.build_unconditional_branch(cont_bb).unwrap();
if let (Some(orelse), Some(else_bb)) = (orelse, else_bb) {
ctx.builder.position_at_end(else_bb);
orelse(generator, ctx)?;
ctx.builder.build_unconditional_branch(cont_bb).unwrap();
}
ctx.builder.position_at_end(cont_bb);
Ok(())
}
/// Generates an `if` construct with a value using lambdas, similar to the following C code:
///
/// ```c
/// llvm_phi_t res;
/// if (cond()) {
/// res = then();
/// } else {
/// res = orelse();
/// }
/// ```
///
/// The type of both branches must be the same, and must also match `llvm_phi_t`.
///
/// * `llvm_phi_t` - The type of the resultant variable.
/// * `cond` - A lambda containing IR statements checking whether the `if` body should be executed.
/// The result value must be an `i1` indicating if the loop should continue.
/// * `then` - A lambda containing IR statements executed when `cond` evaluates to `true`.
/// * `orelse` - A lambda containing IR statements executed when `cond` evaluates to `false`.
pub fn gen_if_expr_callback<'ctx, 'a, G, R, CondFn, BodyFn>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, 'a>,
llvm_phi_t: BasicTypeEnum<'ctx>,
cond: CondFn,
then: BodyFn,
orelse: BodyFn,
) -> Result<BasicValueEnum<'ctx>, String>
where
G: CodeGenerator + ?Sized,
R: BasicValue<'ctx>,
CondFn: FnOnce(&mut G, &mut CodeGenContext<'ctx, 'a>) -> Result<IntValue<'ctx>, String>,
BodyFn: FnOnce(&mut G, &mut CodeGenContext<'ctx, 'a>) -> Result<R, String>,
{
let current = ctx.builder.get_insert_block().and_then(BasicBlock::get_parent).unwrap();
let then_bb = ctx.ctx.append_basic_block(current, "if.then");
let else_bb = ctx.ctx.append_basic_block(current, "if.else");
let cont_bb = ctx.ctx.append_basic_block(current, "if.end");
let cond_v = cond(generator, ctx)?;
ctx.builder
.build_conditional_branch(generator.bool_to_i1(ctx, cond_v), then_bb, else_bb)
.unwrap();
ctx.builder.position_at_end(then_bb);
let then_val = then(generator, ctx)?;
ctx.builder.build_unconditional_branch(cont_bb).unwrap();
ctx.builder.position_at_end(else_bb);
let else_val = orelse(generator, ctx)?;
ctx.builder.build_unconditional_branch(cont_bb).unwrap();
ctx.builder.position_at_end(cont_bb);
assert_eq!(llvm_phi_t, then_val.as_basic_value_enum().get_type());
assert_eq!(llvm_phi_t, else_val.as_basic_value_enum().get_type());
let phi_val = ctx.builder.build_phi(llvm_phi_t, "").unwrap();
phi_val.add_incoming(&[
(&then_val, then_bb),
(&else_val, else_bb),
]);
Ok(phi_val.as_basic_value())
}
pub fn final_proxy<'ctx>(
ctx: &mut CodeGenContext<'ctx, '_>,
target: BasicBlock<'ctx>,

View File

@ -10,7 +10,7 @@ use crate::{
},
typecheck::{
type_inferencer::{FunctionData, Inferencer, PrimitiveStore},
typedef::{FunSignature, FuncArg, Type, TypeEnum, Unifier, VarMap},
typedef::{FunSignature, FuncArg, Type, TypeEnum, Unifier},
},
};
use indoc::indoc;
@ -25,6 +25,7 @@ use nac3parser::{
use parking_lot::RwLock;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::typecheck::typedef::VarMap;
struct Resolver {
id_to_type: HashMap<StrRef, Type>,

View File

@ -1926,8 +1926,9 @@ impl TopLevelComposer {
ret_str,
name,
ast.as_ref().unwrap().location
),]))
}
),
]))
}
instance_to_stmt.insert(
get_subst_key(unifier, self_type, &subst, Some(&vars.keys().copied().collect())),

View File

@ -45,6 +45,7 @@ pub fn subst_ndarray_tvars(
let tvar_ids = params.iter()
.map(|(obj_id, _)| *obj_id)
.sorted()
.collect_vec();
debug_assert_eq!(tvar_ids.len(), 2);

View File

@ -7,7 +7,7 @@ expression: res_vec
"Class {\nname: \"A\",\nancestors: [\"A[T, V]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[v:V], none]\"), (\"fun\", \"fn[[a:T], V]\")],\ntype_vars: [\"T\", \"V\"]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[v:V], none]\",\nvar_id: [32]\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:T], V]\",\nvar_id: [37]\n}\n",
"Function {\nname: \"gfun\",\nsig: \"fn[[a:A[list[float], int32]], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"gfun\",\nsig: \"fn[[a:A[int32, list[float]]], none]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\"],\nfields: [],\nmethods: [(\"__init__\", \"fn[[], none]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
]

View File

@ -3,11 +3,11 @@ source: nac3core/src/toplevel/test.rs
expression: res_vec
---
[
"Class {\nname: \"A\",\nancestors: [\"A[typevar18, typevar19]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[a:A[float, bool], b:B], none]\"), (\"fun\", \"fn[[a:A[float, bool]], A[bool, int32]]\")],\ntype_vars: [\"typevar18\", \"typevar19\"]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[a:A[float, bool], b:B], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:A[float, bool]], A[bool, int32]]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\", \"A[int64, bool]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:A[float, bool]], A[bool, int32]]\"), (\"foo\", \"fn[[b:B], B]\"), (\"bar\", \"fn[[a:A[list[B], int32]], tuple[A[virtual[A[B, int32]], bool], B]]\")],\ntype_vars: []\n}\n",
"Class {\nname: \"A\",\nancestors: [\"A[typevar18, typevar19]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[a:A[bool, float], b:B], none]\"), (\"fun\", \"fn[[a:A[bool, float]], A[bool, int32]]\")],\ntype_vars: [\"typevar18\", \"typevar19\"]\n}\n",
"Function {\nname: \"A.__init__\",\nsig: \"fn[[a:A[bool, float], b:B], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"A.fun\",\nsig: \"fn[[a:A[bool, float]], A[bool, int32]]\",\nvar_id: []\n}\n",
"Class {\nname: \"B\",\nancestors: [\"B\", \"A[int64, bool]\"],\nfields: [\"a\", \"b\"],\nmethods: [(\"__init__\", \"fn[[], none]\"), (\"fun\", \"fn[[a:A[bool, float]], A[bool, int32]]\"), (\"foo\", \"fn[[b:B], B]\"), (\"bar\", \"fn[[a:A[int32, list[B]]], tuple[A[bool, virtual[A[B, int32]]], B]]\")],\ntype_vars: []\n}\n",
"Function {\nname: \"B.__init__\",\nsig: \"fn[[], none]\",\nvar_id: []\n}\n",
"Function {\nname: \"B.foo\",\nsig: \"fn[[b:B], B]\",\nvar_id: []\n}\n",
"Function {\nname: \"B.bar\",\nsig: \"fn[[a:A[list[B], int32]], tuple[A[virtual[A[B, int32]], bool], B]]\",\nvar_id: []\n}\n",
"Function {\nname: \"B.bar\",\nsig: \"fn[[a:A[int32, list[B]]], tuple[A[bool, virtual[A[B, int32]]], B]]\",\nvar_id: []\n}\n",
]

View File

@ -1,6 +1,5 @@
use crate::symbol_resolver::SymbolValue;
use crate::toplevel::helper::PRIMITIVE_DEF_IDS;
use crate::typecheck::typedef::VarMap;
use super::*;
use nac3parser::ast::Constant;

View File

@ -1,11 +1,10 @@
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::{BTreeMap, HashMap};
use std::fmt::Display;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::{borrow::Cow, collections::HashSet};
use std::iter::zip;
use indexmap::IndexMap;
use itertools::Itertools;
use nac3parser::ast::{Location, StrRef};
@ -26,10 +25,14 @@ pub type Type = UnificationKey;
pub struct CallId(pub(super) usize);
pub type Mapping<K, V = Type> = HashMap<K, V>;
pub type IndexMapping<K, V = Type> = IndexMap<K, V>;
/// The mapping between type variable ID and [unifier type][`Type`].
pub type VarMap = IndexMapping<u32>;
/// A [`Mapping`] sorted by its key.
///
/// This type is recommended for mappings that should be stored and/or iterated by its sorted key.
pub type SortedMapping<K, V = Type> = BTreeMap<K, V>;
/// A [`BTreeMap`] storing the mapping between type variable ID and [unifier type][`Type`].
pub type VarMap = SortedMapping<u32>;
#[derive(Clone)]
pub struct Call {
@ -917,8 +920,8 @@ impl Unifier {
// Sort the type arguments by its UnificationKey first, since `HashMap::iter` visits
// all K-V pairs "in arbitrary order"
let (tv1, tv2) = (
params1.iter().map(|(_, v)| v).collect_vec(),
params2.iter().map(|(_, v)| v).collect_vec(),
params1.iter().sorted_by_key(|(k, _)| *k).map(|(_, v)| v).collect_vec(),
params2.iter().sorted_by_key(|(k, _)| *k).map(|(_, v)| v).collect_vec(),
);
for (x, y) in zip(tv1, tv2) {
if self.unify_impl(*x, *y, false).is_err() {
@ -1278,12 +1281,12 @@ impl Unifier {
fn subst_map<K>(
&mut self,
map: &IndexMapping<K>,
map: &SortedMapping<K>,
mapping: &VarMap,
cache: &mut HashMap<Type, Option<Type>>,
) -> Option<IndexMapping<K>>
where
K: std::hash::Hash + Eq + Clone,
) -> Option<SortedMapping<K>>
where
K: Ord + Eq + Clone,
{
let mut map2 = None;
for (k, v) in map {

View File

@ -45,9 +45,9 @@ impl Unifier {
}
}
fn map_eq<K>(&mut self, map1: &IndexMapping<K>, map2: &IndexMapping<K>) -> bool
where
K: std::hash::Hash + Eq + Clone
fn map_eq<K>(&mut self, map1: &SortedMapping<K>, map2: &SortedMapping<K>) -> bool
where
K: Ord + Eq + Clone,
{
if map1.len() != map2.len() {
return false;