forked from M-Labs/nac3
1
0
Fork 0

Compare commits

..

9 Commits

Author SHA1 Message Date
lyken 87d2a4ed59 WIP 2024-07-10 17:27:10 +08:00
lyken 9aae290727 core: irrt general numpy broadcasting 2024-07-10 17:05:01 +08:00
lyken d18c769cdc core: irrt general numpy slicing 2024-07-10 14:05:08 +08:00
lyken f41f06aec7 core: more irrt 2024-07-10 11:56:31 +08:00
lyken 1303265785 core: build.rs rewrite regex to capture `= type` 2024-07-10 10:17:45 +08:00
lyken e9cf6ce1e5 core: move irrt c++ sources to /nac3core/irrt 2024-07-10 10:17:45 +08:00
lyken bc91ab9b13 core: IRRT -Werror=return-type 2024-07-10 10:17:43 +08:00
lyken 1e06a3d199 core: add irrt_test 2024-07-10 10:11:07 +08:00
lyken 87511ac749 core: comment out numpy 2024-07-10 10:05:07 +08:00
22 changed files with 1013 additions and 2777 deletions

View File

@ -1,31 +0,0 @@
#pragma once
#include "irrt_printer.hpp"
namespace {
#define MAX_ERROR_NAME_LEN 32
// TODO: right now just to report some messages for now
struct ErrorContext {
Printer error;
// TODO: add error_class_name??
void initialize(char* string_base_ptr, uint32_t max_length) {
error.initialize(string_base_ptr, max_length);
}
bool has_error() {
return error.length > 0;
}
};
}
extern "C" {
void __nac3_error_context_init(ErrorContext* ctx, char* string_base_ptr, uint32_t max_length) {
ctx->initialize(string_base_ptr, max_length);
}
uint8_t __nac3_error_context_has_error(ErrorContext* ctx) {
return (uint8_t) ctx->has_error();
}
}

View File

@ -1,12 +1,10 @@
#pragma once #pragma once
#include "irrt_basic.hpp"
#include "irrt_error_context.hpp"
#include "irrt_numpy_ndarray.hpp"
#include "irrt_printer.hpp"
#include "irrt_slice.hpp"
#include "irrt_typedefs.hpp"
#include "irrt_utils.hpp" #include "irrt_utils.hpp"
#include "irrt_typedefs.hpp"
#include "irrt_basic.hpp"
#include "irrt_slice.hpp"
#include "irrt_numpy_ndarray.hpp"
/* /*
All IRRT implementations. All IRRT implementations.

View File

@ -8,6 +8,9 @@
NDArray-related implementations. NDArray-related implementations.
`*/ `*/
// NDArray indices are always `uint32_t`.
using NDIndex = uint32_t;
namespace { namespace {
namespace ndarray_util { namespace ndarray_util {
template <typename SizeT> template <typename SizeT>
@ -102,18 +105,14 @@ namespace {
} }
struct NDSlice { struct NDSlice {
// A poor-man's enum variant type // A poor-man's `std::variant<int, UserRange>`
NDSliceType type; NDSliceType type;
/* /*
if type == INPUT_SLICE_TYPE_INDEX => `slice` points to a single `SizeT` if type == INPUT_SLICE_TYPE_INDEX => `slice` points to a single `SizeT`
if type == INPUT_SLICE_TYPE_SLICE => `slice` points to a single `UserRange<SizeT>` if type == INPUT_SLICE_TYPE_SLICE => `slice` points to a single `UserRange`
`SizeT` is controlled by the caller: `NDSlice` only cares about where that
slice is (the pointer), `NDSlice` does not care/know about the actual `sizeof()`
of the slice value.
*/ */
uint8_t* slice; uint8_t *slice;
}; };
namespace ndarray_util { namespace ndarray_util {
@ -124,36 +123,36 @@ namespace {
SizeT final_ndims = ndims; SizeT final_ndims = ndims;
for (SizeT i = 0; i < num_slices; i++) { for (SizeT i = 0; i < num_slices; i++) {
if (slices[i].type == INPUT_SLICE_TYPE_INDEX) { if (slices[i].type == INPUT_SLICE_TYPE_INDEX) {
final_ndims--; // An index demotes the rank by 1 final_ndims--; // An integer slice demotes the rank by 1
} }
} }
return final_ndims; return final_ndims;
} }
} }
// template <typename SizeT> template <typename SizeT>
// struct NDArrayIndicesIter { struct NDArrayIndicesIter {
// SizeT ndims; SizeT ndims;
// const SizeT *shape; const SizeT *shape;
// SizeT *indices; SizeT *indices;
// void set_indices_zero() { void set_indices_zero() {
// __builtin_memset(indices, 0, sizeof(SizeT) * ndims); __builtin_memset(indices, 0, sizeof(SizeT) * ndims);
// } }
// void next() { void next() {
// for (SizeT i = 0; i < ndims; i++) { for (SizeT i = 0; i < ndims; i++) {
// SizeT dim_i = ndims - i - 1; SizeT dim_i = ndims - i - 1;
// indices[dim_i]++; indices[dim_i]++;
// if (indices[dim_i] < shape[dim_i]) { if (indices[dim_i] < shape[dim_i]) {
// break; break;
// } else { } else {
// indices[dim_i] = 0; indices[dim_i] = 0;
// } }
// } }
// } }
// }; };
// The NDArray object. `SizeT` is the *signed* size type of this ndarray. // The NDArray object. `SizeT` is the *signed* size type of this ndarray.
// //
@ -173,8 +172,6 @@ namespace {
// NOTE: Formally this should be of type `void *`, but clang // NOTE: Formally this should be of type `void *`, but clang
// translates `void *` to `i8 *` when run with `-S -emit-llvm`, // translates `void *` to `i8 *` when run with `-S -emit-llvm`,
// so we will put `uint8_t *` here for clarity. // so we will put `uint8_t *` here for clarity.
//
// This pointer should point to the first element of the ndarray directly
uint8_t *data; uint8_t *data;
// The number of bytes of a single element in `data`. // The number of bytes of a single element in `data`.
@ -215,11 +212,11 @@ namespace {
return this->size() * itemsize; return this->size() * itemsize;
} }
void set_pelement_value(uint8_t* pelement, const uint8_t* pvalue) { void set_value_at_pelement(uint8_t* pelement, const uint8_t* pvalue) {
__builtin_memcpy(pelement, pvalue, itemsize); __builtin_memcpy(pelement, pvalue, itemsize);
} }
uint8_t* get_pelement_by_indices(const SizeT *indices) { uint8_t* get_pelement(const SizeT *indices) {
uint8_t* element = data; uint8_t* element = data;
for (SizeT dim_i = 0; dim_i < ndims; dim_i++) for (SizeT dim_i = 0; dim_i < ndims; dim_i++)
element += indices[dim_i] * strides[dim_i]; element += indices[dim_i] * strides[dim_i];
@ -232,7 +229,7 @@ namespace {
SizeT* indices = (SizeT*) __builtin_alloca(sizeof(SizeT) * this->ndims); SizeT* indices = (SizeT*) __builtin_alloca(sizeof(SizeT) * this->ndims);
ndarray_util::set_indices_by_nth(this->ndims, this->shape, indices, nth); ndarray_util::set_indices_by_nth(this->ndims, this->shape, indices, nth);
return get_pelement_by_indices(indices); return get_pelement(indices);
} }
// Get pointer to the first element of this ndarray, assuming // Get pointer to the first element of this ndarray, assuming
@ -255,10 +252,15 @@ namespace {
// Fill the ndarray with a value // Fill the ndarray with a value
void fill_generic(const uint8_t* pvalue) { void fill_generic(const uint8_t* pvalue) {
const SizeT size = this->size(); NDArrayIndicesIter<SizeT> iter;
for (SizeT i = 0; i < size; i++) { iter.ndims = this->ndims;
uint8_t* pelement = get_nth_pelement(i); iter.shape = this->shape;
set_pelement_value(pelement, pvalue); iter.indices = (SizeT*) __builtin_alloca(sizeof(SizeT) * ndims);
iter.set_indices_zero();
for (SizeT i = 0; i < this->size(); i++, iter.next()) {
uint8_t* pelement = get_pelement(iter.indices);
set_value_at_pelement(pelement, pvalue);
} }
} }
@ -281,18 +283,12 @@ namespace {
if (!in_bounds(indices)) continue; if (!in_bounds(indices)) continue;
uint8_t* pelement = get_pelement_by_indices(indices); uint8_t* pelement = get_pelement(indices);
set_pelement_value(pelement, one_pvalue); set_value_at_pelement(pelement, one_pvalue);
} }
} }
// To support numpy "basic indexing" https://numpy.org/doc/stable/user/basics.indexing.html#basic-indexing // To support numpy complex slices (e.g., `my_array[:50:2,4,:2:-1]`)
// "Advanced indexing" https://numpy.org/doc/stable/user/basics.indexing.html#advanced-indexing is not supported
//
// This function supports:
// - "scalar indexing",
// - "slicing and strides",
// - and "dimensional indexing tools" (TODO, but this is really easy to implement).
// //
// Things assumed by this function: // Things assumed by this function:
// - `dst_ndarray` is allocated by the caller // - `dst_ndarray` is allocated by the caller
@ -303,14 +299,13 @@ namespace {
// - `dst_ndarray->data` does not have to be set, it will be derived. // - `dst_ndarray->data` does not have to be set, it will be derived.
// - `dst_ndarray->itemsize` does not have to be set, it will be set to `this->itemsize` // - `dst_ndarray->itemsize` does not have to be set, it will be set to `this->itemsize`
// - `dst_ndarray->shape` and `dst_ndarray.strides` can contain empty values // - `dst_ndarray->shape` and `dst_ndarray.strides` can contain empty values
void subscript(SizeT num_ndslices, NDSlice* ndslices, NDArray<SizeT>* dst_ndarray) { void slice(SizeT num_ndslices, NDSlice* ndslices, NDArray<SizeT>* dst_ndarray) {
// REFERENCE CODE (check out `_index_helper` in `__getitem__`): // REFERENCE CODE (check out `_index_helper` in `__getitem__`):
// https://github.com/wadetb/tinynumpy/blob/0d23d22e07062ffab2afa287374c7b366eebdda1/tinynumpy/tinynumpy.py#L652 // https://github.com/wadetb/tinynumpy/blob/0d23d22e07062ffab2afa287374c7b366eebdda1/tinynumpy/tinynumpy.py#L652
irrt_assert(dst_ndarray->ndims == ndarray_util::deduce_ndims_after_slicing(this->ndims, num_ndslices, ndslices)); irrt_assert(dst_ndarray->ndims == ndarray_util::deduce_ndims_after_slicing(this->ndims, num_ndslices, ndslices));
dst_ndarray->data = this->data; dst_ndarray->data = this->data;
dst_ndarray->itemsize = this->itemsize;
SizeT this_axis = 0; SizeT this_axis = 0;
SizeT dst_axis = 0; SizeT dst_axis = 0;
@ -331,15 +326,15 @@ namespace {
// Handle when the ndslice is a slice (represented by UserSlice in IRRT) // Handle when the ndslice is a slice (represented by UserSlice in IRRT)
// e.g., `my_array[::2, -5, ::-1]` // e.g., `my_array[::2, -5, ::-1]`
// ^^^------^^^^----- like these // ^^^------^^^^----- like these
UserSlice* user_slice = (UserSlice*) ndslice->slice; UserSlice<SizeT>* user_slice = (UserSlice<SizeT>*) ndslice->slice;
Slice slice = user_slice->indices(this->shape[this_axis]); // To resolve negative indices and other funny stuff written by the user Slice<SizeT> slice = user_slice->indices(this->shape[this_axis]); // To resolve negative indices and other funny stuff written by the user
// NOTE: There is no need to write special code to handle negative steps/strides. // NOTE: There is no need to write special code to handle negative steps/strides.
// This simple implementation meticulously handles both positive and negative steps/strides. // This simple implementation meticulously handles both positive and negative steps/strides.
// Check out the tinynumpy and IRRT's test cases if you are not convinced. // Check out the tinynumpy and IRRT's test cases if you are not convinced.
dst_ndarray->data += (SizeT) slice.start * this->strides[this_axis]; // Add offset (NOTE: no need to `* itemsize`, strides count in # of bytes) dst_ndarray->data += slice.start * this->strides[this_axis]; // Add offset (NOTE: no need to `* itemsize`, strides count in # of bytes)
dst_ndarray->strides[dst_axis] = ((SizeT) slice.step) * this->strides[this_axis]; // Determine stride dst_ndarray->strides[dst_axis] = slice.step * this->strides[this_axis]; // Determine stride
dst_ndarray->shape[dst_axis] = (SizeT) slice.len(); // Determine shape dimension dst_ndarray->shape[dst_axis] = slice.len(); // Determine shape dimension
// Next // Next
dst_axis++; dst_axis++;
@ -349,18 +344,7 @@ namespace {
} }
} }
/* irrt_assert(dst_axis == dst_ndarray->ndims); // Sanity check on the implementation
Reference python code:
```python
dst_ndarray.shape.extend(this.shape[this_axis:])
dst_ndarray.strides.extend(this.strides[this_axis:])
```
*/
for (; dst_axis < dst_ndarray->ndims; dst_axis++, this_axis++) {
dst_ndarray->shape[dst_axis] = this->shape[this_axis];
dst_ndarray->strides[dst_axis] = this->strides[this_axis];
}
} }
// Similar to `np.broadcast_to(<ndarray>, <target_shape>)` // Similar to `np.broadcast_to(<ndarray>, <target_shape>)`
@ -442,30 +426,20 @@ namespace {
}; };
src_ndarray->broadcast_to(&broadcasted_src_ndarray); src_ndarray->broadcast_to(&broadcasted_src_ndarray);
const SizeT size = this->size(); // Using iter instead of `get_nth_pelement` because it is slightly faster
for (SizeT i = 0; i < size; i++) { SizeT* indices = __builtin_alloca(sizeof(SizeT) * this->ndims);
uint8_t* src_pelement = broadcasted_src_ndarray_strides->get_nth_pelement(i); auto iter = NDArrayIndicesIter<SizeT> {
uint8_t* this_pelement = this->get_nth_pelement(i); .ndims = this->ndims,
this->set_pelement_value(this_pelement, src_pelement); .shape = this->shape,
.indices = indices
};
const SizeT this_size = this->size();
for (SizeT i = 0; i < this_size; i++, iter.next()) {
uint8_t* src_pelement = broadcasted_src_ndarray_strides->get_pelement(indices);
uint8_t* this_pelement = this->get_pelement(indices);
this->set_value_at_pelement(src_pelement, src_pelement);
} }
} }
// TODO: DOCUMENT ME
bool is_unsized() {
return this->ndims == 0;
}
// Simulate `len(<ndarray>)`
// See (it doesn't help): https://numpy.org/doc/stable/reference/generated/numpy.ndarray.__len__.html#numpy.ndarray.__len__
SliceIndex len() {
// If you do `len(np.asarray(42))` (note that its `.shape` is just `()` - an empty tuple),
// numpy throws a `TypeError: len() of unsized object`
irrt_assert(!this->is_unsized());
// Apparently `len(<ndarray>)` is defined to be the first dimension
// REFERENCE: https://stackoverflow.com/questions/43081809/len-of-a-numpy-array-in-python
return (SliceIndex) this->shape[0];
}
}; };
} }
@ -478,14 +452,6 @@ extern "C" {
return ndarray->size(); return ndarray->size();
} }
void __nac3_ndarray_set_strides_by_shape(NDArray<int32_t>* ndarray) {
ndarray->set_strides_by_shape();
}
void __nac3_ndarray_set_strides_by_shape64(NDArray<int64_t>* ndarray) {
ndarray->set_strides_by_shape();
}
void __nac3_ndarray_fill_generic(NDArray<int32_t>* ndarray, uint8_t* pvalue) { void __nac3_ndarray_fill_generic(NDArray<int32_t>* ndarray, uint8_t* pvalue) {
ndarray->fill_generic(pvalue); ndarray->fill_generic(pvalue);
} }
@ -494,27 +460,7 @@ extern "C" {
ndarray->fill_generic(pvalue); ndarray->fill_generic(pvalue);
} }
int32_t __nac3_ndarray_deduce_ndims_after_slicing(int32_t ndims, int32_t num_slices, const NDSlice* slices) { // void __nac3_ndarray_slice(NDArray<int32_t>* ndarray, int32_t num_slices, NDSlice<int32_t> *slices, NDArray<int32_t> *dst_ndarray) {
return ndarray_util::deduce_ndims_after_slicing(ndims, num_slices, slices); // // ndarray->slice(num_slices, slices, dst_ndarray);
} // }
int64_t __nac3_ndarray_deduce_ndims_after_slicing64(int64_t ndims, int64_t num_slices, const NDSlice* slices) {
return ndarray_util::deduce_ndims_after_slicing(ndims, num_slices, slices);
}
void __nac3_ndarray_subscript(NDArray<int32_t>* ndarray, int32_t num_slices, NDSlice* slices, NDArray<int32_t> *dst_ndarray) {
ndarray->subscript(num_slices, slices, dst_ndarray);
}
void __nac3_ndarray_subscript64(NDArray<int64_t>* ndarray, int32_t num_slices, NDSlice* slices, NDArray<int64_t> *dst_ndarray) {
ndarray->subscript(num_slices, slices, dst_ndarray);
}
SliceIndex __nac3_ndarray_len(NDArray<int32_t>* ndarray) {
return ndarray->len();
}
SliceIndex __nac3_ndarray_len64(NDArray<int64_t>* ndarray) {
return ndarray->len();
}
} }

View File

@ -1,82 +0,0 @@
#pragma once
#include "irrt_typedefs.hpp"
// TODO: obviously implementing printf from scratch is bad,
// is there a header only, no-cstdlib library for this?
namespace {
struct Printer {
char* string_base_ptr;
uint32_t max_length;
uint32_t length; // NOTE: this could be incremented past max_length, which indicates
void initialize(char *string_base_ptr, uint32_t max_length) {
this->string_base_ptr = string_base_ptr;
this->max_length = max_length;
this->length = 0;
}
void put_space() {
put_char(' ');
}
void put_char(char ch) {
push_char(ch);
}
void put_string(const char* string) {
// TODO: optimize?
while (*string != '\0') {
push_char(*string);
string++; // Move to next char
}
}
template<typename T>
void put_int(T value) {
// NOTE: Try not to use recursion to print the digits
// value == 0 is a special case
if (value == 0) {
push_char('0');
} else {
// Add a '-' if the value is negative
if (value < 0) {
push_char('-');
value = -value; // Negate then continue to print the digits
}
// TODO: Recursion is a bad idea on embedded systems?
uint32_t num_digits = int_log_floor(value, 10) + 1;
put_int_helper(num_digits, value);
}
}
// TODO: implement put_float() and more would be useful
private:
void push_char(char ch) {
if (length < max_length) {
string_base_ptr[length] = ch;
}
// NOTE: this could increment past max_length,
// to indicate the true length of the message even if it gets cut off
length++;
}
template <typename T>
void put_int_helper(uint32_t num_digits, T value) {
// Print the digits recursively
__builtin_assume(0 <= value);
if (num_digits > 0) {
put_int_helper(num_digits - 1, value / 10);
uint32_t digit = value % 10;
char digit_char = '0' + (char) digit;
put_char(digit_char);
}
}
};
}

View File

@ -4,15 +4,19 @@
#include "irrt_typedefs.hpp" #include "irrt_typedefs.hpp"
namespace { namespace {
// A proper slice in IRRT, all negative indices have be resolved to absolute values.
// Even though nac3core's slices are always `int32_t`, we will template slice anyway
// since this struct is used as a general utility.
template <typename T>
struct Slice { struct Slice {
SliceIndex start; T start;
SliceIndex stop; T stop;
SliceIndex step; T step;
// The length/The number of elements of the slice if it were a range, // The length/The number of elements of the slice if it were a range,
// i.e., the value of `len(range(this->start, this->stop, this->end))` // i.e., the value of `len(range(this->start, this->stop, this->end))`
SliceIndex len() { T len() {
SliceIndex diff = stop - start; T diff = stop - start;
if (diff > 0 && step > 0) { if (diff > 0 && step > 0) {
return ((diff - 1) / step) + 1; return ((diff - 1) / step) + 1;
} else if (diff < 0 && step < 0) { } else if (diff < 0 && step < 0) {
@ -23,45 +27,38 @@ namespace {
} }
}; };
SliceIndex resolve_index_in_length(SliceIndex length, SliceIndex index) { template<typename T>
T resolve_index_in_length(T length, T index) {
irrt_assert(length >= 0); irrt_assert(length >= 0);
if (index < 0) { if (index < 0) {
// Remember that index is negative, so do a plus here // Remember that index is negative, so do a plus here
return max<SliceIndex>(length + index, 0); return max(length + index, 0);
} else { } else {
return min<SliceIndex>(length, index); return min(length, index);
} }
} }
// A user-written Python-like slice.
//
// i.e., this slice is a triple of either an int or nothing. (e.g., `my_array[:10:2]`, `start` is None)
//
// You can "resolve" a `UserSlice` by using `UserSlice::indices(<length>)`
//
// NOTE: using a bitfield for the `*_defined` is better, at the // NOTE: using a bitfield for the `*_defined` is better, at the
// cost of a more annoying implementation in nac3core inkwell // cost of a more annoying implementation in nac3core inkwell
template <typename T>
struct UserSlice { struct UserSlice {
// Did the user specify `start`? If 0, `start` is undefined (and contains an empty value)
uint8_t start_defined; uint8_t start_defined;
SliceIndex start; T start;
// Similar to `start_defined`
uint8_t stop_defined; uint8_t stop_defined;
SliceIndex stop; T stop;
// Similar to `start_defined`
uint8_t step_defined; uint8_t step_defined;
SliceIndex step; T step;
// Like Python's `slice(start, stop, step).indices(length)` // Like Python's `slice(start, stop, step).indices(length)`
Slice indices(SliceIndex length) { Slice<T> indices(T length) {
// NOTE: This function implements Python's `slice.indices` *FAITHFULLY*. // NOTE: This function implements Python's `slice.indices` *FAITHFULLY*.
// SEE: https://github.com/python/cpython/blob/f62161837e68c1c77961435f1b954412dd5c2b65/Objects/sliceobject.c#L546 // SEE: https://github.com/python/cpython/blob/f62161837e68c1c77961435f1b954412dd5c2b65/Objects/sliceobject.c#L546
irrt_assert(length >= 0); irrt_assert(length >= 0);
irrt_assert(!step_defined || step != 0); // step_defined -> step != 0; step cannot be zero if specified by user irrt_assert(!step_defined || step != 0); // step_defined -> step != 0; step cannot be zero if specified by user
Slice result; Slice<T> result;
result.step = step_defined ? step : 1; result.step = step_defined ? step : 1;
bool step_is_negative = result.step < 0; bool step_is_negative = result.step < 0;

View File

@ -81,7 +81,7 @@ void __print_ndarray_aux(const char *format, bool first, bool last, SizeT* curso
SizeT* indices = (SizeT*) __builtin_alloca(sizeof(SizeT) * ndarray->ndims); SizeT* indices = (SizeT*) __builtin_alloca(sizeof(SizeT) * ndarray->ndims);
for (SizeT i = 0; i < dim; i++) { for (SizeT i = 0; i < dim; i++) {
ndarray_util::set_indices_by_nth(ndarray->ndims, ndarray->shape, indices, *cursor); ndarray_util::set_indices_by_nth(ndarray->ndims, ndarray->shape, indices, *cursor);
ElementT* pelement = (ElementT*) ndarray->get_pelement_by_indices(indices); ElementT* pelement = (ElementT*) ndarray->get_pelement(indices);
ElementT element = *pelement; ElementT element = *pelement;
if (i != 0) printf(", "); // List delimiter if (i != 0) printf(", "); // List delimiter
@ -158,34 +158,34 @@ void test_set_strides_by_shape() {
assert_arrays_match("strides", "%u", 4u, expected_strides, strides); assert_arrays_match("strides", "%u", 4u, expected_strides, strides);
} }
// void test_ndarray_indices_iter_normal() { void test_ndarray_indices_iter_normal() {
// // Test NDArrayIndicesIter normal behavior // Test NDArrayIndicesIter normal behavior
// BEGIN_TEST(); BEGIN_TEST();
//
// int32_t shape[3] = { 1, 2, 3 }; int32_t shape[3] = { 1, 2, 3 };
// int32_t indices[3] = { 0, 0, 0 }; int32_t indices[3] = { 0, 0, 0 };
// auto iter = NDArrayIndicesIter<int32_t> { auto iter = NDArrayIndicesIter<int32_t> {
// .ndims = 3, .ndims = 3,
// .shape = shape, .shape = shape,
// .indices = indices .indices = indices
// }; };
//
// assert_arrays_match("indices #0", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 0 }); assert_arrays_match("indices #0", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 0 });
// iter.next(); iter.next();
// assert_arrays_match("indices #1", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 1 }); assert_arrays_match("indices #1", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 1 });
// iter.next(); iter.next();
// assert_arrays_match("indices #2", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 2 }); assert_arrays_match("indices #2", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 2 });
// iter.next(); iter.next();
// assert_arrays_match("indices #3", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 0 }); assert_arrays_match("indices #3", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 0 });
// iter.next(); iter.next();
// assert_arrays_match("indices #4", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 1 }); assert_arrays_match("indices #4", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 1 });
// iter.next(); iter.next();
// assert_arrays_match("indices #5", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 2 }); assert_arrays_match("indices #5", "%u", 3u, iter.indices, (int32_t[3]) { 0, 1, 2 });
// iter.next(); iter.next();
// assert_arrays_match("indices #6", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 0 }); // Loops back assert_arrays_match("indices #6", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 0 }); // Loops back
// iter.next(); iter.next();
// assert_arrays_match("indices #7", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 1 }); assert_arrays_match("indices #7", "%u", 3u, iter.indices, (int32_t[3]) { 0, 0, 1 });
// } }
void test_ndarray_fill_generic() { void test_ndarray_fill_generic() {
// Test ndarray fill_generic // Test ndarray fill_generic
@ -248,10 +248,10 @@ void test_ndarray_set_to_eye() {
} }
void test_slice_1() { void test_slice_1() {
// Test `subscript(5, None, None).indices(100) == subscript(5, 100, 1)` // Test `slice(5, None, None).indices(100) == slice(5, 100, 1)`
BEGIN_TEST(); BEGIN_TEST();
UserSlice user_slice = { UserSlice<int> user_slice = {
.start_defined = 1, .start_defined = 1,
.start = 5, .start = 5,
.stop_defined = 0, .stop_defined = 0,
@ -265,10 +265,10 @@ void test_slice_1() {
} }
void test_slice_2() { void test_slice_2() {
// Test `subscript(400, 999, None).indices(100) == subscript(100, 100, 1)` // Test `slice(400, 999, None).indices(100) == slice(100, 100, 1)`
BEGIN_TEST(); BEGIN_TEST();
UserSlice user_slice = { UserSlice<int> user_slice = {
.start_defined = 1, .start_defined = 1,
.start = 400, .start = 400,
.stop_defined = 0, .stop_defined = 0,
@ -282,10 +282,10 @@ void test_slice_2() {
} }
void test_slice_3() { void test_slice_3() {
// Test `subscript(-10, -5, None).indices(100) == subscript(90, 95, 1)` // Test `slice(-10, -5, None).indices(100) == slice(90, 95, 1)`
BEGIN_TEST(); BEGIN_TEST();
UserSlice user_slice = { UserSlice<int> user_slice = {
.start_defined = 1, .start_defined = 1,
.start = -10, .start = -10,
.stop_defined = 1, .stop_defined = 1,
@ -300,10 +300,10 @@ void test_slice_3() {
} }
void test_slice_4() { void test_slice_4() {
// Test `subscript(None, None, -5).indices(100) == (99, -1, -5)` // Test `slice(None, None, -5).indices(100) == (99, -1, -5)`
BEGIN_TEST(); BEGIN_TEST();
UserSlice user_slice = { UserSlice<int> user_slice = {
.start_defined = 0, .start_defined = 0,
.stop_defined = 0, .stop_defined = 0,
.step_defined = 1, .step_defined = 1,
@ -366,14 +366,14 @@ void test_ndslice_1() {
}; };
// Create the slice in `ndarray[-2::, 1::2]` // Create the slice in `ndarray[-2::, 1::2]`
UserSlice user_slice_1 = { UserSlice<int32_t> user_slice_1 = {
.start_defined = 1, .start_defined = 1,
.start = -2, .start = -2,
.stop_defined = 0, .stop_defined = 0,
.step_defined = 0 .step_defined = 0
}; };
UserSlice user_slice_2 = { UserSlice<int32_t> user_slice_2 = {
.start_defined = 1, .start_defined = 1,
.start = 1, .start = 1,
.stop_defined = 0, .stop_defined = 0,
@ -387,17 +387,17 @@ void test_ndslice_1() {
{ .type = INPUT_SLICE_TYPE_SLICE, .slice = (uint8_t*) &user_slice_2 } { .type = INPUT_SLICE_TYPE_SLICE, .slice = (uint8_t*) &user_slice_2 }
}; };
ndarray.subscript(num_ndslices, ndslices, &dst_ndarray); ndarray.slice(num_ndslices, ndslices, &dst_ndarray);
int32_t expected_shape[dst_ndims] = { 2, 2 }; int32_t expected_shape[dst_ndims] = { 2, 2 };
int32_t expected_strides[dst_ndims] = { 32, 16 }; int32_t expected_strides[dst_ndims] = { 32, 16 };
assert_arrays_match("shape", "%d", dst_ndims, expected_shape, dst_ndarray.shape); assert_arrays_match("shape", "%d", dst_ndims, expected_shape, dst_ndarray.shape);
assert_arrays_match("strides", "%d", dst_ndims, expected_strides, dst_ndarray.strides); assert_arrays_match("strides", "%d", dst_ndims, expected_strides, dst_ndarray.strides);
assert_values_match("dst_ndarray[0, 0]", "%f", 5.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 0, 0 }))); assert_values_match("dst_ndarray[0, 0]", "%f", 5.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 0, 0 })));
assert_values_match("dst_ndarray[0, 1]", "%f", 7.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 0, 1 }))); assert_values_match("dst_ndarray[0, 1]", "%f", 7.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 0, 1 })));
assert_values_match("dst_ndarray[1, 0]", "%f", 9.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 1, 0 }))); assert_values_match("dst_ndarray[1, 0]", "%f", 9.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 1, 0 })));
assert_values_match("dst_ndarray[1, 1]", "%f", 11.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 1, 1 }))); assert_values_match("dst_ndarray[1, 1]", "%f", 11.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 1, 1 })));
} }
void test_ndslice_2() { void test_ndslice_2() {
@ -450,7 +450,7 @@ void test_ndslice_2() {
// Create the slice in `ndarray[2, ::-2]` // Create the slice in `ndarray[2, ::-2]`
int32_t user_slice_1 = 2; int32_t user_slice_1 = 2;
UserSlice user_slice_2 = { UserSlice<int32_t> user_slice_2 = {
.start_defined = 0, .start_defined = 0,
.stop_defined = 0, .stop_defined = 0,
.step_defined = 1, .step_defined = 1,
@ -463,7 +463,7 @@ void test_ndslice_2() {
{ .type = INPUT_SLICE_TYPE_SLICE, .slice = (uint8_t*) &user_slice_2 } { .type = INPUT_SLICE_TYPE_SLICE, .slice = (uint8_t*) &user_slice_2 }
}; };
ndarray.subscript(num_ndslices, ndslices, &dst_ndarray); ndarray.slice(num_ndslices, ndslices, &dst_ndarray);
int32_t expected_shape[dst_ndims] = { 2 }; int32_t expected_shape[dst_ndims] = { 2 };
int32_t expected_strides[dst_ndims] = { -16 }; int32_t expected_strides[dst_ndims] = { -16 };
@ -471,52 +471,8 @@ void test_ndslice_2() {
assert_arrays_match("strides", "%d", dst_ndims, expected_strides, dst_ndarray.strides); assert_arrays_match("strides", "%d", dst_ndims, expected_strides, dst_ndarray.strides);
// [5.0, 3.0] // [5.0, 3.0]
assert_values_match("dst_ndarray[0]", "%f", 11.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 0 }))); assert_values_match("dst_ndarray[0]", "%f", 11.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 0 })));
assert_values_match("dst_ndarray[1]", "%f", 9.0, *((double *) dst_ndarray.get_pelement_by_indices((int32_t[dst_ndims]) { 1 }))); assert_values_match("dst_ndarray[1]", "%f", 9.0, *((double *) dst_ndarray.get_pelement((int32_t[dst_ndims]) { 1 })));
}
void test_ndslice_3() {
BEGIN_TEST();
double in_data[12] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
const int32_t in_itemsize = sizeof(double);
const int32_t in_ndims = 2;
int32_t in_shape[in_ndims] = { 3, 4 };
int32_t in_strides[in_ndims] = {};
NDArray<int32_t> ndarray = {
.data = (uint8_t*) in_data,
.itemsize = in_itemsize,
.ndims = in_ndims,
.shape = in_shape,
.strides = in_strides
};
ndarray.set_strides_by_shape();
const int32_t dst_ndims = 2;
int32_t dst_shape[dst_ndims] = {999, 999}; // Empty values
int32_t dst_strides[dst_ndims] = {999, 999}; // Empty values
NDArray<int32_t> dst_ndarray = {
.data = nullptr,
.ndims = dst_ndims,
.shape = dst_shape,
.strides = dst_strides
};
// Create the slice in `ndarray[2:3]`
UserSlice user_slice_1 = {
.start_defined = 1,
.start = 2,
.stop_defined = 1,
.stop = 3,
.step_defined = 0,
};
const int32_t num_ndslices = 1;
NDSlice ndslices[num_ndslices] = {
{ .type = INPUT_SLICE_TYPE_SLICE, .slice = (uint8_t*) &user_slice_1 },
};
ndarray.subscript(num_ndslices, ndslices, &dst_ndarray);
} }
void test_can_broadcast_shape() { void test_can_broadcast_shape() {
@ -620,21 +576,19 @@ void test_can_broadcast_shape() {
void test_ndarray_broadcast_1() { void test_ndarray_broadcast_1() {
/* /*
```python # array = np.array([[19.9, 29.9, 39.9, 49.9]], dtype=np.float64)
array = np.array([[19.9, 29.9, 39.9, 49.9]], dtype=np.float64) # >>> [[19.9 29.9 39.9 49.9]]
>>> [[19.9 29.9 39.9 49.9]] #
# array = np.broadcast_to(array, (2, 3, 4))
array = np.broadcast_to(array, (2, 3, 4)) # >>> [[[19.9 29.9 39.9 49.9]
>>> [[[19.9 29.9 39.9 49.9] # >>> [19.9 29.9 39.9 49.9]
>>> [19.9 29.9 39.9 49.9] # >>> [19.9 29.9 39.9 49.9]]
>>> [19.9 29.9 39.9 49.9]] # >>> [[19.9 29.9 39.9 49.9]
>>> [[19.9 29.9 39.9 49.9] # >>> [19.9 29.9 39.9 49.9]
>>> [19.9 29.9 39.9 49.9] # >>> [19.9 29.9 39.9 49.9]]]
>>> [19.9 29.9 39.9 49.9]]] #
# assery array.strides == (0, 0, 8)
assert array.strides == (0, 0, 8)
# and then pick some values in `array` and check them...
```
*/ */
BEGIN_TEST(); BEGIN_TEST();
@ -664,33 +618,31 @@ void test_ndarray_broadcast_1() {
assert_arrays_match("dst_ndarray->strides", "%d", dst_ndims, (int32_t[]) { 0, 0, 8 }, dst_ndarray.strides); assert_arrays_match("dst_ndarray->strides", "%d", dst_ndims, (int32_t[]) { 0, 0, 8 }, dst_ndarray.strides);
assert_values_match("dst_ndarray[0, 0, 0]", "%f", 19.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 0, 0}))); assert_values_match("dst_ndarray[0, 0, 0]", "%f", 19.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 0, 0})));
assert_values_match("dst_ndarray[0, 0, 1]", "%f", 29.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 0, 1}))); assert_values_match("dst_ndarray[0, 0, 1]", "%f", 29.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 0, 1})));
assert_values_match("dst_ndarray[0, 0, 2]", "%f", 39.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 0, 2}))); assert_values_match("dst_ndarray[0, 0, 2]", "%f", 39.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 0, 2})));
assert_values_match("dst_ndarray[0, 0, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 0, 3}))); assert_values_match("dst_ndarray[0, 0, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 0, 3})));
assert_values_match("dst_ndarray[0, 1, 0]", "%f", 19.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 1, 0}))); assert_values_match("dst_ndarray[0, 1, 0]", "%f", 19.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 1, 0})));
assert_values_match("dst_ndarray[0, 1, 1]", "%f", 29.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 1, 1}))); assert_values_match("dst_ndarray[0, 1, 1]", "%f", 29.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 1, 1})));
assert_values_match("dst_ndarray[0, 1, 2]", "%f", 39.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 1, 2}))); assert_values_match("dst_ndarray[0, 1, 2]", "%f", 39.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 1, 2})));
assert_values_match("dst_ndarray[0, 1, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {0, 1, 3}))); assert_values_match("dst_ndarray[0, 1, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {0, 1, 3})));
assert_values_match("dst_ndarray[1, 2, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement_by_indices((int32_t[]) {1, 2, 3}))); assert_values_match("dst_ndarray[1, 2, 3]", "%f", 49.9, *((double*) dst_ndarray.get_pelement((int32_t[]) {1, 2, 3})));
} }
void test_printer() { void test_assign_with() {
const uint32_t buffer_len = 256; /*
char buffer[buffer_len]; ```
Printer printer = { xs = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], dtype=np.float64)
.string_base_ptr = buffer, ys = xs.shape
.max_length = buffer_len, ```
.length = 0 */
};
} }
int main() { int main() {
test_calc_size_from_shape_normal(); test_calc_size_from_shape_normal();
test_calc_size_from_shape_has_zero(); test_calc_size_from_shape_has_zero();
test_set_strides_by_shape(); test_set_strides_by_shape();
// test_ndarray_indices_iter_normal(); test_ndarray_indices_iter_normal();
test_ndarray_fill_generic(); test_ndarray_fill_generic();
test_ndarray_set_to_eye(); test_ndarray_set_to_eye();
test_slice_1(); test_slice_1();
@ -699,9 +651,8 @@ int main() {
test_slice_4(); test_slice_4();
test_ndslice_1(); test_ndslice_1();
test_ndslice_2(); test_ndslice_2();
test_ndslice_3();
test_can_broadcast_shape(); test_can_broadcast_shape();
test_ndarray_broadcast_1(); test_ndarray_broadcast_1();
test_printer(); test_assign_with();
return 0; return 0;
} }

View File

@ -21,43 +21,6 @@ namespace {
return true; return true;
} }
template<typename T>
uint32_t int_log_floor(T value, T base) {
uint32_t result = 0;
while (value < base) {
result++;
value /= base;
}
return result;
}
bool string_is_empty(const char *str) {
return str[0] == '\0';
}
// TODO: DOCUMENT ME!!!!!
// returns false if `src_str` could not be fully copied over to `dst_str`
bool string_copy(uint32_t dst_max_size, char* dst_str, const char* src_str) {
// This function guarantess that `dst_str` will be null-terminated,
for (uint32_t i = 0; i < dst_max_size; i++) {
bool is_last = i + 1 == dst_max_size;
if (is_last && src_str[i] != '\0') {
dst_str[i] = '\0';
return false;
}
if (src_str[i] == '\0') {
dst_str[i] = '\0';
return true;
}
dst_str[i] = src_str[i];
}
__builtin_unreachable();
}
void irrt_panic() { void irrt_panic() {
// Crash the program for now. // Crash the program for now.
// TODO: Don't crash the program // TODO: Don't crash the program

View File

@ -702,54 +702,53 @@ pub fn call_numpy_min<'ctx, G: CodeGenerator + ?Sized>(
BasicValueEnum::PointerValue(n) BasicValueEnum::PointerValue(n)
if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) => if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) =>
{ {
todo!() let (elem_ty, _) = unpack_ndarray_var_tys(&mut ctx.unifier, a_ty);
// let (elem_ty, _) = unpack_ndarray_var_tys(&mut ctx.unifier, a_ty); let llvm_ndarray_ty = ctx.get_llvm_type(generator, elem_ty);
// let llvm_ndarray_ty = ctx.get_llvm_type(generator, elem_ty);
// let n = NDArrayValue::from_ptr_val(n, llvm_usize, None); let n = NDArrayValue::from_ptr_val(n, llvm_usize, None);
// let n_sz = irrt::call_ndarray_calc_size(generator, ctx, &n.dim_sizes(), (None, None)); let n_sz = irrt::call_ndarray_calc_size(generator, ctx, &n.dim_sizes(), (None, None));
// if ctx.registry.llvm_options.opt_level == OptimizationLevel::None { if ctx.registry.llvm_options.opt_level == OptimizationLevel::None {
// let n_sz_eqz = ctx let n_sz_eqz = ctx
// .builder .builder
// .build_int_compare(IntPredicate::NE, n_sz, n_sz.get_type().const_zero(), "") .build_int_compare(IntPredicate::NE, n_sz, n_sz.get_type().const_zero(), "")
// .unwrap(); .unwrap();
// ctx.make_assert( ctx.make_assert(
// generator, generator,
// n_sz_eqz, n_sz_eqz,
// "0:ValueError", "0:ValueError",
// "zero-size array to reduction operation minimum which has no identity", "zero-size array to reduction operation minimum which has no identity",
// [None, None, None], [None, None, None],
// ctx.current_loc, ctx.current_loc,
// ); );
// } }
// let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?; let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?;
// unsafe { unsafe {
// let identity = let identity =
// n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None); n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None);
// ctx.builder.build_store(accumulator_addr, identity).unwrap(); ctx.builder.build_store(accumulator_addr, identity).unwrap();
// } }
// gen_for_callback_incrementing( gen_for_callback_incrementing(
// generator, generator,
// ctx, ctx,
// llvm_usize.const_int(1, false), llvm_usize.const_int(1, false),
// (n_sz, false), (n_sz, false),
// |generator, ctx, _, idx| { |generator, ctx, _, idx| {
// let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) }; let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) };
// let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap(); let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
// let result = call_min(ctx, (elem_ty, accumulator), (elem_ty, elem)); let result = call_min(ctx, (elem_ty, accumulator), (elem_ty, elem));
// ctx.builder.build_store(accumulator_addr, result).unwrap(); ctx.builder.build_store(accumulator_addr, result).unwrap();
// Ok(()) Ok(())
// }, },
// llvm_usize.const_int(1, false), llvm_usize.const_int(1, false),
// )?; )?;
// let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap(); let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
// accumulator accumulator
} }
_ => unsupported_type(ctx, FN_NAME, &[a_ty]), _ => unsupported_type(ctx, FN_NAME, &[a_ty]),
@ -921,54 +920,53 @@ pub fn call_numpy_max<'ctx, G: CodeGenerator + ?Sized>(
BasicValueEnum::PointerValue(n) BasicValueEnum::PointerValue(n)
if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) => if a_ty.obj_id(&ctx.unifier).is_some_and(|id| id == PrimDef::NDArray.id()) =>
{ {
todo!() let (elem_ty, _) = unpack_ndarray_var_tys(&mut ctx.unifier, a_ty);
// let (elem_ty, _) = unpack_ndarray_var_tys(&mut ctx.unifier, a_ty); let llvm_ndarray_ty = ctx.get_llvm_type(generator, elem_ty);
// let llvm_ndarray_ty = ctx.get_llvm_type(generator, elem_ty);
// let n = NDArrayValue::from_ptr_val(n, llvm_usize, None); let n = NDArrayValue::from_ptr_val(n, llvm_usize, None);
// let n_sz = irrt::call_ndarray_calc_size(generator, ctx, &n.dim_sizes(), (None, None)); let n_sz = irrt::call_ndarray_calc_size(generator, ctx, &n.dim_sizes(), (None, None));
// if ctx.registry.llvm_options.opt_level == OptimizationLevel::None { if ctx.registry.llvm_options.opt_level == OptimizationLevel::None {
// let n_sz_eqz = ctx let n_sz_eqz = ctx
// .builder .builder
// .build_int_compare(IntPredicate::NE, n_sz, n_sz.get_type().const_zero(), "") .build_int_compare(IntPredicate::NE, n_sz, n_sz.get_type().const_zero(), "")
// .unwrap(); .unwrap();
// ctx.make_assert( ctx.make_assert(
// generator, generator,
// n_sz_eqz, n_sz_eqz,
// "0:ValueError", "0:ValueError",
// "zero-size array to reduction operation minimum which has no identity", "zero-size array to reduction operation minimum which has no identity",
// [None, None, None], [None, None, None],
// ctx.current_loc, ctx.current_loc,
// ); );
// } }
// let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?; let accumulator_addr = generator.gen_var_alloc(ctx, llvm_ndarray_ty, None)?;
// unsafe { unsafe {
// let identity = let identity =
// n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None); n.data().get_unchecked(ctx, generator, &llvm_usize.const_zero(), None);
// ctx.builder.build_store(accumulator_addr, identity).unwrap(); ctx.builder.build_store(accumulator_addr, identity).unwrap();
// } }
// gen_for_callback_incrementing( gen_for_callback_incrementing(
// generator, generator,
// ctx, ctx,
// llvm_usize.const_int(1, false), llvm_usize.const_int(1, false),
// (n_sz, false), (n_sz, false),
// |generator, ctx, _, idx| { |generator, ctx, _, idx| {
// let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) }; let elem = unsafe { n.data().get_unchecked(ctx, generator, &idx, None) };
// let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap(); let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
// let result = call_max(ctx, (elem_ty, accumulator), (elem_ty, elem)); let result = call_max(ctx, (elem_ty, accumulator), (elem_ty, elem));
// ctx.builder.build_store(accumulator_addr, result).unwrap(); ctx.builder.build_store(accumulator_addr, result).unwrap();
// Ok(()) Ok(())
// }, },
// llvm_usize.const_int(1, false), llvm_usize.const_int(1, false),
// )?; )?;
// let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap(); let accumulator = ctx.builder.build_load(accumulator_addr, "").unwrap();
// accumulator accumulator
} }
_ => unsupported_type(ctx, FN_NAME, &[a_ty]), _ => unsupported_type(ctx, FN_NAME, &[a_ty]),

View File

@ -1,8 +1,5 @@
use crate::codegen::{ use crate::codegen::{
// irrt::{call_ndarray_calc_size, call_ndarray_flatten_index}, llvm_intrinsics::call_int_umin, stmt::gen_for_callback_incrementing, CodeGenContext,
llvm_intrinsics::call_int_umin,
stmt::gen_for_callback_incrementing,
CodeGenContext,
CodeGenerator, CodeGenerator,
}; };
use inkwell::context::Context; use inkwell::context::Context;
@ -1210,27 +1207,25 @@ impl<'ctx> NDArrayType<'ctx> {
ctx: &'ctx Context, ctx: &'ctx Context,
dtype: BasicTypeEnum<'ctx>, dtype: BasicTypeEnum<'ctx>,
) -> Self { ) -> Self {
todo!() let llvm_usize = generator.get_size_type(ctx);
// let llvm_usize = generator.get_size_type(ctx); // struct NDArray { num_dims: size_t, dims: size_t*, data: T* }
//
// * num_dims: Number of dimensions in the array
// * dims: Pointer to an array containing the size of each dimension
// * data: Pointer to an array containing the array data
let llvm_ndarray = ctx
.struct_type(
&[
llvm_usize.into(),
llvm_usize.ptr_type(AddressSpace::default()).into(),
dtype.ptr_type(AddressSpace::default()).into(),
],
false,
)
.ptr_type(AddressSpace::default());
// // struct NDArray { num_dims: size_t, dims: size_t*, data: T* } NDArrayType::from_type(llvm_ndarray, llvm_usize)
// //
// // * num_dims: Number of dimensions in the array
// // * dims: Pointer to an array containing the size of each dimension
// // * data: Pointer to an array containing the array data
// let llvm_ndarray = ctx
// .struct_type(
// &[
// llvm_usize.into(),
// llvm_usize.ptr_type(AddressSpace::default()).into(),
// dtype.ptr_type(AddressSpace::default()).into(),
// ],
// false,
// )
// .ptr_type(AddressSpace::default());
// NDArrayType::from_type(llvm_ndarray, llvm_usize)
} }
/// Creates an [`NDArrayType`] from a [`PointerType`]. /// Creates an [`NDArrayType`] from a [`PointerType`].
@ -1664,22 +1659,23 @@ impl<'ctx, Index: UntypedArrayLikeAccessor<'ctx>> ArrayLikeIndexer<'ctx, Index>
indices: &Index, indices: &Index,
name: Option<&str>, name: Option<&str>,
) -> PointerValue<'ctx> { ) -> PointerValue<'ctx> {
todo!() let llvm_usize = generator.get_size_type(ctx.ctx);
// let llvm_usize = generator.get_size_type(ctx.ctx);
// let indices_elem_ty = indices let indices_elem_ty = indices
// .ptr_offset(ctx, generator, &llvm_usize.const_zero(), None) .ptr_offset(ctx, generator, &llvm_usize.const_zero(), None)
// .get_type() .get_type()
// .get_element_type(); .get_element_type();
// let Ok(indices_elem_ty) = IntType::try_from(indices_elem_ty) else { let Ok(indices_elem_ty) = IntType::try_from(indices_elem_ty) else {
// panic!("Expected list[int32] but got {indices_elem_ty}") panic!("Expected list[int32] but got {indices_elem_ty}")
// }; };
// assert_eq!( assert_eq!(
// indices_elem_ty.get_bit_width(), indices_elem_ty.get_bit_width(),
// 32, 32,
// "Expected list[int32] but got list[int{}]", "Expected list[int32] but got list[int{}]",
// indices_elem_ty.get_bit_width() indices_elem_ty.get_bit_width()
// ); );
todo!()
// let index = call_ndarray_flatten_index(generator, ctx, *self.0, indices); // let index = call_ndarray_flatten_index(generator, ctx, *self.0, indices);
@ -1768,163 +1764,306 @@ impl<'ctx, Index: UntypedArrayLikeAccessor<'ctx>> UntypedArrayLikeMutator<'ctx,
{ {
} }
// #[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
// pub struct StructField<'ctx> { pub struct StructField<'ctx> {
// /// The GEP index of this struct field. /// The GEP index of this struct field.
// pub gep_index: u32, pub gep_index: u32,
// /// Name of this struct field. /// Name of this struct field.
// /// ///
// /// Used for generating names. /// Used for generating names.
// pub name: &'static str, pub name: &'static str,
// /// The type of this struct field. /// The type of this struct field.
// pub ty: BasicTypeEnum<'ctx>, pub ty: BasicTypeEnum<'ctx>,
// } }
//
// pub struct StructFields<'ctx> {
// /// Name of the struct.
// ///
// /// Used for generating names.
// pub name: &'static str,
//
// /// All the [`StructField`]s of this struct.
// ///
// /// **NOTE:** The index position of a [`StructField`]
// /// matches the element's [`StructField::index`].
// pub fields: Vec<StructField<'ctx>>,
// }
//
// pub struct StructFieldsBuilder<'ctx> {
// gep_index_counter: u32,
// /// Name of the struct to be built.
// name: &'static str,
// fields: Vec<StructField<'ctx>>,
// }
//
// impl<'ctx> StructField<'ctx> {
// /// TODO: DOCUMENT ME
// pub fn gep(
// &self,
// ctx: &CodeGenContext<'ctx, '_>,
// struct_ptr: PointerValue<'ctx>,
// ) -> PointerValue<'ctx> {
// let index_type = ctx.ctx.i32_type(); // TODO: I think I'm not supposed to use i32 for GEP like that
// unsafe {
// ctx.builder
// .build_in_bounds_gep(
// struct_ptr,
// &[index_type.const_zero(), index_type.const_int(self.gep_index as u64, false)],
// self.name,
// )
// .unwrap()
// }
// }
//
// /// TODO: DOCUMENT ME
// pub fn load(
// &self,
// ctx: &CodeGenContext<'ctx, '_>,
// struct_ptr: PointerValue<'ctx>,
// ) -> BasicValueEnum<'ctx> {
// ctx.builder.build_load(self.gep(ctx, struct_ptr), self.name).unwrap()
// }
//
// /// TODO: DOCUMENT ME
// pub fn store<V>(&self, ctx: &CodeGenContext<'ctx, '_>, struct_ptr: PointerValue<'ctx>, value: V)
// where
// V: BasicValue<'ctx>,
// {
// ctx.builder.build_store(self.gep(ctx, struct_ptr), value).unwrap();
// }
// }
// type IsInstanceError = String; pub struct StructFields<'ctx> {
// type IsInstanceResult = Result<(), IsInstanceError>; /// Name of the struct.
///
/// Used for generating names.
pub name: &'static str,
// pub fn check_basic_types_match<'ctx, A, B>(expected: A, got: B) -> IsInstanceResult /// All the [`StructField`]s of this struct.
// where ///
// A: BasicType<'ctx>, /// **NOTE:** The index position of a [`StructField`]
// B: BasicType<'ctx>, /// matches the element's [`StructField::index`].
// { pub fields: Vec<StructField<'ctx>>,
// let expected = expected.as_basic_type_enum(); }
// let got = got.as_basic_type_enum();
// // Put those logic into here, struct StructFieldsBuilder<'ctx> {
// // otherwise there is always a fallback reporting on any kind of mismatch gep_index_counter: u32,
// match (expected, got) { /// Name of the struct to be built.
// (BasicTypeEnum::IntType(expected), BasicTypeEnum::IntType(got)) => { name: &'static str,
// if expected.get_bit_width() != got.get_bit_width() { fields: Vec<StructField<'ctx>>,
// return Err(format!( }
// "Expected IntType ({expected}-bit(s)), got IntType ({got}-bit(s))"
// ));
// }
// }
// (expected, got) => {
// if expected != got {
// return Err(format!("Expected {expected}, got {got}"));
// }
// }
// }
// Ok(())
// }
// impl<'ctx> StructFields<'ctx> { impl<'ctx> StructField<'ctx> {
// pub fn num_fields(&self) -> u32 { pub fn gep(
// self.fields.len() as u32 &self,
// } ctx: &CodeGenContext<'ctx, '_>,
// ptr: PointerValue<'ctx>,
// pub fn get_struct_type(&self, ctx: &'ctx Context) -> StructType<'ctx> { ) -> PointerValue<'ctx> {
// let llvm_fields = self.fields.iter().map(|field| field.ty).collect_vec(); ctx.builder.build_struct_gep(ptr, self.gep_index, self.name).unwrap()
// ctx.struct_type(llvm_fields.as_slice(), false) }
// }
// pub fn load(
// pub fn is_type(&self, scrutinee: StructType<'ctx>) -> IsInstanceResult { &self,
// // Check scrutinee's number of struct fields ctx: &CodeGenContext<'ctx, '_>,
// if scrutinee.count_fields() != self.num_fields() { ptr: PointerValue<'ctx>,
// return Err(format!( ) -> BasicValueEnum<'ctx> {
// "Expected {expected_count} field(s) in `{struct_name}` type, got {got_count}", ctx.builder.build_load(self.gep(ctx, ptr), self.name).unwrap()
// struct_name = self.name, }
// expected_count = self.num_fields(),
// got_count = scrutinee.count_fields(), pub fn store<V>(&self, ctx: &CodeGenContext<'ctx, '_>, ptr: PointerValue<'ctx>, value: V)
// )); where
// } V: BasicValue<'ctx>,
// {
// // Check the scrutinee's field types ctx.builder.build_store(ptr, value).unwrap();
// for field in self.fields.iter() { }
// let expected_field_ty = field.ty; }
// let got_field_ty = scrutinee.get_field_type_at_index(field.gep_index).unwrap();
// type IsInstanceError = String;
// if let Err(field_err) = check_basic_types_match(expected_field_ty, got_field_ty) { type IsInstanceResult = Result<(), IsInstanceError>;
// return Err(format!(
// "Field GEP index {gep_index} does not match the expected type of ({struct_name}::{field_name}): {field_err}", pub fn check_basic_types_match<'ctx, A, B>(expected: A, got: B) -> IsInstanceResult
// gep_index = field.gep_index, where
// struct_name = self.name, A: BasicType<'ctx>,
// field_name = field.name, B: BasicType<'ctx>,
// )); {
// } let expected = expected.as_basic_type_enum();
// } let got = got.as_basic_type_enum();
//
// // Done // Put those logic into here,
// Ok(()) // otherwise there is always a fallback reporting on any kind of mismatch
// } match (expected, got) {
// } (BasicTypeEnum::IntType(expected), BasicTypeEnum::IntType(got)) => {
// if expected.get_bit_width() != got.get_bit_width() {
// impl<'ctx> StructFieldsBuilder<'ctx> { return Err(format!(
// pub fn start(name: &'static str) -> Self { "Expected IntType ({expected}-bit(s)), got IntType ({got}-bit(s))"
// StructFieldsBuilder { gep_index_counter: 0, name, fields: Vec::new() } ));
// } }
// }
// pub fn add_field(&mut self, name: &'static str, ty: BasicTypeEnum<'ctx>) -> StructField<'ctx> { (expected, got) => {
// let index = self.gep_index_counter; if expected != got {
// self.gep_index_counter += 1; return Err(format!("Expected {expected}, got {got}"));
// }
// let field = StructField { gep_index: index, name, ty }; }
// self.fields.push(field); // Register into self.fields }
// Ok(())
// field // Return to the caller to conveniently let them do whatever they want }
// }
// impl<'ctx> StructFields<'ctx> {
// pub fn end(self) -> StructFields<'ctx> { pub fn num_fields(&self) -> u32 {
// StructFields { name: self.name, fields: self.fields } self.fields.len() as u32
// } }
// }
// pub fn as_struct_type(&self, ctx: &'ctx Context) -> StructType<'ctx> {
let llvm_fields = self.fields.iter().map(|field| field.ty).collect_vec();
ctx.struct_type(llvm_fields.as_slice(), false)
}
pub fn is_type(&self, scrutinee: StructType<'ctx>) -> IsInstanceResult {
// Check scrutinee's number of struct fields
if scrutinee.count_fields() != self.num_fields() {
return Err(format!(
"Expected {expected_count} field(s) in `{struct_name}` type, got {got_count}",
struct_name = self.name,
expected_count = self.num_fields(),
got_count = scrutinee.count_fields(),
));
}
// Check the scrutinee's field types
for field in self.fields.iter() {
let expected_field_ty = field.ty;
let got_field_ty = scrutinee.get_field_type_at_index(field.gep_index).unwrap();
if let Err(field_err) = check_basic_types_match(expected_field_ty, got_field_ty) {
return Err(format!(
"Field GEP index {gep_index} does not match the expected type of ({struct_name}::{field_name}): {field_err}",
gep_index = field.gep_index,
struct_name = self.name,
field_name = field.name,
));
}
}
// Done
Ok(())
}
}
impl<'ctx> StructFieldsBuilder<'ctx> {
fn start(name: &'static str) -> Self {
StructFieldsBuilder { gep_index_counter: 0, name, fields: Vec::new() }
}
fn add_field(&mut self, name: &'static str, ty: BasicTypeEnum<'ctx>) -> StructField<'ctx> {
let index = self.gep_index_counter;
self.gep_index_counter += 1;
StructField { gep_index: index, name, ty }
}
fn end(self) -> StructFields<'ctx> {
StructFields { name: self.name, fields: self.fields }
}
}
#[derive(Debug, Clone, Copy)]
pub struct NpArrayType<'ctx> {
pub size_type: IntType<'ctx>,
pub elem_type: BasicTypeEnum<'ctx>,
}
pub struct NpArrayStructFields<'ctx> {
pub whole_struct: StructFields<'ctx>,
pub data: StructField<'ctx>,
pub itemsize: StructField<'ctx>,
pub ndims: StructField<'ctx>,
pub shape: StructField<'ctx>,
pub strides: StructField<'ctx>,
}
impl<'ctx> NpArrayType<'ctx> {
pub fn new_opaque_elem(
ctx: &CodeGenContext<'ctx, '_>,
size_type: IntType<'ctx>,
) -> NpArrayType<'ctx> {
NpArrayType { size_type, elem_type: ctx.ctx.i8_type().as_basic_type_enum() }
}
pub fn struct_type(&self, ctx: &CodeGenContext<'ctx, '_>) -> StructType<'ctx> {
self.fields().whole_struct.as_struct_type(ctx.ctx)
}
pub fn fields(&self) -> NpArrayStructFields<'ctx> {
let mut builder = StructFieldsBuilder::start("NpArray");
let addrspace = AddressSpace::default();
let byte_type = self.size_type.get_context().i8_type();
// Make sure the struct matches PERFECTLY with that defined in `nac3core/irrt`.
let data = builder.add_field("data", byte_type.ptr_type(addrspace).into());
let itemsize = builder.add_field("itemsize", self.size_type.into());
let ndims = builder.add_field("ndims", self.size_type.into());
let shape = builder.add_field("shape", self.size_type.ptr_type(addrspace).into());
let strides = builder.add_field("strides", self.size_type.ptr_type(addrspace).into());
NpArrayStructFields { whole_struct: builder.end(), data, itemsize, ndims, shape, strides }
}
/// Allocate an `ndarray` on stack, with the following notes:
///
/// - `ndarray.ndims` will be initialized to `in_ndims`.
/// - `ndarray.itemsize` will be initialized to the size of `self.elem_type.size_of()`.
/// - `ndarray.shape` and `ndarray.strides` will be allocated on the stack with number of elements being `in_ndims`,
/// all with empty/uninitialized values.
pub fn alloca(
&self,
ctx: &CodeGenContext<'ctx, '_>,
in_ndims: IntValue<'ctx>,
name: &str,
) -> NpArrayValue<'ctx> {
let fields = self.fields();
let ptr =
ctx.builder.build_alloca(fields.whole_struct.as_struct_type(ctx.ctx), name).unwrap();
// Allocate `in_dims` number of `size_type` on the stack for `shape` and `strides`
let allocated_shape =
ctx.builder.build_array_alloca(fields.shape.ty, in_ndims, "allocated_shape").unwrap();
let allocated_strides = ctx
.builder
.build_array_alloca(fields.strides.ty, in_ndims, "allocated_strides")
.unwrap();
let value = NpArrayValue { ty: *self, ptr };
value.store_ndims(ctx, in_ndims);
value.store_itemsize(ctx, self.elem_type.size_of().unwrap());
value.store_shape(ctx, allocated_shape);
value.store_strides(ctx, allocated_strides);
return value;
}
}
#[derive(Debug, Clone, Copy)]
pub struct NpArrayValue<'ctx> {
pub ty: NpArrayType<'ctx>,
pub ptr: PointerValue<'ctx>,
}
impl<'ctx> NpArrayValue<'ctx> {
pub fn load_ndims(&self, ctx: &CodeGenContext<'ctx, '_>) -> IntValue<'ctx> {
let field = self.ty.fields().ndims;
field.load(ctx, self.ptr).into_int_value()
}
pub fn store_ndims(&self, ctx: &CodeGenContext<'ctx, '_>, value: IntValue<'ctx>) {
let field = self.ty.fields().ndims;
field.store(ctx, self.ptr, value);
}
pub fn load_itemsize(&self, ctx: &CodeGenContext<'ctx, '_>) -> IntValue<'ctx> {
let field = self.ty.fields().itemsize;
field.load(ctx, self.ptr).into_int_value()
}
pub fn store_itemsize(&self, ctx: &CodeGenContext<'ctx, '_>, value: IntValue<'ctx>) {
let field = self.ty.fields().itemsize;
field.store(ctx, self.ptr, value);
}
pub fn load_shape(&self, ctx: &CodeGenContext<'ctx, '_>) -> PointerValue<'ctx> {
let field = self.ty.fields().shape;
field.load(ctx, self.ptr).into_pointer_value()
}
pub fn store_shape(&self, ctx: &CodeGenContext<'ctx, '_>, value: PointerValue<'ctx>) {
let field = self.ty.fields().shape;
field.store(ctx, self.ptr, value);
}
pub fn load_strides(&self, ctx: &CodeGenContext<'ctx, '_>) -> PointerValue<'ctx> {
let field = self.ty.fields().strides;
field.load(ctx, self.ptr).into_pointer_value()
}
pub fn store_strides(&self, ctx: &CodeGenContext<'ctx, '_>, value: PointerValue<'ctx>) {
let field = self.ty.fields().strides;
field.store(ctx, self.ptr, value);
}
/// TODO: DOCUMENT ME -- NDIMS WOULD NEVER CHANGE!!!!!
pub fn shape_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
) -> TypedArrayLikeAdapter<'ctx, IntValue<'ctx>> {
let field = self.ty.fields().shape;
field.gep(ctx, self.ptr);
let ndims = self.load_ndims(ctx);
TypedArrayLikeAdapter {
adapted: ArraySliceValue(self.ptr, ndims, Some(field.name)),
downcast_fn: Box::new(|_ctx, x| x.into_int_value()),
upcast_fn: Box::new(|_ctx, x| x.as_basic_value_enum()),
}
}
/// TODO: DOCUMENT ME -- NDIMS WOULD NEVER CHANGE!!!!!
pub fn strides_slice(
&self,
ctx: &CodeGenContext<'ctx, '_>,
) -> TypedArrayLikeAdapter<'ctx, IntValue<'ctx>> {
let field = self.ty.fields().strides;
field.gep(ctx, self.ptr);
let ndims = self.load_ndims(ctx);
TypedArrayLikeAdapter {
adapted: ArraySliceValue(self.ptr, ndims, Some(field.name)),
downcast_fn: Box::new(|_ctx, x| x.into_int_value()),
upcast_fn: Box::new(|_ctx, x| x.as_basic_value_enum()),
}
}
}

View File

@ -1,14 +1,10 @@
use std::{ use std::{collections::HashMap, convert::TryInto, iter::once, iter::zip};
collections::HashMap,
convert::TryInto,
iter::{once, zip},
};
use crate::{ use crate::{
codegen::{ codegen::{
classes::{ classes::{
ArrayLikeIndexer, ArrayLikeValue, ListType, ListValue, NDArrayDataProxy, NDArrayValue, ArrayLikeIndexer, ArrayLikeValue, ListType, ListValue, NDArrayValue, ProxyType,
ProxyType, ProxyValue, RangeValue, TypedArrayLikeAccessor, UntypedArrayLikeAccessor, ProxyValue, RangeValue, TypedArrayLikeAccessor, UntypedArrayLikeAccessor,
}, },
concrete_type::{ConcreteFuncArg, ConcreteTypeEnum, ConcreteTypeStore}, concrete_type::{ConcreteFuncArg, ConcreteTypeEnum, ConcreteTypeStore},
gen_in_range_check, get_llvm_abi_type, get_llvm_type, gen_in_range_check, get_llvm_abi_type, get_llvm_type,
@ -17,8 +13,7 @@ use crate::{
call_expect, call_float_floor, call_float_pow, call_float_powi, call_int_smax, call_expect, call_float_floor, call_float_pow, call_float_powi, call_int_smax,
call_memcpy_generic, call_memcpy_generic,
}, },
need_sret, need_sret, numpy,
numpy::{self, call_ndarray_subscript_impl, get_ndarray_first_element},
stmt::{ stmt::{
gen_for_callback_incrementing, gen_if_callback, gen_if_else_expr_callback, gen_raise, gen_for_callback_incrementing, gen_if_callback, gen_if_else_expr_callback, gen_raise,
gen_var, gen_var,
@ -39,17 +34,15 @@ use crate::{
use inkwell::{ use inkwell::{
attributes::{Attribute, AttributeLoc}, attributes::{Attribute, AttributeLoc},
types::{AnyType, BasicType, BasicTypeEnum}, types::{AnyType, BasicType, BasicTypeEnum},
values::{BasicValue, BasicValueEnum, CallSiteValue, FunctionValue, IntValue, PointerValue}, values::{BasicValueEnum, CallSiteValue, FunctionValue, IntValue, PointerValue},
AddressSpace, IntPredicate, OptimizationLevel, AddressSpace, IntPredicate, OptimizationLevel,
}; };
use itertools::{chain, izip, Either, Itertools}; use itertools::{chain, izip, Either, Itertools};
use nac3parser::ast::{ use nac3parser::ast::{
self, Boolop, Cmpop, Comprehension, Constant, Expr, ExprKind, Located, Location, Operator, self, Boolop, Cmpop, Comprehension, Constant, Expr, ExprKind, Location, Operator, StrRef,
StrRef, Unaryop, Unaryop,
}; };
use super::classes::{NpArrayType, NpArrayValue};
pub fn get_subst_key( pub fn get_subst_key(
unifier: &mut Unifier, unifier: &mut Unifier,
obj: Option<Type>, obj: Option<Type>,
@ -2102,123 +2095,17 @@ pub fn gen_cmpop_expr<'ctx, G: CodeGenerator>(
/// ///
/// * `ty` - The `Type` of the `NDArray` elements. /// * `ty` - The `Type` of the `NDArray` elements.
/// * `ndims` - The `Type` of the `NDArray` number-of-dimensions `Literal`. /// * `ndims` - The `Type` of the `NDArray` number-of-dimensions `Literal`.
/// * `ndarray` - The `NDArray` value. /// * `v` - The `NDArray` value.
/// * `slice` - The slice expression used to subscript into the `ndarray`. /// * `slice` - The slice expression used to subscript into the `ndarray`.
fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>( fn gen_ndarray_subscript_expr<'ctx, G: CodeGenerator>(
generator: &mut G, generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>, ctx: &mut CodeGenContext<'ctx, '_>,
ty: Type, ty: Type,
ndims: Type, ndims: Type,
ndarray: NpArrayValue<'ctx>, v: NDArrayValue<'ctx>,
slice: &Expr<Option<Type>>, slice: &Expr<Option<Type>>,
) -> Result<Option<ValueEnum<'ctx>>, String> { ) -> Result<Option<ValueEnum<'ctx>>, String> {
// TODO: bounds check (on IRRT (how?), or using inkwell) todo!()
// TODO: For invalid `slice`, throw a proper error
// TODO: Support https://numpy.org/doc/stable/user/basics.indexing.html#dimensional-indexing-tools
let size_type = ndarray.ty.size_type;
debug_assert_eq!(size_type, generator.get_size_type(ctx.ctx)); // The ndarray's size_type somehow isn't that of `generator.get_size_type()`... there would be a bug
// Annoying notes about `slice`
// - `my_array[5]`
// - slice is a `Constant`
// - `my_array[:5]`
// - slice is a `Slice`
// - `my_array[:]`
// - slice is a `Slice`, but lower upper step would all be `Option::None`
// - `my_array[:, :]`
// - slice is now a `Tuple` of two `Slice`-s
//
// In summary:
// - when there is a comma "," within [], `slice` will be a `Tuple` of the entries.
// - when there is not comma "," within [] (i.e., just a single entry), `slice` will be that entry itself.
//
// `entries` will flatten it out.
let entries = match &slice.node {
ExprKind::Tuple { elts, ctx } => elts.iter().collect_vec(),
_ => vec![slice],
};
// This could have been written as a `ndslices = entries.into_iter().map(...)`,
// but error shortcutting part would be annoying
let mut ndslices = vec![];
for entry in entries.into_iter() {
// NOTE: Currently nac3core's slices do not have an object representation,
// so the code/implementation looks awkward - we have to do pattern matching on the expression
let ndslice = match &entry.node {
ExprKind::Slice { lower: start, upper: stop, step } => {
// Helper function here to deduce code duplication
let mut help = |value_expr: &Option<
Box<Located<ExprKind<Option<Type>>, Option<Type>>>,
>|
-> Result<_, String> {
Ok(match value_expr {
None => None,
Some(value_expr) => Some(
generator
.gen_expr(ctx, &value_expr)?
.unwrap()
.to_basic_value_enum(ctx, generator, ctx.primitives.int32)?
.into_int_value(),
),
})
};
let start = help(start)?;
let stop = help(stop)?;
let step = help(step)?;
// start stop step should all be 32-bit ints after typechecking,
// and `IrrtUserSlice` expects `int32`s
NDSlice::Slice(UserSlice { start, stop, step })
}
_ => {
// Anything else that is not a slice (might be illegal values),
// For nac3core, this should be e.g., an int32 constant, an int32 variable, otherwise its an error
let index = generator
.gen_expr(ctx, entry)?
.unwrap()
.to_basic_value_enum(ctx, generator, ctx.primitives.int32)?
.into_int_value();
NDSlice::Index(index)
}
};
ndslices.push(ndslice);
}
// TODO: what is going on? why the original implementation doesn't assert `ndims_values.len() == 1`
// Extract the `ndims` from a `Type` to `i128`
let TypeEnum::TLiteral { values: ndims_values, .. } = &*ctx.unifier.get_ty_immutable(ndims)
else {
unreachable!()
};
assert_eq!(ndims_values.len(), 1);
let ndims = i128::try_from(ndims_values[0].clone()).unwrap() as u64;
assert!(ndims > 0);
// Deduce the subndarray's ndims
let dst_ndims = deduce_ndims_after_slicing(ndims, ndslices.iter());
// Finally, perform the actual subscript logic
// TODO: `call_ndarray_subscript_impl` under the hood deduces `dst_ndims` again. We could save it some time by passing `dst_ndims` - a TODO?
let subndarray = call_ndarray_subscript_impl(
generator,
ctx,
ndarray,
&ndslices.iter().collect_vec(),
)?;
// ...and return the result, with two cases
let result = if dst_ndims == 0 {
// 1) ndims == 0 (this happens when you do `np.zerps((3, 4))[1, 1]`), return *THE ELEMENT*
get_ndarray_first_element(ctx, subndarray, "element")
} else {
// 2) ndims > 0 (other cases), return subndarray
subndarray.ptr.as_basic_value_enum()
};
Ok(Some(ValueEnum::Dynamic(result)))
// let llvm_i1 = ctx.ctx.bool_type(); // let llvm_i1 = ctx.ctx.bool_type();
// let llvm_i32 = ctx.ctx.i32_type(); // let llvm_i32 = ctx.ctx.i32_type();
@ -3144,29 +3031,17 @@ pub fn gen_expr<'ctx, G: CodeGenerator>(
} }
} }
TypeEnum::TObj { obj_id, params, .. } if *obj_id == PrimDef::NDArray.id() => { TypeEnum::TObj { obj_id, params, .. } if *obj_id == PrimDef::NDArray.id() => {
let (elem_ty, ndims) = params.iter().map(|(_, ty)| ty).collect_tuple().unwrap(); let (ty, ndims) = params.iter().map(|(_, ty)| ty).collect_tuple().unwrap();
// Get the pointer to the ndarray described by `value` let v = if let Some(v) = generator.gen_expr(ctx, value)? {
let ndarray_ptr = if let Some(v) = generator.gen_expr(ctx, value)? {
v.to_basic_value_enum(ctx, generator, value.custom.unwrap())? v.to_basic_value_enum(ctx, generator, value.custom.unwrap())?
.into_pointer_value() .into_pointer_value()
} else { } else {
return Ok(None); return Ok(None);
}; };
let v = NDArrayValue::from_ptr_val(v, usize, None);
// Derive the current NDArray struct type independently... return gen_ndarray_subscript_expr(generator, ctx, *ty, *ndims, v, slice);
let ndarray_ty = NpArrayType {
elem_type: ctx.get_llvm_type(generator, *elem_ty),
size_type: generator.get_size_type(ctx.ctx),
};
// ...and wrap it in `NDArrayValue`
let ndarray = ndarray_ty.value_from_ptr(ctx.ctx, ndarray_ptr);
// Implementation
return gen_ndarray_subscript_expr(
generator, ctx, *elem_ty, *ndims, ndarray, slice,
);
} }
TypeEnum::TTuple { .. } => { TypeEnum::TTuple { .. } => {
let index: u32 = let index: u32 =

View File

@ -1,87 +0,0 @@
// TODO: Use derppening's abstraction
use std::marker::PhantomData;
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, IntType},
values::BasicValueEnum,
AddressSpace,
};
use crate::codegen::structure::{
CustomStructType, CustomType, Field, FieldCreator, IntType2, Object, PointerType2,
PointingArrayType,
};
#[derive(Debug, Clone, Copy)]
pub struct NpArrayType<'ctx> {
pub size_type: IntType<'ctx>,
pub elem_type: BasicTypeEnum<'ctx>,
}
pub struct NpArrayFields<'ctx> {
pub data: Field<'ctx, PointerType2<'ctx>>,
pub itemsize: Field<'ctx, IntType2<'ctx>>,
pub ndims: Field<'ctx, IntType2<'ctx>>,
pub shape: Field<'ctx, PointingArrayType<'ctx, IntType2<'ctx>>>,
pub strides: Field<'ctx, PointingArrayType<'ctx, IntType2<'ctx>>>,
}
pub type NpArrayValue<'ctx> = Object<'ctx, NpArrayType<'ctx>>;
// impl<'ctx> CustomType<'ctx> for NpArrayType<'ctx> {
// type Value = NpArrayValue<'ctx>;
//
// fn llvm_basic_type_enum(
// &self,
// ctx: &'ctx inkwell::context::Context,
// ) -> inkwell::types::BasicTypeEnum<'ctx> {
// self.llvm_struct_type(ctx).as_basic_type_enum()
// }
//
// fn llvm_field_load(
// &self,
// ctx: &crate::codegen::CodeGenContext<'ctx, '_>,
// field: crate::codegen::structure::FieldInfo,
// struct_ptr: inkwell::values::PointerValue<'ctx>,
// ) -> Self::Value {
// let ok = field.llvm_load(ctx, struct_ptr);
// todo!()
// }
//
// fn llvm_field_store(
// &self,
// ctx: &crate::codegen::CodeGenContext<'ctx, '_>,
// field: crate::codegen::structure::FieldInfo,
// struct_ptr: inkwell::values::PointerValue<'ctx>,
// value: &Self::Value,
// ) {
// todo!()
// }
// }
impl<'ctx> CustomStructType<'ctx> for NpArrayType<'ctx> {
type Fields = NpArrayFields<'ctx>;
fn llvm_struct_name() -> &'static str {
"NDArray"
}
fn add_fields_to(&self, creator: &mut FieldCreator<'ctx>) -> Self::Fields {
let pi8 = creator.ctx.i8_type().ptr_type(AddressSpace::default());
NpArrayFields {
data: creator.add_field("data", PointerType2(pi8)),
itemsize: creator.add_field("itemsize", IntType2(self.size_type)),
ndims: creator.add_field("ndims", IntType2(self.size_type)),
shape: creator.add_field("shape", PointingArrayType::new(IntType2(self.size_type))),
strides: creator.add_field("strides", PointingArrayType::new(IntType2(self.size_type))),
}
}
}
impl<'ctx> NpArrayType<'ctx> {
pub fn new_opaque_elem(ctx: &'ctx Context, size_type: IntType<'ctx>) -> Self {
NpArrayType { elem_type: ctx.i8_type().into(), size_type }
}
}

File diff suppressed because it is too large Load Diff

View File

@ -35,54 +35,6 @@ fn get_float_intrinsic_repr(ctx: &Context, ft: FloatType) -> &'static str {
unreachable!() unreachable!()
} }
/// Invokes the [`llvm.lifetime.start`](https://releases.llvm.org/14.0.0/docs/LangRef.html#llvm-lifetime-start-intrinsic)
/// intrinsic.
pub fn call_lifetime_start<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
size: IntValue<'ctx>,
ptr: PointerValue<'ctx>,
) {
const FN_NAME: &str = "llvm.lifetime.start";
// NOTE: inkwell temporary workaround, see [`call_stackrestore`] for details
let intrinsic_fn = ctx.module.get_function(FN_NAME).unwrap_or_else(|| {
let llvm_void = ctx.ctx.void_type();
let llvm_i64 = ctx.ctx.i64_type();
let llvm_p0i8 = ctx.ctx.i8_type().ptr_type(AddressSpace::default());
let fn_type = llvm_void.fn_type(&[llvm_i64.into(), llvm_p0i8.into()], false);
ctx.module.add_function(FN_NAME, fn_type, None)
});
ctx.builder
.build_call(intrinsic_fn, &[size.into(), ptr.into()], "")
.map(CallSiteValue::try_as_basic_value)
.unwrap();
}
/// Invokes the [`llvm.lifetime.end`](https://releases.llvm.org/14.0.0/docs/LangRef.html#llvm-lifetime-end-intrinsic)
/// intrinsic.
pub fn call_lifetime_end<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
size: IntValue<'ctx>,
ptr: PointerValue<'ctx>,
) {
const FN_NAME: &str = "llvm.lifetime.end";
// NOTE: inkwell temporary workaround, see [`call_stackrestore`] for details
let intrinsic_fn = ctx.module.get_function(FN_NAME).unwrap_or_else(|| {
let llvm_void = ctx.ctx.void_type();
let llvm_i64 = ctx.ctx.i64_type();
let llvm_p0i8 = ctx.ctx.i8_type().ptr_type(AddressSpace::default());
let fn_type = llvm_void.fn_type(&[llvm_i64.into(), llvm_p0i8.into()], false);
ctx.module.add_function(FN_NAME, fn_type, None)
});
ctx.builder
.build_call(intrinsic_fn, &[size.into(), ptr.into()], "")
.map(CallSiteValue::try_as_basic_value)
.unwrap();
}
/// Invokes the [`llvm.stacksave`](https://llvm.org/docs/LangRef.html#llvm-stacksave-intrinsic) /// Invokes the [`llvm.stacksave`](https://llvm.org/docs/LangRef.html#llvm-stacksave-intrinsic)
/// intrinsic. /// intrinsic.
pub fn call_stacksave<'ctx>( pub fn call_stacksave<'ctx>(

View File

@ -7,7 +7,6 @@ use crate::{
typedef::{CallId, FuncArg, Type, TypeEnum, Unifier}, typedef::{CallId, FuncArg, Type, TypeEnum, Unifier},
}, },
}; };
use classes::NpArrayType;
use crossbeam::channel::{unbounded, Receiver, Sender}; use crossbeam::channel::{unbounded, Receiver, Sender};
use inkwell::{ use inkwell::{
attributes::{Attribute, AttributeLoc}, attributes::{Attribute, AttributeLoc},
@ -44,7 +43,6 @@ pub mod irrt;
pub mod llvm_intrinsics; pub mod llvm_intrinsics;
pub mod numpy; pub mod numpy;
pub mod stmt; pub mod stmt;
pub mod structure;
#[cfg(test)] #[cfg(test)]
mod test; mod test;
@ -478,14 +476,7 @@ fn get_llvm_type<'ctx, G: CodeGenerator + ?Sized>(
ctx, module, generator, unifier, top_level, type_cache, dtype, ctx, module, generator, unifier, top_level, type_cache, dtype,
); );
let ndarray_ty = NpArrayType { NDArrayType::new(generator, ctx, element_type).as_base_type().into()
size_type: generator.get_size_type(ctx),
elem_type: element_type,
};
ndarray_ty
.get_struct_type(ctx)
.ptr_type(AddressSpace::default())
.as_basic_type_enum()
} }
_ => unreachable!( _ => unreachable!(

View File

@ -2,11 +2,15 @@ use crate::{
codegen::{ codegen::{
classes::{ classes::{
ArrayLikeIndexer, ArrayLikeValue, ListType, ListValue, NDArrayType, NDArrayValue, ArrayLikeIndexer, ArrayLikeValue, ListType, ListValue, NDArrayType, NDArrayValue,
NpArrayType, ProxyType, ProxyValue, TypedArrayLikeAccessor, TypedArrayLikeAdapter, ProxyType, ProxyValue, TypedArrayLikeAccessor, TypedArrayLikeAdapter,
TypedArrayLikeMutator, UntypedArrayLikeAccessor, UntypedArrayLikeMutator, TypedArrayLikeMutator, UntypedArrayLikeAccessor, UntypedArrayLikeMutator,
}, },
expr::gen_binop_expr_with_values, expr::gen_binop_expr_with_values,
get_llvm_type, irrt, irrt::{
calculate_len_for_slice_range, call_ndarray_calc_broadcast,
call_ndarray_calc_broadcast_index, call_ndarray_calc_nd_indices,
call_ndarray_calc_size,
},
llvm_intrinsics::{self, call_memcpy_generic}, llvm_intrinsics::{self, call_memcpy_generic},
stmt::{gen_for_callback_incrementing, gen_for_range_callback, gen_if_else_expr_callback}, stmt::{gen_for_callback_incrementing, gen_for_range_callback, gen_if_else_expr_callback},
CodeGenContext, CodeGenerator, CodeGenContext, CodeGenerator,
@ -22,27 +26,14 @@ use crate::{
typedef::{FunSignature, Type, TypeEnum}, typedef::{FunSignature, Type, TypeEnum},
}, },
}; };
use inkwell::types::{AnyTypeEnum, BasicTypeEnum, PointerType};
use inkwell::{ use inkwell::{
types::BasicType, types::BasicType,
values::{BasicValueEnum, IntValue, PointerValue}, values::{BasicValueEnum, IntValue, PointerValue},
AddressSpace, IntPredicate, OptimizationLevel, AddressSpace, IntPredicate, OptimizationLevel,
}; };
use inkwell::{
types::{AnyTypeEnum, BasicTypeEnum, IntType, PointerType},
values::BasicValue,
};
use nac3parser::ast::{Operator, StrRef}; use nac3parser::ast::{Operator, StrRef};
use super::{
classes::NpArrayValue,
irrt::{
call_nac3_ndarray_deduce_ndims_after_slicing, call_nac3_ndarray_set_strides_by_shape,
call_nac3_ndarray_size, call_nac3_ndarray_subscript, get_irrt_ndarray_ptr_type,
get_opaque_uint8_ptr_type, IrrtNDSliceType, NDSlice,
},
stmt::gen_return,
};
// /// Creates an uninitialized `NDArray` instance. // /// Creates an uninitialized `NDArray` instance.
// fn create_ndarray_uninitialized<'ctx, G: CodeGenerator + ?Sized>( // fn create_ndarray_uninitialized<'ctx, G: CodeGenerator + ?Sized>(
// generator: &mut G, // generator: &mut G,
@ -2024,499 +2015,3 @@ use super::{
// Ok(()) // Ok(())
// } // }
// //
fn simple_assert<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
cond: IntValue<'ctx>,
msg: &str,
) where
G: CodeGenerator + ?Sized,
{
let mut full_msg = String::from("simple_assert failed: ");
full_msg.push_str(msg);
ctx.make_assert(
generator,
cond,
"0:ValueError",
full_msg.as_str(),
[None, None, None],
ctx.current_loc,
);
}
fn copy_array_slice<'ctx, G, Src, Dst>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
dst: Dst,
src: Src,
) where
G: CodeGenerator + ?Sized,
Dst: TypedArrayLikeMutator<'ctx, IntType<'ctx>>,
Src: TypedArrayLikeAccessor<'ctx, IntType<'ctx>>,
{
// Sanity check
let len_match = ctx
.builder
.build_int_compare(
IntPredicate::EQ,
src.size(ctx, generator),
dst.size(ctx, generator),
"len_match",
)
.unwrap();
simple_assert(generator, ctx, len_match, "copy_array_slice length mismatched");
let size_type = generator.get_size_type(ctx.ctx);
let init_val = size_type.const_zero();
let max_val = (dst.size(ctx, generator), false);
let incr_val = size_type.const_int(1, false);
gen_for_callback_incrementing(
generator,
ctx,
init_val,
max_val,
|generator, ctx, _hooks, idx| {
let value = src.get_typed(ctx, generator, &idx, Some("copy_array_slice.tmp"));
dst.set_typed(ctx, generator, &idx, value);
Ok(())
},
incr_val,
)
.unwrap();
}
fn alloca_ndarray<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_type: BasicTypeEnum<'ctx>,
ndims: IntValue<'ctx>,
name: &str,
) -> Result<NpArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
{
let size_type = generator.get_size_type(ctx.ctx);
let ndarray_ty = NpArrayType { size_type, elem_type };
let ndarray = ndarray_ty.alloca(ctx, ndims, name);
Ok(ndarray)
}
pub struct Producer<'ctx, G: CodeGenerator + ?Sized, T> {
pub count: IntValue<'ctx>,
pub write_to_slice: Box<
dyn Fn(
&mut G,
&mut CodeGenContext<'ctx, '_>,
&TypedArrayLikeAdapter<'ctx, T>,
) -> Result<(), String>
+ 'ctx,
>,
}
/// TODO: UPDATE DOCUMENTATION
/// LLVM-typed implementation for generating a [`Producer`] that sets a list of ints.
///
/// * `elem_ty` - The element type of the `NDArray`.
/// * `shape` - The `shape` parameter used to construct the `NDArray`.
///
/// ### Notes on `shape`
///
/// Just like numpy, the `shape` argument can be:
/// 1. A list of `int32`; e.g., `np.empty([600, 800, 3])`
/// 2. A tuple of `int32`; e.g., `np.empty((600, 800, 3))`
/// 3. A scalar `int32`; e.g., `np.empty(3)`, this is functionally equivalent to `np.empty([3])`
///
/// See also [`typecheck::type_inferencer::fold_numpy_function_call_shape_argument`] to
/// learn how `shape` gets from being a Python user expression to here.
fn parse_input_shape_arg<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
) -> Result<Producer<'ctx, G, IntValue<'ctx>>, String>
where
G: CodeGenerator + ?Sized,
{
let size_type = generator.get_size_type(ctx.ctx);
match &*ctx.unifier.get_ty(shape_ty) {
TypeEnum::TObj { obj_id, .. }
if *obj_id == ctx.primitives.list.obj_id(&ctx.unifier).unwrap() =>
{
// 1. A list of ints; e.g., `np.empty([600, 800, 3])`
// A list has to be a PointerValue
let shape_list = ListValue::from_ptr_val(shape.into_pointer_value(), size_type, None);
// Create `Producer`
let ndims = shape_list.load_size(ctx, Some("count"));
Ok(Producer {
count: ndims,
write_to_slice: Box::new(move |ctx, generator, dst_slice| {
// Basically iterate through the list and write to `dst_slice` accordingly
let init_val = size_type.const_zero();
let max_val = (ndims, false);
let incr_val = size_type.const_int(1, false);
gen_for_callback_incrementing(
ctx,
generator,
init_val,
max_val,
|generator, ctx, _hooks, idx| {
// Get the dimension at `idx`
let dim =
shape_list.data().get(ctx, generator, &idx, None).into_int_value();
// Cast `dim` to SizeT
let dim = ctx
.builder
.build_int_s_extend_or_bit_cast(dim, size_type, "dim_casted")
.unwrap();
// Write
dst_slice.set_typed(ctx, generator, &idx, dim);
Ok(())
},
incr_val,
)?;
Ok(())
}),
})
}
TypeEnum::TTuple { ty: tuple_types } => {
// 2. A tuple of ints; e.g., `np.empty((600, 800, 3))`
// Get the length/size of the tuple, which also happens to be the value of `ndims`.
let ndims = tuple_types.len();
// A tuple has to be a StructValue
// Read [`codegen::expr::gen_expr`] to see how `nac3core` translates a Python tuple into LLVM.
let shape_tuple = shape.into_struct_value();
Ok(Producer {
count: size_type.const_int(ndims as u64, false),
write_to_slice: Box::new(move |generator, ctx, dst_slice| {
for dim_i in 0..ndims {
// Get the dimension at `dim_i`
let dim = ctx
.builder
.build_extract_value(
shape_tuple,
dim_i as u32,
format!("dim{dim_i}").as_str(),
)
.unwrap()
.into_int_value();
// Cast `dim` to SizeT
let dim = ctx
.builder
.build_int_s_extend_or_bit_cast(dim, size_type, "dim_casted")
.unwrap();
// Write
dst_slice.set_typed(
ctx,
generator,
&size_type.const_int(dim_i as u64, false),
dim,
);
}
Ok(())
}),
})
}
TypeEnum::TObj { obj_id, .. }
if *obj_id == ctx.primitives.int32.obj_id(&ctx.unifier).unwrap() =>
{
// 3. A scalar int; e.g., `np.empty(3)`, this is functionally equivalent to `np.empty([3])`
// The value has to be an integer
let shape_int = shape.into_int_value();
Ok(Producer {
count: size_type.const_int(1, false),
write_to_slice: Box::new(move |generator, ctx, dst_slice| {
// Only index 0 is set with the input value
let dim_i = size_type.const_zero();
// Cast `shape_int` to SizeT
let dim = ctx
.builder
.build_int_s_extend_or_bit_cast(shape_int, size_type, "dim_casted")
.unwrap();
// Write
dst_slice.set_typed(ctx, generator, &dim_i, dim);
Ok(())
}),
})
}
_ => panic!("parse_input_shape_arg encountered unknown type"),
}
}
enum NDArrayInitMode<'ctx, G: CodeGenerator + ?Sized> {
SetNDim { ndim: IntValue<'ctx> },
SetShape { shape: Producer<'ctx, G, IntValue<'ctx>> },
SetShapeAndAllocaData { shape: Producer<'ctx, G, IntValue<'ctx>> },
}
/// TODO: DOCUMENT ME
fn alloca_ndarray_and_init<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_type: BasicTypeEnum<'ctx>,
init_mode: NDArrayInitMode<'ctx, G>,
name: &str,
) -> Result<NpArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
{
// It is implemented verbosely in order to make the initialization modes super clear in their intent.
match init_mode {
NDArrayInitMode::SetNDim { ndim: ndims } => {
let ndarray = alloca_ndarray(generator, ctx, elem_type, ndims, name)?;
Ok(ndarray)
}
NDArrayInitMode::SetShape { shape } => {
let ndims = shape.count;
let ndarray = alloca_ndarray(generator, ctx, elem_type, ndims, name)?;
// Fill `ndarray.shape` with `shape_producer`
(shape.write_to_slice)(generator, ctx, &ndarray.shape_slice(ctx));
Ok(ndarray)
}
NDArrayInitMode::SetShapeAndAllocaData { shape } => {
let ndims = shape.count;
let ndarray = alloca_ndarray(generator, ctx, elem_type, ndims, name)?;
// Fill `ndarray.shape` with `shape_producer`
(shape.write_to_slice)(generator, ctx, &ndarray.shape_slice(ctx));
// Now we populate `ndarray.data` by alloca-ing.
// But first, we need to know the size of the ndarray to know how many elements to alloca
// NOTE: calculating the size of an ndarray requires `ndarray.shape` to be set.
let ndarray_size = call_nac3_ndarray_size(ctx, ndarray);
// Alloca `data` and assign it to `ndarray.data`
let data_ptr = ctx.builder.build_array_alloca(elem_type, ndarray_size, "data").unwrap();
// We also have to cast `data_ptr` to `uint8_t*` because that is what `NDArray` has.
let data_ptr = ctx
.builder
.build_pointer_cast(data_ptr, get_opaque_uint8_ptr_type(ctx.ctx), "data_casted")
.unwrap();
ndarray.store_data(ctx, data_ptr);
// Finally, do `set_strides_by_shape`
// Check out https://ajcr.net/stride-guide-part-1/ to see what numpy "strides" are.
call_nac3_ndarray_set_strides_by_shape(ctx, ndarray);
Ok(ndarray)
}
}
}
pub fn get_ndarray_first_element<'ctx>(
ctx: &CodeGenContext<'ctx, '_>,
ndarray: NpArrayValue<'ctx>,
name: &str,
) -> BasicValueEnum<'ctx> {
let data = ndarray.load_data(ctx);
// Cast `data` to the actual element the `subndarray` holds
// otherwise `subndarray.data` is just a bunch of `uint8_t*`
let data = ctx
.builder
.build_pointer_cast(
data,
ndarray.ty.elem_type.ptr_type(AddressSpace::default()),
"data_casted",
)
.unwrap();
// Load the element
ctx.builder.build_load(data, name).unwrap()
}
pub fn call_ndarray_subscript_impl<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
ndarray: NpArrayValue<'ctx>,
ndslices: &Vec<&NDSlice<'ctx>>,
) -> Result<NpArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
{
// First we will calculate the correct ndims of the dst_ndarray
// Then allocate for dst_ndarray (A known `ndims` value is required for this)
// Finally do call the IRRT function that actually does subscript
let size_type = ndarray.ty.size_type;
// Prepare the argument `ndims`
let ndims = ndarray.load_ndims(ctx);
// Prepare the argument `num_slices` in LLVM - which conveniently is simply `ndslices.len()`
let num_slices = size_type.const_int(ndslices.len() as u64, false);
// Prepare the argument `slices`
let ndslices_ptr = IrrtNDSliceType::alloca_ndslices(ctx, ndslices);
// Get `dst_ndims`
let dst_ndims = call_nac3_ndarray_deduce_ndims_after_slicing(
ctx,
size_type,
ndims,
num_slices,
ndslices_ptr,
);
// Allocate `dst_ndarray`
let dst_ndarray = alloca_ndarray_and_init(
generator,
ctx,
ndarray.ty.elem_type,
NDArrayInitMode::SetNDim { ndim: dst_ndims },
"subndarray",
)?;
call_nac3_ndarray_subscript(ctx, ndarray, num_slices, ndslices_ptr, dst_ndarray);
Ok(dst_ndarray)
}
/// LLVM-typed implementation for generating the implementation for constructing an empty `NDArray`.
fn call_ndarray_empty_impl<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
name: &str,
) -> Result<NpArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
{
let elem_type = ctx.get_llvm_type(generator, elem_ty);
let shape = parse_input_shape_arg(generator, ctx, shape, shape_ty)?;
let ndarray = alloca_ndarray_and_init(
generator,
ctx,
elem_type,
NDArrayInitMode::SetShapeAndAllocaData { shape },
name,
)?;
Ok(ndarray)
}
fn call_ndarray_fill_impl<'ctx, G>(
generator: &mut G,
ctx: &mut CodeGenContext<'ctx, '_>,
elem_ty: Type,
shape: BasicValueEnum<'ctx>,
shape_ty: Type,
fill_value: BasicValueEnum<'ctx>,
name: &str,
) -> Result<NpArrayValue<'ctx>, String>
where
G: CodeGenerator + ?Sized,
{
let ndarray = call_ndarray_empty_impl(generator, ctx, elem_ty, shape, shape_ty, name)?;
irrt::call_nac3_ndarray_fill_generic(ctx, ndarray, fill_value);
Ok(ndarray)
}
/// Generates LLVM IR for `np.empty`.
pub fn gen_ndarray_empty<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
let ndarray = call_ndarray_empty_impl(
generator,
context,
context.primitives.float,
shape,
shape_ty,
"empty_ndarray",
)?;
Ok(ndarray.ptr)
}
/// Generates LLVM IR for `np.zeros`.
pub fn gen_ndarray_zeros<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
// NOTE: Currently nac3's `np.zeros` is always `float64`.
let float64_ty = context.primitives.float;
let float64_llvm_type = context.get_llvm_type(generator, float64_ty).into_float_type();
let ndarray = call_ndarray_fill_impl(
generator,
context,
float64_ty, // `elem_ty` is always `float64`
shape,
shape_ty,
float64_llvm_type.const_zero().as_basic_value_enum(),
"zeros_ndarray",
)?;
Ok(ndarray.ptr)
}
/// Generates LLVM IR for `np.ones`.
pub fn gen_ndarray_ones<'ctx>(
context: &mut CodeGenContext<'ctx, '_>,
obj: &Option<(Type, ValueEnum<'ctx>)>,
fun: (&FunSignature, DefinitionId),
args: &[(Option<StrRef>, ValueEnum<'ctx>)],
generator: &mut dyn CodeGenerator,
) -> Result<PointerValue<'ctx>, String> {
assert!(obj.is_none());
assert_eq!(args.len(), 1);
// Parse arguments
let shape_ty = fun.0.args[0].ty;
let shape = args[0].1.clone().to_basic_value_enum(context, generator, shape_ty)?;
// Implementation
// NOTE: Currently nac3's `np.ones` is always `float64`.
let float64_ty = context.primitives.float;
let float64_llvm_type = context.get_llvm_type(generator, float64_ty).into_float_type();
let ndarray = call_ndarray_fill_impl(
generator,
context,
float64_ty, // `elem_ty` is always `float64`
shape,
shape_ty,
float64_llvm_type.const_float(1.0).as_basic_value_enum(),
"ones_ndarray",
)?;
Ok(ndarray.ptr)
}

View File

@ -1,318 +0,0 @@
use std::marker::PhantomData;
use inkwell::{
context::Context,
types::{BasicType, BasicTypeEnum, IntType, PointerType, StructType},
values::{BasicValue, BasicValueEnum, IntValue, PointerValue},
AddressSpace,
};
use super::CodeGenContext;
#[derive(Debug, Clone, Copy)]
pub struct FieldInfo {
gep_index: u32,
name: &'static str,
}
impl FieldInfo {
pub fn llvm_gep<'ctx>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
struct_ptr: PointerValue<'ctx>,
) -> PointerValue<'ctx> {
let index_type = ctx.ctx.i32_type(); // TODO: I think I'm not supposed to *just* use i32 for GEP like that
unsafe {
ctx.builder
.build_in_bounds_gep(
struct_ptr,
&[index_type.const_zero(), index_type.const_int(self.gep_index as u64, false)],
self.name,
)
.unwrap()
}
}
pub fn llvm_load<'ctx>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
struct_ptr: PointerValue<'ctx>,
) -> BasicValueEnum<'ctx> {
// We will use `self.name` as the LLVM label for debugging purposes
ctx.builder.build_load(self.llvm_gep(ctx, struct_ptr), self.name).unwrap()
}
pub fn llvm_store<'ctx>(
&self,
ctx: &CodeGenContext<'ctx, '_>,
struct_ptr: PointerValue<'ctx>,
value: BasicValueEnum<'ctx>,
) {
ctx.builder.build_store(self.llvm_gep(ctx, struct_ptr), value).unwrap();
}
}
pub struct Object<'ctx, T> {
pub ty: T,
pub ptr: PointerValue<'ctx>,
}
pub struct Field<'ctx, T: CustomType<'ctx>> {
pub info: FieldInfo,
pub ty: T,
_phantom: PhantomData<&'ctx ()>,
}
pub struct FieldCreator<'ctx> {
pub ctx: &'ctx Context,
struct_name: &'ctx str,
gep_index_counter: u32,
fields: Vec<(FieldInfo, BasicTypeEnum<'ctx>)>,
}
impl<'ctx> FieldCreator<'ctx> {
pub fn new(ctx: &'ctx Context, struct_name: &'ctx str) -> Self {
FieldCreator { ctx, struct_name, gep_index_counter: 0, fields: Vec::new() }
}
fn next_gep_index(&mut self) -> u32 {
let index = self.gep_index_counter;
self.gep_index_counter += 1;
index
}
fn get_struct_field_types(&self) -> Vec<BasicTypeEnum<'ctx>> {
self.fields.iter().map(|x| x.1.clone()).collect()
}
pub fn add_field<T: CustomType<'ctx>>(&mut self, name: &'static str, ty: T) -> Field<'ctx, T> {
let gep_index = self.next_gep_index();
let field_type = ty.llvm_basic_type_enum(self.ctx);
let field_info = FieldInfo { gep_index, name };
let field = Field { info: field_info, ty, _phantom: PhantomData };
self.fields.push((field_info.clone(), field_type));
field
}
fn num_fields(&self) -> u32 {
self.fields.len() as u32 // casted to u32 because that is what inkwell returns
}
}
pub trait CustomType<'ctx>: Clone {
type Value;
fn llvm_basic_type_enum(&self, ctx: &'ctx Context) -> BasicTypeEnum<'ctx>;
fn llvm_field_load(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
) -> Self::Value;
fn llvm_field_store(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
value: &Self::Value,
);
}
#[derive(Debug, Clone, Copy)]
pub struct IntType2<'ctx>(pub IntType<'ctx>);
impl<'ctx> CustomType<'ctx> for IntType2<'ctx> {
type Value = IntValue<'ctx>;
fn llvm_basic_type_enum(&self, ctx: &'ctx Context) -> BasicTypeEnum<'ctx> {
self.0.as_basic_type_enum()
}
fn llvm_field_load(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
) -> Self::Value {
let int_value = field.llvm_load(ctx, struct_ptr).into_int_value();
assert_eq!(int_value.get_type().get_bit_width(), self.0.get_bit_width());
int_value
}
fn llvm_field_store(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
int_value: &Self::Value,
) {
assert_eq!(int_value.get_type().get_bit_width(), self.0.get_bit_width());
field.llvm_store(ctx, struct_ptr, int_value.as_basic_value_enum());
}
}
#[derive(Debug, Clone, Copy)]
pub struct PointerType2<'ctx>(pub PointerType<'ctx>);
impl<'ctx> CustomType<'ctx> for PointerType2<'ctx> {
type Value = PointerValue<'ctx>;
fn llvm_basic_type_enum(&self, ctx: &'ctx Context) -> BasicTypeEnum<'ctx> {
self.0.as_basic_type_enum()
}
fn llvm_field_load(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
) -> Self::Value {
field.llvm_load(ctx, struct_ptr).into_pointer_value()
}
fn llvm_field_store(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
pointer_value: &Self::Value,
) {
field.llvm_store(ctx, struct_ptr, pointer_value.as_basic_value_enum());
}
}
#[derive(Debug, Clone, Copy)]
pub struct PointingArrayType<'ctx, ElementType: CustomType<'ctx>> {
pub element_type: ElementType,
_phantom: PhantomData<&'ctx ()>,
}
impl<'ctx, ElementType: CustomType<'ctx>> PointingArrayType<'ctx, ElementType> {
pub fn new(element_type: ElementType) -> Self {
PointingArrayType { element_type, _phantom: PhantomData }
}
}
impl<'ctx, Element: CustomType<'ctx>> CustomType<'ctx> for PointingArrayType<'ctx, Element> {
type Value = Object<'ctx, Self>;
fn llvm_basic_type_enum(&self, ctx: &'ctx Context) -> BasicTypeEnum<'ctx> {
// Element*
self.element_type
.llvm_basic_type_enum(ctx)
.ptr_type(AddressSpace::default())
.as_basic_type_enum()
}
fn llvm_field_load(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
) -> Self::Value {
// Remember that it is just a pointer
Object { ty: self.clone(), ptr: field.llvm_load(ctx, struct_ptr).into_pointer_value() }
}
fn llvm_field_store(
&self,
ctx: &CodeGenContext<'ctx, '_>,
field: FieldInfo,
struct_ptr: PointerValue<'ctx>,
value: &Self::Value,
) {
// Remember that it is just a pointer
todo!()
}
}
pub fn check_basic_types_match<'ctx, A, B>(expected: A, got: B) -> Result<(), String>
where
A: BasicType<'ctx>,
B: BasicType<'ctx>,
{
let expected = expected.as_basic_type_enum();
let got = got.as_basic_type_enum();
// Put those logic into here,
// otherwise there is always a fallback reporting on any kind of mismatch
match (expected, got) {
(BasicTypeEnum::IntType(expected), BasicTypeEnum::IntType(got)) => {
if expected.get_bit_width() != got.get_bit_width() {
return Err(format!(
"Expected IntType ({expected}-bit(s)), got IntType ({got}-bit(s))"
));
}
}
(expected, got) => {
if expected != got {
return Err(format!("Expected {expected}, got {got}"));
}
}
}
Ok(())
}
pub trait CustomStructType<'ctx> {
type Fields;
fn llvm_struct_name() -> &'static str;
fn add_fields_to(&self, creator: &mut FieldCreator<'ctx>) -> Self::Fields;
fn fields(&self, ctx: &'ctx Context) -> Self::Fields {
let mut creator = FieldCreator::new(ctx, Self::llvm_struct_name());
let fields = self.add_fields_to(&mut creator);
fields
}
fn llvm_struct_type(&self, ctx: &'ctx Context) -> StructType<'ctx> {
let mut creator = FieldCreator::new(ctx, Self::llvm_struct_name());
self.add_fields_to(&mut creator);
ctx.struct_type(&creator.get_struct_field_types(), false)
}
fn check_struct_type(
&self,
ctx: &'ctx Context,
scrutinee: StructType<'ctx>,
) -> Result<(), String> {
let mut creator = FieldCreator::new(ctx, Self::llvm_struct_name());
self.add_fields_to(&mut creator);
// Check scrutinee's number of struct fields
let expected_field_count = creator.num_fields();
let got_field_count = scrutinee.count_fields();
if got_field_count != expected_field_count {
return Err(format!(
"Expected {expected_count} field(s) in `{struct_name}` type, got {got_count}",
struct_name = Self::llvm_struct_name(),
expected_count = expected_field_count,
got_count = got_field_count,
));
}
// Check the scrutinee's field types
for (field_info, expected_field_ty) in creator.fields {
let got_field_ty = scrutinee.get_field_type_at_index(field_info.gep_index).unwrap();
if let Err(field_err) = check_basic_types_match(expected_field_ty, got_field_ty) {
return Err(format!(
"Field GEP index {gep_index} does not match the expected type of ({struct_name}::{field_name}): {field_err}",
gep_index = field_info.gep_index,
struct_name = Self::llvm_struct_name(),
field_name = field_info.name,
));
}
}
// Done
Ok(())
}
}

View File

@ -438,15 +438,14 @@ fn test_classes_range_type_new() {
assert!(RangeType::is_type(llvm_range.as_base_type()).is_ok()); assert!(RangeType::is_type(llvm_range.as_base_type()).is_ok());
} }
// #[test] #[test]
// fn test_classes_ndarray_type_new() { fn test_classes_ndarray_type_new() {
// let ctx = inkwell::context::Context::create(); let ctx = inkwell::context::Context::create();
// let generator = DefaultCodeGenerator::new(String::new(), 64); let generator = DefaultCodeGenerator::new(String::new(), 64);
//
// let llvm_i32 = ctx.i32_type(); let llvm_i32 = ctx.i32_type();
// let llvm_usize = generator.get_size_type(&ctx); let llvm_usize = generator.get_size_type(&ctx);
//
// let llvm_ndarray = NDArrayType::new(&generator, &ctx, llvm_i32.into()); let llvm_ndarray = NDArrayType::new(&generator, &ctx, llvm_i32.into());
// assert!(NDArrayType::is_type(llvm_ndarray.as_base_type(), llvm_usize).is_ok()); assert!(NDArrayType::is_type(llvm_ndarray.as_base_type(), llvm_usize).is_ok());
// } }
//

View File

@ -7,7 +7,6 @@
)] )]
#![warn(clippy::pedantic)] #![warn(clippy::pedantic)]
#![allow( #![allow(
unused,
dead_code, dead_code,
clippy::cast_possible_truncation, clippy::cast_possible_truncation,
clippy::cast_sign_loss, clippy::cast_sign_loss,
@ -24,4 +23,4 @@ pub mod codegen;
pub mod symbol_resolver; pub mod symbol_resolver;
pub mod toplevel; pub mod toplevel;
pub mod typecheck; pub mod typecheck;
pub mod util; pub mod util;

View File

@ -1,7 +1,6 @@
use std::iter::once; use std::iter::once;
use crate::util::SizeVariant; use crate::util::SizeVariant;
use classes::NpArrayType;
use helper::{debug_assert_prim_is_allowed, make_exception_fields, PrimDefDetails}; use helper::{debug_assert_prim_is_allowed, make_exception_fields, PrimDefDetails};
use indexmap::IndexMap; use indexmap::IndexMap;
use inkwell::{ use inkwell::{
@ -1194,13 +1193,14 @@ impl<'a> BuiltinBuilder<'a> {
self.ndarray_float, self.ndarray_float,
&[(self.ndarray_factory_fn_shape_arg_tvar.ty, "shape")], &[(self.ndarray_factory_fn_shape_arg_tvar.ty, "shape")],
Box::new(move |ctx, obj, fun, args, generator| { Box::new(move |ctx, obj, fun, args, generator| {
let func = match prim { todo!()
PrimDef::FunNpNDArray | PrimDef::FunNpEmpty => gen_ndarray_empty, // let func = match prim {
PrimDef::FunNpZeros => gen_ndarray_zeros, // PrimDef::FunNpNDArray | PrimDef::FunNpEmpty => gen_ndarray_empty,
PrimDef::FunNpOnes => gen_ndarray_ones, // gen_ndarray_ones, // PrimDef::FunNpZeros => gen_ndarray_zeros,
_ => unreachable!(), // PrimDef::FunNpOnes => gen_ndarray_ones,
}; // _ => unreachable!(),
func(ctx, &obj, fun, &args, generator).map(|val| Some(val.as_basic_value_enum())) // };
// func(ctx, &obj, fun, &args, generator).map(|val| Some(val.as_basic_value_enum()))
}), }),
) )
} }
@ -1461,65 +1461,51 @@ impl<'a> BuiltinBuilder<'a> {
} }
} }
TypeEnum::TObj { obj_id, .. } if *obj_id == PrimDef::NDArray.id() => { TypeEnum::TObj { obj_id, .. } if *obj_id == PrimDef::NDArray.id() => {
// TODO: Check is unsized and throw error if so let llvm_i32 = ctx.ctx.i32_type();
let llvm_usize = generator.get_size_type(ctx.ctx);
// Parse `arg` let arg = NDArrayValue::from_ptr_val(
let ndarray_ptr = arg.into_pointer_value(); // It has to be an ndarray arg.into_pointer_value(),
llvm_usize,
None,
);
let size_type = generator.get_size_type(ctx.ctx); let ndims = arg.dim_sizes().size(ctx, generator);
let ndarray_ty = NpArrayType::new_opaque_elem(ctx.ctx, size_type); // We don't need to care about the element type - we only want the shape ctx.make_assert(
let ndarray = ndarray_ty.value_from_ptr(ctx.ctx, ndarray_ptr); generator,
ctx.builder
.build_int_compare(
IntPredicate::NE,
ndims,
llvm_usize.const_zero(),
"",
)
.unwrap(),
"0:TypeError",
&format!("{name}() of unsized object", name = prim.name()),
[None, None, None],
ctx.current_loc,
);
let result = call_nac3_len(ctx, ndarray).as_basic_value_enum(); let len = unsafe {
Some(result) arg.dim_sizes().get_typed_unchecked(
ctx,
generator,
&llvm_usize.const_zero(),
None,
)
};
// Some(.as_basic_value_enum()) if len.get_type().get_bit_width() == 32 {
Some(len.into())
// let llvm_i32 = ctx.ctx.i32_type(); } else {
// let llvm_usize = generator.get_size_type(ctx.ctx); Some(
ctx.builder
// let arg = NDArrayValue::from_ptr_val( .build_int_truncate(len, llvm_i32, "len")
// arg.into_pointer_value(), .map(Into::into)
// llvm_usize, .unwrap(),
// None, )
// ); }
// let ndims = arg.dim_sizes().size(ctx, generator);
// ctx.make_assert(
// generator,
// ctx.builder
// .build_int_compare(
// IntPredicate::NE,
// ndims,
// llvm_usize.const_zero(),
// "",
// )
// .unwrap(),
// "0:TypeError",
// &format!("{name}() of unsized object", name = prim.name()),
// [None, None, None],
// ctx.current_loc,
// );
// let len = unsafe {
// arg.dim_sizes().get_typed_unchecked(
// ctx,
// generator,
// &llvm_usize.const_zero(),
// None,
// )
// };
// if len.get_type().get_bit_width() == 32 {
// Some(len.into())
// } else {
// Some(
// ctx.builder
// .build_int_truncate(len, llvm_i32, "len")
// .map(Into::into)
// .unwrap(),
// )
// }
} }
_ => unreachable!(), _ => unreachable!(),
} }

View File

@ -1,5 +0,0 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum SizeVariant {
Bits32,
Bits64,
}

View File

@ -1,18 +0,0 @@
@extern
def output_float64(x: float):
...
def output_ndarray_float_1(n: ndarray[float, Literal[1]]):
for i in range(len(n)):
output_float64(n[i])
def output_ndarray_float_2(n: ndarray[float, Literal[2]]):
for r in range(len(n)):
for c in range(len(n[r])):
output_float64(n[r][c])
def run() -> int32:
hello = np_ones((3, 4))
# output_float64(hello[2, 3])
output_ndarray_float_1(hello[::-2, 2])
return 0

View File

@ -449,11 +449,6 @@ fn main() {
.create_target_machine(llvm_options.opt_level) .create_target_machine(llvm_options.opt_level)
.expect("couldn't create target machine"); .expect("couldn't create target machine");
// Debug print if DEBUG_STANDALONE_DUMP_IR is defined
if std::env::var("DEBUG_STANDALONE_DUMP_IR").is_ok() {
main.print_to_file("standalone.ll").unwrap();
}
let pass_options = PassBuilderOptions::create(); let pass_options = PassBuilderOptions::create();
pass_options.set_merge_functions(true); pass_options.set_merge_functions(true);
let passes = format!("default<O{}>", opt_level as u32); let passes = format!("default<O{}>", opt_level as u32);