From 4c655865e5d9af83a98c137609b01972f4e51beb Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 18 Oct 2021 16:52:19 +0100 Subject: Begin work on matrix type --- src/check_expr.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 513144f11..85f2eeb23 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -6207,6 +6207,17 @@ bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, } o->type = t->EnumeratedArray.elem; return true; + + case Type_Matrix: + *max_count = t->Matrix.column_count; + if (indirection) { + o->mode = Addressing_Variable; + } else if (o->mode != Addressing_Variable && + o->mode != Addressing_Constant) { + o->mode = Addressing_Value; + } + o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count); + return true; case Type_Slice: o->type = t->Slice.elem; @@ -6505,6 +6516,11 @@ void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, } +void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) { + error(node, "TODO: matrix index expressions"); +} + + ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) { u32 prev_state_flags = c->state_flags; defer (c->state_flags = prev_state_flags); @@ -8202,6 +8218,8 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type // Okay } else if (is_type_relative_slice(t)) { // Okay + } else if (is_type_matrix(t)) { + // Okay } else { valid = false; } @@ -8266,10 +8284,14 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type } } } + + if (type_hint != nullptr && is_type_matrix(t)) { + // TODO(bill): allow matrix columns to be assignable to other types which are the same internally + // if a type hint exists + } + case_end; - - case_ast_node(se, SliceExpr, node); check_expr(c, o, se->expr); node->viral_state_flags |= se->expr->viral_state_flags; @@ -8442,7 +8464,12 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type } case_end; - + + case_ast_node(mie, MatrixIndexExpr, node); + check_matrix_index_expr(c, o, node, type_hint); + o->expr = node; + return Expr_Expr; + case_end; case_ast_node(ce, CallExpr, node); return check_call_expr(c, o, node, ce->proc, ce->args, ce->inlining, type_hint); @@ -8952,6 +8979,15 @@ gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) { str = gb_string_append_rune(str, ']'); case_end; + case_ast_node(mie, MatrixIndexExpr, node); + str = write_expr_to_string(str, mie->expr, shorthand); + str = gb_string_append_rune(str, '['); + str = write_expr_to_string(str, mie->row_index, shorthand); + str = gb_string_appendc(str, "; "); + str = write_expr_to_string(str, mie->column_index, shorthand); + str = gb_string_append_rune(str, ']'); + case_end; + case_ast_node(e, Ellipsis, node); str = gb_string_appendc(str, ".."); str = write_expr_to_string(str, e->expr, shorthand); @@ -9023,6 +9059,16 @@ gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) { str = gb_string_append_rune(str, ']'); str = write_expr_to_string(str, mt->value, shorthand); case_end; + + case_ast_node(mt, MatrixType, node); + str = gb_string_append_rune(str, '['); + str = write_expr_to_string(str, mt->row_count, shorthand); + str = gb_string_appendc(str, "; "); + str = write_expr_to_string(str, mt->column_count, shorthand); + str = gb_string_append_rune(str, ']'); + str = write_expr_to_string(str, mt->elem, shorthand); + case_end; + case_ast_node(f, Field, node); if (f->flags&FieldFlag_using) { -- cgit v1.2.3 From ba331024af2f5074125442e91dda6c8e63324c8f Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 18 Oct 2021 18:16:52 +0100 Subject: Very basic matrix support in backend --- core/fmt/fmt.odin | 35 +++++++++- src/check_expr.cpp | 153 ++++++++++++++++++++++++++++++++++++++++++- src/checker.cpp | 8 +++ src/llvm_backend.hpp | 4 ++ src/llvm_backend_const.cpp | 28 ++++++++ src/llvm_backend_expr.cpp | 78 ++++++++++++++++++++++ src/llvm_backend_utility.cpp | 35 ++++++++++ src/types.cpp | 31 +++++++-- 8 files changed, 364 insertions(+), 8 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index cee00da23..804a29cab 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -1954,7 +1954,40 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { } case runtime.Type_Info_Matrix: - io.write_string(fi.writer, "[]") + reflect.write_type(fi.writer, type_info_of(v.id)) + io.write_byte(fi.writer, '{') + defer io.write_byte(fi.writer, '}') + + fi.indent += 1; defer fi.indent -= 1 + + if fi.hash { + io.write_byte(fi.writer, '\n') + // TODO(bill): Should this render it like in written form? e.g. tranposed + for col in 0.. 0 { io.write_string(fi.writer, ", ") } + + offset := row*info.elem_size + col*info.stride + + data := uintptr(v.data) + uintptr(offset) + fmt_arg(fi, any{rawptr(data), info.elem.id}, verb) + } + io.write_string(fi.writer, ";\n") + } + } else { + for col in 0.. 0 { io.write_string(fi.writer, "; ") } + for row in 0.. 0 { io.write_string(fi.writer, ", ") } + + offset := row*info.elem_size + col*info.stride + + data := uintptr(v.data) + uintptr(offset) + fmt_arg(fi, any{rawptr(data), info.elem.id}, verb) + } + } + } } } diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 85f2eeb23..9c12802d7 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -1400,8 +1400,9 @@ bool check_unary_op(CheckerContext *c, Operand *o, Token op) { } bool check_binary_op(CheckerContext *c, Operand *o, Token op) { + Type *main_type = o->type; // TODO(bill): Handle errors correctly - Type *type = base_type(core_array_type(o->type)); + Type *type = base_type(core_array_type(main_type)); Type *ct = core_type(type); switch (op.kind) { case Token_Sub: @@ -1414,10 +1415,15 @@ bool check_binary_op(CheckerContext *c, Operand *o, Token op) { } break; - case Token_Mul: case Token_Quo: - case Token_MulEq: case Token_QuoEq: + if (is_type_matrix(main_type)) { + error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string)); + return false; + } + /*fallthrough*/ + case Token_Mul: + case Token_MulEq: case Token_AddEq: if (is_type_bit_set(type)) { return true; @@ -1458,6 +1464,10 @@ bool check_binary_op(CheckerContext *c, Operand *o, Token op) { case Token_ModMod: case Token_ModEq: case Token_ModModEq: + if (is_type_matrix(main_type)) { + error(op, "Operator '%.*s' is only allowed with matrix types", LIT(op.string)); + return false; + } if (!is_type_integer(type)) { error(op, "Operator '%.*s' is only allowed with integers", LIT(op.string)); return false; @@ -2671,6 +2681,114 @@ bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type } +void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) { + if (!check_binary_op(c, x, op)) { + x->mode = Addressing_Invalid; + return; + } + + if (is_type_matrix(x->type)) { + Type *xt = base_type(x->type); + Type *yt = base_type(y->type); + GB_ASSERT(xt->kind == Type_Matrix); + if (op.kind == Token_Mul) { + if (yt->kind == Type_Matrix) { + if (!are_types_identical(xt->Matrix.elem, yt->Matrix.elem)) { + goto matrix_error; + } + + if (xt->Matrix.column_count != yt->Matrix.row_count) { + goto matrix_error; + } + x->mode = Addressing_Value; + x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, yt->Matrix.column_count); + goto matrix_success; + } else if (yt->kind == Type_Array) { + if (!are_types_identical(xt->Matrix.elem, yt->Array.elem)) { + goto matrix_error; + } + + if (xt->Matrix.column_count != yt->Array.count) { + goto matrix_error; + } + + // Treat arrays as column vectors + x->mode = Addressing_Value; + x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1); + goto matrix_success; + } + } + if (!are_types_identical(xt, yt)) { + goto matrix_error; + } + x->mode = Addressing_Value; + x->type = xt; + goto matrix_success; + } else { + Type *xt = base_type(x->type); + Type *yt = base_type(y->type); + GB_ASSERT(is_type_matrix(yt)); + GB_ASSERT(!is_type_matrix(xt)); + + if (op.kind == Token_Mul) { + // NOTE(bill): no need to handle the matrix case here since it should be handled above + if (xt->kind == Type_Array) { + if (!are_types_identical(yt->Matrix.elem, xt->Array.elem)) { + goto matrix_error; + } + + if (xt->Array.count != yt->Matrix.row_count) { + goto matrix_error; + } + + // Treat arrays as row vectors + x->mode = Addressing_Value; + x->type = alloc_type_matrix(xt->Matrix.elem, 1, xt->Matrix.column_count); + goto matrix_success; + } + } + if (!are_types_identical(xt, yt)) { + goto matrix_error; + } + x->mode = Addressing_Value; + x->type = xt; + goto matrix_success; + } + +matrix_success: + if (type_hint != nullptr) { + Type *th = base_type(type_hint); + if (are_types_identical(th, x->type)) { + x->type = type_hint; + } else if (x->type->kind == Type_Matrix && th->kind == Type_Array) { + Type *xt = x->type; + if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) { + // ignore + } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) { + x->type = type_hint; + } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) { + x->type = type_hint; + } + } + } + return; + + +matrix_error: + gbString xt = type_to_string(x->type); + gbString yt = type_to_string(y->type); + gbString expr_str = expr_to_string(x->expr); + error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xt, yt); + gb_string_free(expr_str); + gb_string_free(yt); + gb_string_free(xt); + x->type = t_invalid; + x->mode = Addressing_Invalid; + return; + +} + + void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint, bool use_lhs_as_type_hint=false) { GB_ASSERT(node->kind == Ast_BinaryExpr); Operand y_ = {}, *y = &y_; @@ -2874,6 +2992,12 @@ void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint x->type = y->type; return; } + if (is_type_matrix(x->type) || is_type_matrix(y->type)) { + check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint); + return; + } + + if (!are_types_identical(x->type, y->type)) { if (x->type != t_invalid && y->type != t_invalid) { @@ -3258,6 +3382,29 @@ void convert_to_typed(CheckerContext *c, Operand *operand, Type *target_type) { break; } + + case Type_Matrix: { + Type *elem = base_array_type(t); + if (check_is_assignable_to(c, operand, elem)) { + if (t->Matrix.row_count != t->Matrix.column_count) { + operand->mode = Addressing_Invalid; + begin_error_block(); + defer (end_error_block()); + + convert_untyped_error(c, operand, target_type); + error_line("\tNote: Only a square matrix types can be initialized with a scalar value\n"); + return; + } else { + operand->mode = Addressing_Value; + } + } else { + operand->mode = Addressing_Invalid; + convert_untyped_error(c, operand, target_type); + return; + } + break; + } + case Type_Union: if (!is_operand_nil(*operand) && !is_operand_undef(*operand)) { diff --git a/src/checker.cpp b/src/checker.cpp index 8711fdc0c..c0e6d47c0 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1659,6 +1659,10 @@ void add_type_info_type_internal(CheckerContext *c, Type *t) { add_type_info_type_internal(c, bt->RelativeSlice.slice_type); add_type_info_type_internal(c, bt->RelativeSlice.base_integer); break; + + case Type_Matrix: + add_type_info_type_internal(c, bt->Matrix.elem); + break; default: GB_PANIC("Unhandled type: %*.s %d", LIT(type_strings[bt->kind]), bt->kind); @@ -1870,6 +1874,10 @@ void add_min_dep_type_info(Checker *c, Type *t) { add_min_dep_type_info(c, bt->RelativeSlice.slice_type); add_min_dep_type_info(c, bt->RelativeSlice.base_integer); break; + + case Type_Matrix: + add_min_dep_type_info(c, bt->Matrix.elem); + break; default: GB_PANIC("Unhandled type: %*.s", LIT(type_strings[bt->kind])); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index ffb81f0e4..73ddad797 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -333,6 +333,10 @@ lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index); lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel); lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel); +lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column); +lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column); + + lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *end_type); void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block); diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index 68050e0ce..4cfcecdc3 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -512,6 +512,34 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc res.value = llvm_const_array(lb_type(m, elem), elems, cast(unsigned)count); return res; + } else if (is_type_matrix(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_Compound) { + i64 row = type->Matrix.row_count; + i64 column = type->Matrix.column_count; + GB_ASSERT(row == column); + + Type *elem = type->Matrix.elem; + + lbValue single_elem = lb_const_value(m, elem, value, allow_local); + single_elem.value = llvm_const_cast(single_elem.value, lb_type(m, elem)); + + i64 stride_bytes = matrix_type_stride(type); + i64 stride_elems = stride_bytes/type_size_of(elem); + + i64 total_elem_count = matrix_type_total_elems(type); + LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)total_elem_count); + for (i64 i = 0; i < row; i++) { + elems[i*stride_elems + i] = single_elem.value; + } + for (i64 i = 0; i < total_elem_count; i++) { + if (elems[i] == nullptr) { + elems[i] = LLVMConstNull(lb_type(m, elem)); + } + } + + res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)total_elem_count); + return res; } switch (value.kind) { diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index 3056952f6..6b7d90ec0 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -477,10 +477,72 @@ lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue r } +lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { + GB_ASSERT(is_type_matrix(lhs.type) || is_type_matrix(rhs.type)); + + Type *xt = base_type(lhs.type); + Type *yt = base_type(rhs.type); + + if (op == Token_Mul) { + if (xt->kind == Type_Matrix) { + if (yt->kind == Type_Matrix) { + GB_ASSERT(is_type_matrix(type)); + GB_ASSERT(xt->Matrix.column_count == yt->Matrix.row_count); + GB_ASSERT(are_types_identical(xt->Matrix.elem, yt->Matrix.elem)); + + Type *elem = xt->Matrix.elem; + + lbAddr res = lb_add_local_generated(p, type, true); + for (i64 i = 0; i < xt->Matrix.row_count; i++) { + for (i64 j = 0; j < yt->Matrix.column_count; j++) { + for (i64 k = 0; k < xt->Matrix.column_count; k++) { + lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j); + + lbValue a = lb_emit_matrix_ev(p, lhs, i, k); + lbValue b = lb_emit_matrix_ev(p, rhs, k, j); + lbValue c = lb_emit_arith(p, op, a, b, elem); + lbValue d = lb_emit_load(p, dst); + lbValue e = lb_emit_arith(p, Token_Add, d, c, elem); + lb_emit_store(p, dst, e); + + } + } + } + + return lb_addr_load(p, res); + } + } + + } else { + GB_ASSERT(are_types_identical(xt, yt)); + GB_ASSERT(xt->kind == Type_Matrix); + // element-wise arithmetic + // pretend it is an array + lbValue array_lhs = lhs; + lbValue array_rhs = rhs; + Type *array_type = alloc_type_array(xt->Matrix.elem, matrix_type_total_elems(xt)); + GB_ASSERT(type_size_of(array_type) == type_size_of(type)); + + array_lhs.type = array_type; + array_rhs.type = array_type; + + lbValue array = lb_emit_arith_array(p, op, array_lhs, array_rhs, type); + array.type = type; + return array; + } + + GB_PANIC("TODO: lb_emit_arith_matrix"); + + return {}; +} + + lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { if (is_type_array_like(lhs.type) || is_type_array_like(rhs.type)) { return lb_emit_arith_array(p, op, lhs, rhs, type); + } else if (is_type_matrix(lhs.type) || is_type_matrix(rhs.type)) { + return lb_emit_arith_matrix(p, op, lhs, rhs, type); } else if (is_type_complex(type)) { lhs = lb_emit_conv(p, lhs, type); rhs = lb_emit_conv(p, rhs, type); @@ -1417,6 +1479,22 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } return lb_addr_load(p, v); } + + if (is_type_matrix(dst) && !is_type_matrix(src)) { + GB_ASSERT(dst->Matrix.row_count == dst->Matrix.column_count); + + Type *elem = base_array_type(dst); + lbValue e = lb_emit_conv(p, value, elem); + lbAddr v = lb_add_local_generated(p, t, false); + for (i64 i = 0; i < dst->Matrix.row_count; i++) { + isize j = cast(isize)i; + lbValue ptr = lb_emit_matrix_epi(p, v.addr, j, j); + lb_emit_store(p, ptr, e); + } + + + return lb_addr_load(p, v); + } if (is_type_any(dst)) { if (is_type_untyped_nil(src)) { diff --git a/src/llvm_backend_utility.cpp b/src/llvm_backend_utility.cpp index 0531c62bb..1b41be2a3 100644 --- a/src/llvm_backend_utility.cpp +++ b/src/llvm_backend_utility.cpp @@ -1221,6 +1221,41 @@ lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) { return res; } +lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) { + Type *t = s.type; + GB_ASSERT(is_type_pointer(t)); + Type *st = base_type(type_deref(t)); + GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st)); + + Type *ptr = base_array_type(st); + + isize index = row*column; + GB_ASSERT(0 <= index); + + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(p->module, t_int), 0, false), + LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false), + }; + + lbValue res = {}; + if (lb_is_const(s)) { + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + } else { + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + } + res.type = alloc_type_pointer(ptr); + return res; +} + +lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) { + Type *st = base_type(s.type); + GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st)); + + lbValue value = lb_address_from_load_or_generate_local(p, s); + lbValue ptr = lb_emit_matrix_epi(p, value, row, column); + return lb_emit_load(p, ptr); +} + void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) { Type *t = lb_addr_type(slice); diff --git a/src/types.cpp b/src/types.cpp index 0313ade60..fd9b20c91 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1257,6 +1257,22 @@ i64 matrix_type_stride(Type *t) { return stride; } +i64 matrix_type_stride_in_elems(Type *t) { + t = base_type(t); + GB_ASSERT(t->kind == Type_Matrix); + i64 stride = matrix_type_stride(t); + return stride/gb_max(1, type_size_of(t->Matrix.elem)); +} + + +i64 matrix_type_total_elems(Type *t) { + t = base_type(t); + GB_ASSERT(t->kind == Type_Matrix); + i64 size = type_size_of(t); + i64 elem_size = type_size_of(t->Matrix.elem); + return size/gb_max(elem_size, 1); +} + bool is_type_dynamic_array(Type *t) { t = base_type(t); return t->kind == Type_DynamicArray; @@ -3174,17 +3190,17 @@ i64 type_align_of_internal(Type *t, TypePath *path) { case Type_Matrix: { Type *elem = t->Matrix.elem; - i64 row_count = t->Matrix.row_count; - // i64 column_count = t->Matrix.column_count; + i64 row_count = gb_max(t->Matrix.row_count, 1); + bool pop = type_path_push(path, elem); if (path->failure) { return FAILURE_ALIGNMENT; } + // elem align is used here rather than size as it make a little more sense i64 elem_align = type_align_of_internal(elem, path); if (pop) type_path_pop(path); - i64 align = gb_clamp(elem_align * row_count, elem_align, build_context.max_align); - + i64 align = gb_min(next_pow2(elem_align * row_count), build_context.max_align); return align; } @@ -3935,6 +3951,13 @@ gbString write_type_to_string(gbString str, Type *type) { str = gb_string_append_fmt(str, ") "); str = write_type_to_string(str, type->RelativeSlice.slice_type); break; + + case Type_Matrix: + str = gb_string_appendc(str, gb_bprintf("[%d", cast(int)type->Matrix.row_count)); + str = gb_string_appendc(str, "; "); + str = gb_string_appendc(str, gb_bprintf("%d]", cast(int)type->Matrix.column_count)); + str = write_type_to_string(str, type->Matrix.elem); + break; } return str; -- cgit v1.2.3 From 243e2e2b8a7566087375178a66b25b5d9ac9a356 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 19 Oct 2021 11:24:26 +0100 Subject: Basic support for matrix*vector, vector*matrix operations --- core/fmt/fmt.odin | 16 ++-- src/check_expr.cpp | 30 +++--- src/llvm_backend.cpp | 57 ++++++++++-- src/llvm_backend_expr.cpp | 213 ++++++++++++++++++++++++------------------- src/llvm_backend_general.cpp | 8 +- src/llvm_backend_utility.cpp | 10 +- src/types.cpp | 3 + 7 files changed, 207 insertions(+), 130 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index 804a29cab..46b1fc14c 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -1960,13 +1960,13 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { fi.indent += 1; defer fi.indent -= 1 - if fi.hash { + if fi.hash { io.write_byte(fi.writer, '\n') // TODO(bill): Should this render it like in written form? e.g. tranposed - for col in 0.. 0 { io.write_string(fi.writer, ", ") } + for col in 0.. 0 { io.write_string(fi.writer, ", ") } offset := row*info.elem_size + col*info.stride @@ -1976,10 +1976,10 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { io.write_string(fi.writer, ";\n") } } else { - for col in 0.. 0 { io.write_string(fi.writer, "; ") } - for row in 0.. 0 { io.write_string(fi.writer, ", ") } + for row in 0.. 0 { io.write_string(fi.writer, ", ") } + for col in 0.. 0 { io.write_string(fi.writer, "; ") } offset := row*info.elem_size + col*info.stride diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 9c12802d7..1ca5b895d 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -2686,10 +2686,11 @@ void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand x->mode = Addressing_Invalid; return; } + + Type *xt = base_type(x->type); + Type *yt = base_type(y->type); if (is_type_matrix(x->type)) { - Type *xt = base_type(x->type); - Type *yt = base_type(y->type); GB_ASSERT(xt->kind == Type_Matrix); if (op.kind == Token_Mul) { if (yt->kind == Type_Matrix) { @@ -2714,7 +2715,11 @@ void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand // Treat arrays as column vectors x->mode = Addressing_Value; - x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1); + if (type_hint == nullptr && xt->Matrix.row_count == yt->Array.count) { + x->type = y->type; + } else { + x->type = alloc_type_matrix(xt->Matrix.elem, xt->Matrix.row_count, 1); + } goto matrix_success; } } @@ -2725,8 +2730,6 @@ void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand x->type = xt; goto matrix_success; } else { - Type *xt = base_type(x->type); - Type *yt = base_type(y->type); GB_ASSERT(is_type_matrix(yt)); GB_ASSERT(!is_type_matrix(xt)); @@ -2743,7 +2746,11 @@ void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand // Treat arrays as row vectors x->mode = Addressing_Value; - x->type = alloc_type_matrix(xt->Matrix.elem, 1, xt->Matrix.column_count); + if (type_hint == nullptr && yt->Matrix.column_count == xt->Array.count) { + x->type = x->type; + } else { + x->type = alloc_type_matrix(yt->Matrix.elem, 1, yt->Matrix.column_count); + } goto matrix_success; } } @@ -2775,13 +2782,13 @@ matrix_success: matrix_error: - gbString xt = type_to_string(x->type); - gbString yt = type_to_string(y->type); + gbString xts = type_to_string(x->type); + gbString yts = type_to_string(y->type); gbString expr_str = expr_to_string(x->expr); - error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xt, yt); + error(op, "Mismatched types in binary matrix expression '%s' for operator '%.*s' : '%s' vs '%s'", expr_str, LIT(op.string), xts, yts); gb_string_free(expr_str); - gb_string_free(yt); - gb_string_free(xt); + gb_string_free(yts); + gb_string_free(xts); x->type = t_invalid; x->mode = Addressing_Invalid; return; @@ -2994,6 +3001,7 @@ void check_binary_expr(CheckerContext *c, Operand *x, Ast *node, Type *type_hint } if (is_type_matrix(x->type) || is_type_matrix(y->type)) { check_binary_matrix(c, op, x, y, type_hint, use_lhs_as_type_hint); + x->expr = node; return; } diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index a72ddc646..a853a6224 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1135,13 +1135,46 @@ void lb_generate_code(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; - LLVMInitializeAllTargetInfos(); - LLVMInitializeAllTargets(); - LLVMInitializeAllTargetMCs(); - LLVMInitializeAllAsmPrinters(); - LLVMInitializeAllAsmParsers(); - LLVMInitializeAllDisassemblers(); - LLVMInitializeNativeTarget(); + switch (build_context.metrics.arch) { + case TargetArch_amd64: + case TargetArch_386: + LLVMInitializeX86TargetInfo(); + LLVMInitializeX86Target(); + LLVMInitializeX86TargetMC(); + LLVMInitializeX86AsmPrinter(); + LLVMInitializeX86AsmParser(); + LLVMInitializeX86Disassembler(); + break; + case TargetArch_arm64: + LLVMInitializeAArch64TargetInfo(); + LLVMInitializeAArch64Target(); + LLVMInitializeAArch64TargetMC(); + LLVMInitializeAArch64AsmPrinter(); + LLVMInitializeAArch64AsmParser(); + LLVMInitializeAArch64Disassembler(); + break; + case TargetArch_wasm32: + LLVMInitializeWebAssemblyTargetInfo(); + LLVMInitializeWebAssemblyTarget(); + LLVMInitializeWebAssemblyTargetMC(); + LLVMInitializeWebAssemblyAsmPrinter(); + LLVMInitializeWebAssemblyAsmParser(); + LLVMInitializeWebAssemblyDisassembler(); + break; + default: + LLVMInitializeAllTargetInfos(); + LLVMInitializeAllTargets(); + LLVMInitializeAllTargetMCs(); + LLVMInitializeAllAsmPrinters(); + LLVMInitializeAllAsmParsers(); + LLVMInitializeAllDisassemblers(); + break; + } + + + if (build_context.microarch == "native") { + LLVMInitializeNativeTarget(); + } char const *target_triple = alloc_cstring(permanent_allocator(), build_context.metrics.target_triplet); for_array(i, gen->modules.entries) { @@ -1174,6 +1207,14 @@ void lb_generate_code(lbGenerator *gen) { if (gb_strcmp(llvm_cpu, host_cpu_name) == 0) { llvm_features = LLVMGetHostCPUFeatures(); } + } else if (build_context.metrics.arch == TargetArch_amd64) { + // NOTE(bill): x86-64-v2 is more than enough for everyone + // + // x86-64: CMOV, CMPXCHG8B, FPU, FXSR, MMX, FXSR, SCE, SSE, SSE2 + // x86-64-v2: (close to Nehalem) CMPXCHG16B, LAHF-SAHF, POPCNT, SSE3, SSE4.1, SSE4.2, SSSE3 + // x86-64-v3: (close to Haswell) AVX, AVX2, BMI1, BMI2, F16C, FMA, LZCNT, MOVBE, XSAVE + // x86-64-v4: AVX512F, AVX512BW, AVX512CD, AVX512DQ, AVX512VL + llvm_cpu = "x86-64-v2"; } // GB_ASSERT_MSG(LLVMTargetHasAsmBackend(target)); @@ -1640,6 +1681,7 @@ void lb_generate_code(lbGenerator *gen) { code_gen_file_type = LLVMAssemblyFile; } + for_array(j, gen->modules.entries) { lbModule *m = gen->modules.entries[j].value; if (LLVMVerifyModule(m->mod, LLVMReturnStatusAction, &llvm_error)) { @@ -1684,7 +1726,6 @@ void lb_generate_code(lbGenerator *gen) { } } - TIME_SECTION("LLVM Add Foreign Library Paths"); for_array(j, gen->modules.entries) { diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index 2e2d45991..ed98c6845 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -509,12 +509,16 @@ LLVMValueRef llvm_matrix_column_major_load(lbProcedure *p, lbValue lhs) { GB_ASSERT(mt->kind == Type_Matrix); GB_ASSERT(lb_matrix_elem_simple(mt)); - unsigned total_elem_count = cast(unsigned)matrix_type_total_elems(mt); + + i64 stride = matrix_type_stride_in_elems(mt); + i64 rows = mt->Matrix.row_count; + i64 columns = mt->Matrix.column_count; + unsigned elem_count = cast(unsigned)(rows*columns); Type *elem = mt->Matrix.elem; LLVMTypeRef elem_type = lb_type(m, elem); - LLVMTypeRef vector_type = LLVMVectorType(elem_type, total_elem_count); + LLVMTypeRef vector_type = LLVMVectorType(elem_type, elem_count); LLVMTypeRef types[] = {vector_type}; char const *name = "llvm.matrix.column.major.load"; @@ -524,44 +528,18 @@ LLVMValueRef llvm_matrix_column_major_load(lbProcedure *p, lbValue lhs) { lbValue ptr = lb_address_from_load_or_generate_local(p, lhs); ptr = lb_emit_matrix_epi(p, ptr, 0, 0); - + LLVMValueRef values[5] = {}; values[0] = ptr.value; - values[1] = lb_const_int(m, t_u64, 8*matrix_type_stride(mt)).value; // bit width - values[2] = LLVMConstNull(lb_type(m, t_llvm_bool)); - values[3] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; - values[4] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; - - return LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); -} -LLVMValueRef llvm_matrix_column_major_load_from_ptr(lbProcedure *p, lbValue ptr) { - lbModule *m = p->module; - - Type *mt = base_type(type_deref(ptr.type)); - GB_ASSERT(mt->kind == Type_Matrix); - GB_ASSERT(lb_matrix_elem_simple(mt)); - - unsigned total_elem_count = cast(unsigned)matrix_type_total_elems(mt); - - Type *elem = mt->Matrix.elem; - LLVMTypeRef elem_type = lb_type(m, elem); - - LLVMTypeRef vector_type = LLVMVectorType(elem_type, total_elem_count); - LLVMTypeRef types[] = {vector_type}; - - char const *name = "llvm.matrix.column.major.load"; - unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); - GB_ASSERT_MSG(id != 0, "Unable to find %s", name); - LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); - - LLVMValueRef values[5] = {}; - values[0] = lb_emit_matrix_epi(p, ptr, 0, 0).value; - values[1] = lb_const_int(m, t_u64, 8*matrix_type_stride(mt)).value; // bit width + values[1] = lb_const_int(m, t_u64, stride).value; values[2] = LLVMConstNull(lb_type(m, t_llvm_bool)); values[3] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; values[4] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; - return LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + gb_printf_err("%s\n", LLVMPrintValueToString(call)); + // LLVMAddAttributeAtIndex(call, 0, lb_create_enum_attribute(p->module->ctx, "align", cast(u64)type_align_of(mt))); + return call; } void llvm_matrix_column_major_store(lbProcedure *p, lbAddr addr, LLVMValueRef vector_value) { @@ -571,12 +549,7 @@ void llvm_matrix_column_major_store(lbProcedure *p, lbAddr addr, LLVMValueRef ve GB_ASSERT(mt->kind == Type_Matrix); GB_ASSERT(lb_matrix_elem_simple(mt)); - unsigned total_elem_count = cast(unsigned)matrix_type_total_elems(mt); - - Type *elem = mt->Matrix.elem; - LLVMTypeRef elem_type = lb_type(m, elem); - - LLVMTypeRef vector_type = LLVMVectorType(elem_type, total_elem_count); + LLVMTypeRef vector_type = LLVMTypeOf(vector_value); LLVMTypeRef types[] = {vector_type}; char const *name = "llvm.matrix.column.major.store"; @@ -587,56 +560,26 @@ void llvm_matrix_column_major_store(lbProcedure *p, lbAddr addr, LLVMValueRef ve lbValue ptr = lb_addr_get_ptr(p, addr); ptr = lb_emit_matrix_epi(p, ptr, 0, 0); - GB_ASSERT(LLVMTypeOf(vector_value) == vector_type); unsigned vector_size = LLVMGetVectorSize(vector_type); GB_ASSERT((mt->Matrix.row_count*mt->Matrix.column_count) == cast(i64)vector_size); - LLVMValueRef values[6] = {}; - values[0] = vector_value; - values[1] = ptr.value; - values[2] = lb_const_int(m, t_u64, 8*matrix_type_stride(mt)).value; // bit width - values[3] = LLVMConstNull(lb_type(m, t_llvm_bool)); - values[4] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; - values[5] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; - - LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); -} - -void llvm_matrix_column_major_store_to_raw_ptr(lbProcedure *p, Type *mt, lbValue ptr, LLVMValueRef vector_value) { - lbModule *m = p->module; - - mt = base_type(mt); - GB_ASSERT(mt->kind == Type_Matrix); - GB_ASSERT(lb_matrix_elem_simple(mt)); - - unsigned total_elem_count = cast(unsigned)matrix_type_total_elems(mt); - - Type *elem = mt->Matrix.elem; - LLVMTypeRef elem_type = lb_type(m, elem); - - LLVMTypeRef vector_type = LLVMVectorType(elem_type, total_elem_count); - LLVMTypeRef types[] = {vector_type}; - - char const *name = "llvm.matrix.column.major.store"; - unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); - GB_ASSERT_MSG(id != 0, "Unable to find %s", name); - LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); - - GB_ASSERT(LLVMTypeOf(vector_value) == vector_type); - unsigned vector_size = LLVMGetVectorSize(vector_type); - GB_ASSERT((mt->Matrix.row_count*mt->Matrix.column_count) == cast(i64)vector_size); + i64 stride = matrix_type_stride_in_elems(mt); LLVMValueRef values[6] = {}; values[0] = vector_value; values[1] = ptr.value; - values[2] = lb_const_int(m, t_u64, 8*matrix_type_stride(mt)).value; // bit width + values[2] = lb_const_int(m, t_u64, stride).value; values[3] = LLVMConstNull(lb_type(m, t_llvm_bool)); values[4] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; values[5] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; - LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + gb_printf_err("%s\n", LLVMPrintValueToString(call)); + // LLVMAddAttributeAtIndex(call, 1, lb_create_enum_attribute(p->module->ctx, "align", cast(u64)type_align_of(mt))); + gb_unused(call); } + LLVMValueRef llvm_matrix_multiply(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, i64 outer_rows, i64 inner, i64 outer_columns) { lbModule *m = p->module; @@ -648,6 +591,7 @@ LLVMValueRef llvm_matrix_multiply(lbProcedure *p, LLVMValueRef a, LLVMValueRef b LLVMTypeRef elem_type = LLVMGetElementType(a_type); LLVMTypeRef res_vector_type = LLVMVectorType(elem_type, cast(unsigned)(outer_rows*outer_columns)); + LLVMTypeRef types[] = {res_vector_type, a_type, b_type}; char const *name = "llvm.matrix.multiply"; @@ -662,7 +606,9 @@ LLVMValueRef llvm_matrix_multiply(lbProcedure *p, LLVMValueRef a, LLVMValueRef b values[3] = lb_const_int(m, t_u32, inner).value; values[4] = lb_const_int(m, t_u32, outer_columns).value; - return LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + gb_printf_err("%s\n", LLVMPrintValueToString(call)); + return call; } @@ -684,19 +630,13 @@ lbValue lb_emit_matrix_mul(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) // TODO(bill): LLVM ERROR: Do not know how to split the result of this operator! lbAddr res = lb_add_local_generated(p, type, true); - lbValue res_ptr = lb_addr_get_ptr(p, res); - res_ptr = lb_emit_matrix_epi(p, res_ptr, 0, 0); - - lbValue lhs_ptr = lb_address_from_load_or_generate_local(p, lhs); - lbValue rhs_ptr = lb_address_from_load_or_generate_local(p, rhs); - LLVMValueRef a = llvm_matrix_column_major_load_from_ptr(p, lhs_ptr); - LLVMValueRef b = llvm_matrix_column_major_load_from_ptr(p, rhs_ptr); - LLVMValueRef c = llvm_matrix_multiply(p, a, b, xt->Matrix.row_count, xt->Matrix.column_count, yt->Matrix.column_count); - - llvm_matrix_column_major_store_to_raw_ptr(p, type, res_ptr, c); + LLVMValueRef a = llvm_matrix_column_major_load(p, lhs); gb_unused(a); + LLVMValueRef b = llvm_matrix_column_major_load(p, rhs); gb_unused(b); + LLVMValueRef c = llvm_matrix_multiply(p, a, b, xt->Matrix.row_count, xt->Matrix.column_count, yt->Matrix.column_count); gb_unused(c); + llvm_matrix_column_major_store(p, res, c); return lb_addr_load(p, res); - } + } slow_form: { @@ -704,18 +644,21 @@ slow_form: lbAddr res = lb_add_local_generated(p, type, true); - for (i64 i = 0; i < xt->Matrix.row_count; i++) { - for (i64 j = 0; j < yt->Matrix.column_count; j++) { - for (i64 k = 0; k < xt->Matrix.column_count; k++) { + i64 outer_rows = xt->Matrix.row_count; + i64 inner = xt->Matrix.column_count; + i64 outer_columns = yt->Matrix.column_count; + + for (i64 j = 0; j < outer_columns; j++) { + for (i64 i = 0; i < outer_rows; i++) { + for (i64 k = 0; k < inner; k++) { lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j); + lbValue d0 = lb_emit_load(p, dst); lbValue a = lb_emit_matrix_ev(p, lhs, i, k); lbValue b = lb_emit_matrix_ev(p, rhs, k, j); lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); - lbValue d = lb_emit_load(p, dst); - lbValue e = lb_emit_arith(p, Token_Add, d, c, elem); - lb_emit_store(p, dst, e); - + lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); + lb_emit_store(p, dst, d); } } } @@ -724,6 +667,72 @@ slow_form: } } +lbValue lb_emit_matrix_mul_vector(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) { + Type *mt = base_type(lhs.type); + Type *vt = base_type(rhs.type); + + GB_ASSERT(is_type_matrix(mt)); + GB_ASSERT(is_type_array_like(vt)); + + i64 vector_count = get_array_type_count(vt); + + GB_ASSERT(mt->Matrix.column_count == vector_count); + GB_ASSERT(are_types_identical(mt->Matrix.elem, base_array_type(vt))); + + Type *elem = mt->Matrix.elem; + + lbAddr res = lb_add_local_generated(p, type, true); + + for (i64 i = 0; i < mt->Matrix.row_count; i++) { + for (i64 j = 0; j < mt->Matrix.column_count; j++) { + lbValue dst = lb_emit_matrix_epi(p, res.addr, i, 0); + lbValue d0 = lb_emit_load(p, dst); + + lbValue a = lb_emit_matrix_ev(p, lhs, i, j); + lbValue b = lb_emit_struct_ev(p, rhs, cast(i32)j); + lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); + lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); + lb_emit_store(p, dst, d); + } + } + + return lb_addr_load(p, res); +} + +lbValue lb_emit_vector_mul_matrix(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) { + Type *mt = base_type(rhs.type); + Type *vt = base_type(lhs.type); + + GB_ASSERT(is_type_matrix(mt)); + GB_ASSERT(is_type_array_like(vt)); + + i64 vector_count = get_array_type_count(vt); + + GB_ASSERT(mt->Matrix.row_count == vector_count); + GB_ASSERT(are_types_identical(mt->Matrix.elem, base_array_type(vt))); + + Type *elem = mt->Matrix.elem; + + lbAddr res = lb_add_local_generated(p, type, true); + + for (i64 j = 0; j < mt->Matrix.column_count; j++) { + for (i64 k = 0; k < mt->Matrix.row_count; k++) { + lbValue dst = lb_emit_matrix_epi(p, res.addr, 0, j); + lbValue d0 = lb_emit_load(p, dst); + + lbValue a = lb_emit_struct_ev(p, lhs, cast(i32)k); + lbValue b = lb_emit_matrix_ev(p, rhs, k, j); + lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); + lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); + lb_emit_store(p, dst, d); + } + } + + return lb_addr_load(p, res); +} + + + lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { GB_ASSERT(is_type_matrix(lhs.type) || is_type_matrix(rhs.type)); @@ -735,7 +744,12 @@ lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue if (xt->kind == Type_Matrix) { if (yt->kind == Type_Matrix) { return lb_emit_matrix_mul(p, lhs, rhs, type); + } else if (is_type_array_like(yt)) { + return lb_emit_matrix_mul_vector(p, lhs, rhs, type); } + } else if (is_type_array_like(xt)) { + GB_ASSERT(yt->kind == Type_Matrix); + return lb_emit_vector_mul_matrix(p, lhs, rhs, type); } } else { @@ -1036,6 +1050,13 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { ast_node(be, BinaryExpr, expr); TypeAndValue tv = type_and_value_of_expr(expr); + + if (is_type_matrix(be->left->tav.type) || is_type_matrix(be->right->tav.type)) { + lbValue left = lb_build_expr(p, be->left); + lbValue right = lb_build_expr(p, be->right); + return lb_emit_arith_matrix(p, be->op.kind, left, right, default_type(tv.type)); + } + switch (be->op.kind) { case Token_Add: diff --git a/src/llvm_backend_general.cpp b/src/llvm_backend_general.cpp index ee8f220ef..63a63349a 100644 --- a/src/llvm_backend_general.cpp +++ b/src/llvm_backend_general.cpp @@ -1937,7 +1937,7 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { i64 elem_size = type_size_of(type->Matrix.elem); GB_ASSERT(elem_size > 0); i64 elem_count = size/elem_size; - GB_ASSERT(elem_count > 0); + GB_ASSERT_MSG(elem_count > 0, "%s", type_to_string(type)); m->internal_type_level -= 1; @@ -2611,8 +2611,10 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 p LLVMTypeRef llvm_type = lb_type(p->module, type); LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name); - // unsigned alignment = 16; // TODO(bill): Make this configurable - unsigned alignment = cast(unsigned)lb_alignof(llvm_type); + unsigned alignment = cast(unsigned)gb_max(type_align_of(type), lb_alignof(llvm_type)); + if (is_type_matrix(type)) { + alignment *= 2; // NOTE(bill): Just in case + } LLVMSetAlignment(ptr, alignment); LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); diff --git a/src/llvm_backend_utility.cpp b/src/llvm_backend_utility.cpp index 1b41be2a3..3971c0ca6 100644 --- a/src/llvm_backend_utility.cpp +++ b/src/llvm_backend_utility.cpp @@ -1224,12 +1224,14 @@ lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) { lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) { Type *t = s.type; GB_ASSERT(is_type_pointer(t)); - Type *st = base_type(type_deref(t)); - GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st)); + Type *mt = base_type(type_deref(t)); + GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt)); - Type *ptr = base_array_type(st); + Type *ptr = base_array_type(mt); + + i64 stride_elems = matrix_type_stride_in_elems(mt); - isize index = row*column; + isize index = row + column*stride_elems; GB_ASSERT(0 <= index); LLVMValueRef indices[2] = { diff --git a/src/types.cpp b/src/types.cpp index fd9b20c91..8bce69cf3 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1249,6 +1249,7 @@ bool is_type_matrix(Type *t) { } i64 matrix_type_stride(Type *t) { + // TODO(bill): precompute matrix stride t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); i64 align = type_align_of(t); @@ -1258,6 +1259,7 @@ i64 matrix_type_stride(Type *t) { } i64 matrix_type_stride_in_elems(Type *t) { + // TODO(bill): precompute matrix stride t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); i64 stride = matrix_type_stride(t); @@ -1266,6 +1268,7 @@ i64 matrix_type_stride_in_elems(Type *t) { i64 matrix_type_total_elems(Type *t) { + // TODO(bill): precompute matrix total elems t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); i64 size = type_size_of(t); -- cgit v1.2.3 From 1556fad65a52af7683d5c80f2f724ef252525163 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 19 Oct 2021 11:31:11 +0100 Subject: Change syntax for matrices to `matrix[R, C]T` --- core/fmt/fmt.odin | 5 ++--- core/reflect/types.odin | 4 ++-- core/runtime/print.odin | 4 ++-- src/check_expr.cpp | 6 +++--- src/parser.cpp | 37 +++++++++++++++++++------------------ src/tokenizer.cpp | 1 + src/types.cpp | 4 +--- 7 files changed, 30 insertions(+), 31 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index 46b1fc14c..c0190a0b9 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -1954,9 +1954,8 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { } case runtime.Type_Info_Matrix: - reflect.write_type(fi.writer, type_info_of(v.id)) - io.write_byte(fi.writer, '{') - defer io.write_byte(fi.writer, '}') + io.write_string(fi.writer, "matrix[") + defer io.write_byte(fi.writer, ']') fi.indent += 1; defer fi.indent -= 1 diff --git a/core/reflect/types.odin b/core/reflect/types.odin index cf79abb07..74778013a 100644 --- a/core/reflect/types.odin +++ b/core/reflect/types.odin @@ -592,9 +592,9 @@ write_type_writer :: proc(w: io.Writer, ti: ^Type_Info, n_written: ^int = nil) - write_type(w, info.slice, &n) or_return case Type_Info_Matrix: - io.write_string(w, "[", &n) or_return + io.write_string(w, "matrix[", &n) or_return io.write_i64(w, i64(info.row_count), 10, &n) or_return - io.write_string(w, "; ", &n) or_return + io.write_string(w, ", ", &n) or_return io.write_i64(w, i64(info.column_count), 10, &n) or_return io.write_string(w, "]", &n) or_return write_type(w, info.elem, &n) or_return diff --git a/core/runtime/print.odin b/core/runtime/print.odin index f32ac0831..8a14eba08 100644 --- a/core/runtime/print.odin +++ b/core/runtime/print.odin @@ -372,9 +372,9 @@ print_type :: proc "contextless" (ti: ^Type_Info) { print_type(info.slice) case Type_Info_Matrix: - print_string("[") + print_string("matrix[") print_u64(u64(info.row_count)) - print_string("; ") + print_string(", ") print_u64(u64(info.column_count)) print_string("]") print_type(info.elem) diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 1ca5b895d..a75334e6c 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -9138,7 +9138,7 @@ gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) { str = write_expr_to_string(str, mie->expr, shorthand); str = gb_string_append_rune(str, '['); str = write_expr_to_string(str, mie->row_index, shorthand); - str = gb_string_appendc(str, "; "); + str = gb_string_appendc(str, ", "); str = write_expr_to_string(str, mie->column_index, shorthand); str = gb_string_append_rune(str, ']'); case_end; @@ -9216,9 +9216,9 @@ gbString write_expr_to_string(gbString str, Ast *node, bool shorthand) { case_end; case_ast_node(mt, MatrixType, node); - str = gb_string_append_rune(str, '['); + str = gb_string_appendc(str, "matrix["); str = write_expr_to_string(str, mt->row_count, shorthand); - str = gb_string_appendc(str, "; "); + str = gb_string_appendc(str, ", "); str = write_expr_to_string(str, mt->column_count, shorthand); str = gb_string_append_rune(str, ']'); str = write_expr_to_string(str, mt->elem, shorthand); diff --git a/src/parser.cpp b/src/parser.cpp index 499bd337b..c29cf70d9 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -2241,18 +2241,6 @@ Ast *parse_operand(AstFile *f, bool lhs) { count_expr = parse_expr(f, false); f->expr_level--; } - if (allow_token(f, Token_Semicolon)) { - Ast *row_count = count_expr; - Ast *column_count = nullptr; - - f->expr_level++; - column_count = parse_expr(f, false); - f->expr_level--; - - expect_token(f, Token_CloseBracket); - - return ast_matrix_type(f, token, row_count, column_count, parse_type(f)); - } expect_token(f, Token_CloseBracket); return ast_array_type(f, token, count_expr, parse_type(f)); @@ -2271,6 +2259,23 @@ Ast *parse_operand(AstFile *f, bool lhs) { return ast_map_type(f, token, key, value); } break; + + case Token_matrix: { + Token token = expect_token(f, Token_matrix); + Ast *row_count = nullptr; + Ast *column_count = nullptr; + Ast *type = nullptr; + Token open, close; + + open = expect_token_after(f, Token_OpenBracket, "matrix"); + row_count = parse_expr(f, true); + expect_token(f, Token_Comma); + column_count = parse_expr(f, true); + close = expect_token(f, Token_CloseBracket); + type = parse_type(f); + + return ast_matrix_type(f, token, row_count, column_count, type); + } break; case Token_struct: { Token token = expect_token(f, Token_struct); @@ -2716,11 +2721,7 @@ Ast *parse_atom_expr(AstFile *f, Ast *operand, bool lhs) { case Token_RangeHalf: syntax_error(f->curr_token, "Expected a colon, not a range"); /* fallthrough */ - case Token_Semicolon: // matrix index - if (f->curr_token.kind == Token_Semicolon && f->curr_token.string == "\n") { - syntax_error(f->curr_token, "Expected a ';', not a newline"); - } - /* fallthrough */ + case Token_Comma: // matrix index case Token_Colon: interval = advance_token(f); is_interval = true; @@ -2736,7 +2737,7 @@ Ast *parse_atom_expr(AstFile *f, Ast *operand, bool lhs) { close = expect_token(f, Token_CloseBracket); if (is_interval) { - if (interval.kind == Token_Semicolon) { + if (interval.kind == Token_Comma) { if (indices[0] == nullptr || indices[1] == nullptr) { syntax_error(open, "Matrix index expressions require both row and column indices"); } diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index c7627d09c..10b4494d7 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -117,6 +117,7 @@ TOKEN_KIND(Token__KeywordBegin, ""), \ TOKEN_KIND(Token_or_else, "or_else"), \ TOKEN_KIND(Token_or_return, "or_return"), \ TOKEN_KIND(Token_asm, "asm"), \ + TOKEN_KIND(Token_matrix, "matrix"), \ TOKEN_KIND(Token__KeywordEnd, ""), \ TOKEN_KIND(Token_Count, "") diff --git a/src/types.cpp b/src/types.cpp index 8bce69cf3..8e64a10c1 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -3956,9 +3956,7 @@ gbString write_type_to_string(gbString str, Type *type) { break; case Type_Matrix: - str = gb_string_appendc(str, gb_bprintf("[%d", cast(int)type->Matrix.row_count)); - str = gb_string_appendc(str, "; "); - str = gb_string_appendc(str, gb_bprintf("%d]", cast(int)type->Matrix.column_count)); + str = gb_string_appendc(str, gb_bprintf("matrix[%d, %d]", cast(int)type->Matrix.row_count, cast(int)type->Matrix.column_count)); str = write_type_to_string(str, type->Matrix.elem); break; } -- cgit v1.2.3 From 662cbaf425a54127dea206c3a35d776853bac169 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 19 Oct 2021 12:13:19 +0100 Subject: Support indexing matrices --- core/runtime/error_checks.odin | 23 +++++++++++++++ src/check_expr.cpp | 66 ++++++++++++++++++++++++++++++++++++++++-- src/checker.cpp | 1 + src/llvm_backend.hpp | 1 + src/llvm_backend_expr.cpp | 54 +++++++++++++++++++++++++++++++++- src/llvm_backend_general.cpp | 30 +++++++++++++++++++ src/llvm_backend_utility.cpp | 31 ++++++++++++++++++++ src/types.cpp | 4 +++ 8 files changed, 206 insertions(+), 4 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/core/runtime/error_checks.odin b/core/runtime/error_checks.odin index bdd010b50..7f1aeb2d7 100644 --- a/core/runtime/error_checks.odin +++ b/core/runtime/error_checks.odin @@ -96,6 +96,29 @@ dynamic_array_expr_error :: proc "contextless" (file: string, line, column: i32, } +matrix_bounds_check_error :: proc "contextless" (file: string, line, column: i32, row_index, column_index, row_count, column_count: int) { + if 0 <= row_index && row_index < row_count && + 0 <= column_index && column_index < column_count { + return + } + handle_error :: proc "contextless" (file: string, line, column: i32, row_index, column_index, row_count, column_count: int) { + print_caller_location(Source_Code_Location{file, line, column, ""}) + print_string(" Matrix indices [") + print_i64(i64(row_index)) + print_string(", ") + print_i64(i64(column_index)) + print_string(" is out of bounds range [0..<") + print_i64(i64(row_count)) + print_string(", 0..<") + print_i64(i64(column_count)) + print_string("]") + print_byte('\n') + bounds_trap() + } + handle_error(file, line, column, row_index, column_index, row_count, column_count) +} + + type_assertion_check :: proc "contextless" (ok: bool, file: string, line, column: i32, from, to: typeid) { if ok { return diff --git a/src/check_expr.cpp b/src/check_expr.cpp index a75334e6c..73e1a7e51 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -6367,8 +6367,7 @@ bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 *max_count, *max_count = t->Matrix.column_count; if (indirection) { o->mode = Addressing_Variable; - } else if (o->mode != Addressing_Variable && - o->mode != Addressing_Constant) { + } else if (o->mode != Addressing_Variable) { o->mode = Addressing_Value; } o->type = alloc_type_array(t->Matrix.elem, t->Matrix.row_count); @@ -6672,7 +6671,68 @@ void check_promote_optional_ok(CheckerContext *c, Operand *x, Type **val_type_, void check_matrix_index_expr(CheckerContext *c, Operand *o, Ast *node, Type *type_hint) { - error(node, "TODO: matrix index expressions"); + ast_node(ie, MatrixIndexExpr, node); + + check_expr(c, o, ie->expr); + node->viral_state_flags |= ie->expr->viral_state_flags; + if (o->mode == Addressing_Invalid) { + o->expr = node; + return; + } + + Type *t = base_type(type_deref(o->type)); + bool is_ptr = is_type_pointer(o->type); + bool is_const = o->mode == Addressing_Constant; + + if (t->kind != Type_Matrix) { + gbString str = expr_to_string(o->expr); + gbString type_str = type_to_string(o->type); + defer (gb_string_free(str)); + defer (gb_string_free(type_str)); + if (is_const) { + error(o->expr, "Cannot use matrix indexing on constant '%s' of type '%s'", str, type_str); + } else { + error(o->expr, "Cannot use matrix indexing on '%s' of type '%s'", str, type_str); + } + o->mode = Addressing_Invalid; + o->expr = node; + return; + } + o->type = t->Matrix.elem; + if (is_ptr) { + o->mode = Addressing_Variable; + } else if (o->mode != Addressing_Variable) { + o->mode = Addressing_Value; + } + + if (ie->row_index == nullptr) { + gbString str = expr_to_string(o->expr); + error(o->expr, "Missing row index for '%s'", str); + gb_string_free(str); + o->mode = Addressing_Invalid; + o->expr = node; + return; + } + if (ie->column_index == nullptr) { + gbString str = expr_to_string(o->expr); + error(o->expr, "Missing column index for '%s'", str); + gb_string_free(str); + o->mode = Addressing_Invalid; + o->expr = node; + return; + } + + i64 row_count = t->Matrix.row_count; + i64 column_count = t->Matrix.column_count; + + i64 row_index = 0; + i64 column_index = 0; + bool row_ok = check_index_value(c, t, false, ie->row_index, row_count, &row_index, nullptr); + bool column_ok = check_index_value(c, t, false, ie->column_index, column_count, &column_index, nullptr); + + + gb_unused(row_ok); + gb_unused(column_ok); } diff --git a/src/checker.cpp b/src/checker.cpp index c0e6d47c0..23597167b 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -2022,6 +2022,7 @@ void generate_minimum_dependency_set(Checker *c, Entity *start) { String bounds_check_entities[] = { // Bounds checking related procedures str_lit("bounds_check_error"), + str_lit("matrix_bounds_check_error"), str_lit("slice_expr_error_hi"), str_lit("slice_expr_error_lo_hi"), str_lit("multi_pointer_slice_expr_error"), diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 73ddad797..9041e7621 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -333,6 +333,7 @@ lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index); lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel); lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel); +lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column); lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column); lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column); diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index ed98c6845..bcbb77355 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -1727,7 +1727,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } if (is_type_matrix(dst) && !is_type_matrix(src)) { - GB_ASSERT(dst->Matrix.row_count == dst->Matrix.column_count); + GB_ASSERT_MSG(dst->Matrix.row_count == dst->Matrix.column_count, "%s <- %s", type_to_string(dst), type_to_string(src)); Type *elem = base_array_type(dst); lbValue e = lb_emit_conv(p, value, elem); @@ -2805,6 +2805,10 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_ast_node(ie, IndexExpr, expr); return lb_addr_load(p, lb_build_addr(p, expr)); case_end; + + case_ast_node(ie, MatrixIndexExpr, expr); + return lb_addr_load(p, lb_build_addr(p, expr)); + case_end; case_ast_node(ia, InlineAsmExpr, expr); Type *t = type_of_expr(expr); @@ -3304,6 +3308,25 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue v = lb_emit_ptr_offset(p, elem, index); return lb_addr(v); } + + case Type_Matrix: { + lbValue matrix = {}; + matrix = lb_build_addr_ptr(p, ie->expr); + if (deref) { + matrix = lb_emit_load(p, matrix); + } + lbValue index = lb_build_expr(p, ie->index); + index = lb_emit_conv(p, index, t_int); + lbValue elem = lb_emit_matrix_ep(p, matrix, lb_const_int(p->module, t_int, 0), index); + elem = lb_emit_conv(p, elem, alloc_type_pointer(type_of_expr(expr))); + + auto index_tv = type_and_value_of_expr(ie->index); + if (index_tv.mode != Addressing_Constant) { + lbValue len = lb_const_int(p->module, t_int, t->Matrix.column_count); + lb_emit_bounds_check(p, ast_token(ie->index), index, len); + } + return lb_addr(elem); + } case Type_Basic: { // Basic_string @@ -3326,6 +3349,35 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } } case_end; + + case_ast_node(ie, MatrixIndexExpr, expr); + Type *t = base_type(type_of_expr(ie->expr)); + + bool deref = is_type_pointer(t); + t = base_type(type_deref(t)); + + lbValue m = {}; + m = lb_build_addr_ptr(p, ie->expr); + if (deref) { + m = lb_emit_load(p, m); + } + lbValue row_index = lb_build_expr(p, ie->row_index); + lbValue column_index = lb_build_expr(p, ie->column_index); + row_index = lb_emit_conv(p, row_index, t_int); + column_index = lb_emit_conv(p, column_index, t_int); + lbValue elem = lb_emit_matrix_ep(p, m, row_index, column_index); + + auto row_index_tv = type_and_value_of_expr(ie->row_index); + auto column_index_tv = type_and_value_of_expr(ie->column_index); + if (row_index_tv.mode != Addressing_Constant || column_index_tv.mode != Addressing_Constant) { + lbValue row_count = lb_const_int(p->module, t_int, t->Matrix.row_count); + lbValue column_count = lb_const_int(p->module, t_int, t->Matrix.column_count); + lb_emit_matrix_bounds_check(p, ast_token(ie->row_index), row_index, column_index, row_count, column_count); + } + return lb_addr(elem); + + + case_end; case_ast_node(se, SliceExpr, expr); diff --git a/src/llvm_backend_general.cpp b/src/llvm_backend_general.cpp index 63a63349a..01221cad6 100644 --- a/src/llvm_backend_general.cpp +++ b/src/llvm_backend_general.cpp @@ -419,6 +419,36 @@ void lb_emit_bounds_check(lbProcedure *p, Token token, lbValue index, lbValue le lb_emit_runtime_call(p, "bounds_check_error", args); } +void lb_emit_matrix_bounds_check(lbProcedure *p, Token token, lbValue row_index, lbValue column_index, lbValue row_count, lbValue column_count) { + if (build_context.no_bounds_check) { + return; + } + if ((p->state_flags & StateFlag_no_bounds_check) != 0) { + return; + } + + row_index = lb_emit_conv(p, row_index, t_int); + column_index = lb_emit_conv(p, column_index, t_int); + row_count = lb_emit_conv(p, row_count, t_int); + column_count = lb_emit_conv(p, column_count, t_int); + + lbValue file = lb_find_or_add_entity_string(p->module, get_file_path_string(token.pos.file_id)); + lbValue line = lb_const_int(p->module, t_i32, token.pos.line); + lbValue column = lb_const_int(p->module, t_i32, token.pos.column); + + auto args = array_make(permanent_allocator(), 7); + args[0] = file; + args[1] = line; + args[2] = column; + args[3] = row_index; + args[4] = column_index; + args[5] = row_count; + args[6] = column_count; + + lb_emit_runtime_call(p, "matrix_bounds_check_error", args); +} + + void lb_emit_multi_pointer_slice_bounds_check(lbProcedure *p, Token token, lbValue low, lbValue high) { if (build_context.no_bounds_check) { return; diff --git a/src/llvm_backend_utility.cpp b/src/llvm_backend_utility.cpp index 3971c0ca6..c7e9e1742 100644 --- a/src/llvm_backend_utility.cpp +++ b/src/llvm_backend_utility.cpp @@ -1249,6 +1249,37 @@ lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) { return res; } +lbValue lb_emit_matrix_ep(lbProcedure *p, lbValue s, lbValue row, lbValue column) { + Type *t = s.type; + GB_ASSERT(is_type_pointer(t)); + Type *mt = base_type(type_deref(t)); + GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt)); + + Type *ptr = base_array_type(mt); + + LLVMValueRef stride_elems = lb_const_int(p->module, t_int, matrix_type_stride_in_elems(mt)).value; + + row = lb_emit_conv(p, row, t_int); + column = lb_emit_conv(p, column, t_int); + + LLVMValueRef index = LLVMBuildAdd(p->builder, row.value, LLVMBuildMul(p->builder, column.value, stride_elems, ""), ""); + + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(p->module, t_int), 0, false), + index, + }; + + lbValue res = {}; + if (lb_is_const(s)) { + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + } else { + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + } + res.type = alloc_type_pointer(ptr); + return res; +} + + lbValue lb_emit_matrix_ev(lbProcedure *p, lbValue s, isize row, isize column) { Type *st = base_type(s.type); GB_ASSERT_MSG(is_type_matrix(st), "%s", type_to_string(st)); diff --git a/src/types.cpp b/src/types.cpp index 8e64a10c1..ec094b4ff 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1726,6 +1726,8 @@ bool is_type_indexable(Type *t) { return true; case Type_RelativeSlice: return true; + case Type_Matrix: + return true; } return false; } @@ -1743,6 +1745,8 @@ bool is_type_sliceable(Type *t) { return false; case Type_RelativeSlice: return true; + case Type_Matrix: + return false; } return false; } -- cgit v1.2.3 From 82b6772ea4fa9872a1fb98305814be8cf7f2c7c4 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 20 Oct 2021 00:40:03 +0100 Subject: Support matrix literals --- core/fmt/fmt.odin | 4 +- core/runtime/core.odin | 2 +- src/check_expr.cpp | 5 ++ src/llvm_backend.hpp | 2 + src/llvm_backend_const.cpp | 83 ++++++++++++++++++++++++++++-- src/llvm_backend_expr.cpp | 119 ++++++++++++++++++++++++++++++++++++++++--- src/llvm_backend_type.cpp | 2 +- src/llvm_backend_utility.cpp | 78 +++++++++++++++++++++++++--- src/parser.cpp | 1 + src/types.cpp | 33 ++++++++++++ 10 files changed, 306 insertions(+), 23 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index c0190a0b9..dc5b529ea 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -1967,7 +1967,7 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { for col in 0.. 0 { io.write_string(fi.writer, ", ") } - offset := row*info.elem_size + col*info.stride + offset := (row + col*info.elem_stride)*info.elem_size data := uintptr(v.data) + uintptr(offset) fmt_arg(fi, any{rawptr(data), info.elem.id}, verb) @@ -1980,7 +1980,7 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { for col in 0.. 0 { io.write_string(fi.writer, "; ") } - offset := row*info.elem_size + col*info.stride + offset := (row + col*info.elem_stride)*info.elem_size data := uintptr(v.data) + uintptr(offset) fmt_arg(fi, any{rawptr(data), info.elem.id}, verb) diff --git a/core/runtime/core.odin b/core/runtime/core.odin index 611b4002c..ba1e81da6 100644 --- a/core/runtime/core.odin +++ b/core/runtime/core.odin @@ -165,7 +165,7 @@ Type_Info_Relative_Slice :: struct { Type_Info_Matrix :: struct { elem: ^Type_Info, elem_size: int, - stride: int, // bytes + elem_stride: int, row_count: int, column_count: int, } diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 73e1a7e51..eb6040320 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -7369,6 +7369,7 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type case Type_Array: case Type_DynamicArray: case Type_SimdVector: + case Type_Matrix: { Type *elem_type = nullptr; String context_name = {}; @@ -7395,6 +7396,10 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type elem_type = t->SimdVector.elem; context_name = str_lit("simd vector literal"); max_type_count = t->SimdVector.count; + } else if (t->kind == Type_Matrix) { + elem_type = t->Matrix.elem; + context_name = str_lit("matrix literal"); + max_type_count = t->Matrix.row_count*t->Matrix.column_count; } else { GB_PANIC("unreachable"); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 9041e7621..d2abed354 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -393,6 +393,8 @@ lbValue lb_soa_struct_len(lbProcedure *p, lbValue value); void lb_emit_increment(lbProcedure *p, lbValue addr); lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y); +lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t); + void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len); lbValue lb_type_info(lbModule *m, Type *type); diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index 4cfcecdc3..413fb365b 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -523,14 +523,11 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc lbValue single_elem = lb_const_value(m, elem, value, allow_local); single_elem.value = llvm_const_cast(single_elem.value, lb_type(m, elem)); - - i64 stride_bytes = matrix_type_stride(type); - i64 stride_elems = stride_bytes/type_size_of(elem); - + i64 total_elem_count = matrix_type_total_elems(type); LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)total_elem_count); for (i64 i = 0; i < row; i++) { - elems[i*stride_elems + i] = single_elem.value; + elems[matrix_index_to_offset(type, i)] = single_elem.value; } for (i64 i = 0; i < total_elem_count; i++) { if (elems[i] == nullptr) { @@ -984,6 +981,82 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc res.value = LLVMConstInt(lb_type(m, original_type), bits, false); return res; + } else if (is_type_matrix(type)) { + ast_node(cl, CompoundLit, value.value_compound); + Type *elem_type = type->Matrix.elem; + isize elem_count = cl->elems.count; + if (elem_count == 0 || !elem_type_can_be_constant(elem_type)) { + return lb_const_nil(m, original_type); + } + + i64 max_count = type->Matrix.row_count*type->Matrix.column_count; + i64 total_count = matrix_type_total_elems(type); + + LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)total_count); + if (cl->elems[0]->kind == Ast_FieldValue) { + for_array(j, cl->elems) { + Ast *elem = cl->elems[j]; + ast_node(fv, FieldValue, elem); + if (is_ast_range(fv->field)) { + ast_node(ie, BinaryExpr, fv->field); + TypeAndValue lo_tav = ie->left->tav; + TypeAndValue hi_tav = ie->right->tav; + GB_ASSERT(lo_tav.mode == Addressing_Constant); + GB_ASSERT(hi_tav.mode == Addressing_Constant); + + TokenKind op = ie->op.kind; + i64 lo = exact_value_to_i64(lo_tav.value); + i64 hi = exact_value_to_i64(hi_tav.value); + if (op != Token_RangeHalf) { + hi += 1; + } + TypeAndValue tav = fv->value->tav; + LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value; + for (i64 k = lo; k < hi; k++) { + i64 offset = matrix_index_to_offset(type, k); + GB_ASSERT(values[offset] == nullptr); + values[offset] = val; + } + } else { + TypeAndValue index_tav = fv->field->tav; + GB_ASSERT(index_tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(index_tav.value); + TypeAndValue tav = fv->value->tav; + LLVMValueRef val = lb_const_value(m, elem_type, tav.value, allow_local).value; + i64 offset = matrix_index_to_offset(type, index); + GB_ASSERT(values[offset] == nullptr); + values[offset] = val; + } + } + + for (i64 i = 0; i < total_count; i++) { + if (values[i] == nullptr) { + values[i] = LLVMConstNull(lb_type(m, elem_type)); + } + } + + res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)total_count, values, allow_local); + return res; + } else { + GB_ASSERT_MSG(elem_count == max_count, "%td != %td", elem_count, max_count); + + LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)total_count); + + for_array(i, cl->elems) { + TypeAndValue tav = cl->elems[i]->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + i64 offset = matrix_index_to_offset(type, i); + values[offset] = lb_const_value(m, elem_type, tav.value, allow_local).value; + } + for (isize i = 0; i < total_count; i++) { + if (values[i] == nullptr) { + values[i] = LLVMConstNull(lb_type(m, elem_type)); + } + } + + res.value = lb_build_constant_array_values(m, type, elem_type, cast(isize)total_count, values, allow_local); + return res; + } } else { return lb_const_nil(m, original_type); } diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index bcbb77355..518ce33af 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -648,18 +648,23 @@ slow_form: i64 inner = xt->Matrix.column_count; i64 outer_columns = yt->Matrix.column_count; + auto inners = slice_make(permanent_allocator(), inner); + for (i64 j = 0; j < outer_columns; j++) { for (i64 i = 0; i < outer_rows; i++) { + lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j); for (i64 k = 0; k < inner; k++) { - lbValue dst = lb_emit_matrix_epi(p, res.addr, i, j); - lbValue d0 = lb_emit_load(p, dst); - - lbValue a = lb_emit_matrix_ev(p, lhs, i, k); - lbValue b = lb_emit_matrix_ev(p, rhs, k, j); - lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); - lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); - lb_emit_store(p, dst, d); + inners[k][0] = lb_emit_matrix_ev(p, lhs, i, k); + inners[k][1] = lb_emit_matrix_ev(p, rhs, k, j); } + + lbValue sum = lb_emit_load(p, dst); + for (i64 k = 0; k < inner; k++) { + lbValue a = inners[k][0]; + lbValue b = inners[k][1]; + sum = lb_emit_mul_add(p, a, b, sum, elem); + } + lb_emit_store(p, dst, sum); } } @@ -3626,6 +3631,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case Type_Slice: et = bt->Slice.elem; break; case Type_BitSet: et = bt->BitSet.elem; break; case Type_SimdVector: et = bt->SimdVector.elem; break; + case Type_Matrix: et = bt->Matrix.elem; break; } String proc_name = {}; @@ -4157,7 +4163,104 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } break; } + + case Type_Matrix: { + if (cl->elems.count > 0) { + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); + + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + // NOTE(bill): Separate value, gep, store into their own chunks + for_array(i, cl->elems) { + Ast *elem = cl->elems[i]; + + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + if (lb_is_elem_const(fv->value, et)) { + continue; + } + if (is_ast_range(fv->field)) { + ast_node(ie, BinaryExpr, fv->field); + TypeAndValue lo_tav = ie->left->tav; + TypeAndValue hi_tav = ie->right->tav; + GB_ASSERT(lo_tav.mode == Addressing_Constant); + GB_ASSERT(hi_tav.mode == Addressing_Constant); + + TokenKind op = ie->op.kind; + i64 lo = exact_value_to_i64(lo_tav.value); + i64 hi = exact_value_to_i64(hi_tav.value); + if (op != Token_RangeHalf) { + hi += 1; + } + + lbValue value = lb_build_expr(p, fv->value); + + for (i64 k = lo; k < hi; k++) { + lbCompoundLitElemTempData data = {}; + data.value = value; + + data.elem_index = cast(i32)matrix_index_to_offset(bt, k); + array_add(&temp_data, data); + } + + } else { + auto tav = fv->field->tav; + GB_ASSERT(tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(tav.value); + + lbValue value = lb_build_expr(p, fv->value); + lbCompoundLitElemTempData data = {}; + data.value = lb_emit_conv(p, value, et); + data.expr = fv->value; + + data.elem_index = cast(i32)matrix_index_to_offset(bt, index); + array_add(&temp_data, data); + } + + } else { + if (lb_is_elem_const(elem, et)) { + continue; + } + lbCompoundLitElemTempData data = {}; + data.expr = elem; + data.elem_index = cast(i32)matrix_index_to_offset(bt, i); + array_add(&temp_data, data); + } + } + + for_array(i, temp_data) { + temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index); + } + + for_array(i, temp_data) { + lbValue field_expr = temp_data[i].value; + Ast *expr = temp_data[i].expr; + + auto prev_hint = lb_set_copy_elision_hint(p, lb_addr(temp_data[i].gep), expr); + + if (field_expr.value == nullptr) { + field_expr = lb_build_expr(p, expr); + } + Type *t = field_expr.type; + GB_ASSERT(t->kind != Type_Tuple); + lbValue ev = lb_emit_conv(p, field_expr, et); + + if (!p->copy_elision_hint.used) { + temp_data[i].value = ev; + } + + lb_reset_copy_elision_hint(p, prev_hint); + } + + for_array(i, temp_data) { + if (temp_data[i].value.value != nullptr) { + lb_emit_store(p, temp_data[i].gep, temp_data[i].value); + } + } + } + break; + } + } return v; diff --git a/src/llvm_backend_type.cpp b/src/llvm_backend_type.cpp index 82e20bf60..decb57702 100644 --- a/src/llvm_backend_type.cpp +++ b/src/llvm_backend_type.cpp @@ -877,7 +877,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da LLVMValueRef vals[5] = { lb_get_type_info_ptr(m, t->Matrix.elem).value, lb_const_int(m, t_int, ez).value, - lb_const_int(m, t_int, matrix_type_stride(t)).value, + lb_const_int(m, t_int, matrix_type_stride_in_elems(t)).value, lb_const_int(m, t_int, t->Matrix.row_count).value, lb_const_int(m, t_int, t->Matrix.column_count).value, }; diff --git a/src/llvm_backend_utility.cpp b/src/llvm_backend_utility.cpp index c7e9e1742..fb9264661 100644 --- a/src/llvm_backend_utility.cpp +++ b/src/llvm_backend_utility.cpp @@ -1225,18 +1225,53 @@ lbValue lb_emit_matrix_epi(lbProcedure *p, lbValue s, isize row, isize column) { Type *t = s.type; GB_ASSERT(is_type_pointer(t)); Type *mt = base_type(type_deref(t)); - GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt)); - + Type *ptr = base_array_type(mt); - i64 stride_elems = matrix_type_stride_in_elems(mt); + if (column == 0) { + GB_ASSERT_MSG(is_type_matrix(mt) || is_type_array_like(mt), "%s", type_to_string(mt)); + + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(p->module, t_int), 0, false), + LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)row, false), + }; + + lbValue res = {}; + if (lb_is_const(s)) { + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + } else { + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + } + + Type *ptr = base_array_type(mt); + res.type = alloc_type_pointer(ptr); + return res; + } else if (row == 0 && is_type_array_like(mt)) { + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(p->module, t_int), 0, false), + LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)column, false), + }; + + lbValue res = {}; + if (lb_is_const(s)) { + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + } else { + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + } + + Type *ptr = base_array_type(mt); + res.type = alloc_type_pointer(ptr); + return res; + } + - isize index = row + column*stride_elems; - GB_ASSERT(0 <= index); + GB_ASSERT_MSG(is_type_matrix(mt), "%s", type_to_string(mt)); + + isize offset = matrix_indices_to_offset(mt, row, column); LLVMValueRef indices[2] = { LLVMConstInt(lb_type(p->module, t_int), 0, false), - LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false), + LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)offset, false), }; lbValue res = {}; @@ -1447,3 +1482,34 @@ lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) { } return lb_emit_struct_ev(p, value, cast(i32)n); } + + + +lbValue lb_emit_mul_add(lbProcedure *p, lbValue a, lbValue b, lbValue c, Type *t) { + lbModule *m = p->module; + + a = lb_emit_conv(p, a, t); + b = lb_emit_conv(p, b, t); + c = lb_emit_conv(p, c, t); + + if (!is_type_different_to_arch_endianness(t) && is_type_float(t)) { + char const *name = "llvm.fma"; + unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); + GB_ASSERT_MSG(id != 0, "Unable to find %s", name); + + LLVMTypeRef types[1] = {}; + types[0] = lb_type(m, t); + + LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); + LLVMValueRef values[3] = {}; + values[0] = a.value; + values[1] = b.value; + values[2] = c.value; + LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); + return {call, t}; + } else { + lbValue x = lb_emit_arith(p, Token_Mul, a, b, t); + lbValue y = lb_emit_arith(p, Token_Add, x, c, t); + return y; + } +} \ No newline at end of file diff --git a/src/parser.cpp b/src/parser.cpp index c29cf70d9..83da481d5 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -2569,6 +2569,7 @@ bool is_literal_type(Ast *node) { case Ast_DynamicArrayType: case Ast_MapType: case Ast_BitSetType: + case Ast_MatrixType: case Ast_CallExpr: return true; } diff --git a/src/types.cpp b/src/types.cpp index ec094b4ff..bbabdf732 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1276,6 +1276,39 @@ i64 matrix_type_total_elems(Type *t) { return size/gb_max(elem_size, 1); } +void matrix_indices_from_index(Type *t, i64 index, i64 *row_index_, i64 *column_index_) { + t = base_type(t); + GB_ASSERT(t->kind == Type_Matrix); + i64 row_count = t->Matrix.row_count; + i64 column_count = t->Matrix.column_count; + GB_ASSERT(0 <= index && index < row_count*column_count); + + i64 row_index = index / column_count; + i64 column_index = index % column_count; + + if (row_index_) *row_index_ = row_index; + if (column_index_) *column_index_ = column_index; +} + +i64 matrix_index_to_offset(Type *t, i64 index) { + t = base_type(t); + GB_ASSERT(t->kind == Type_Matrix); + + i64 row_index, column_index; + matrix_indices_from_index(t, index, &row_index, &column_index); + i64 stride_elems = matrix_type_stride_in_elems(t); + return stride_elems*column_index + row_index; +} + +i64 matrix_indices_to_offset(Type *t, i64 row_index, i64 column_index) { + t = base_type(t); + GB_ASSERT(t->kind == Type_Matrix); + GB_ASSERT(0 <= row_index && row_index < t->Matrix.row_count); + GB_ASSERT(0 <= column_index && column_index < t->Matrix.column_count); + i64 stride_elems = matrix_type_stride_in_elems(t); + return stride_elems*column_index + row_index; +} + bool is_type_dynamic_array(Type *t) { t = base_type(t); return t->kind == Type_DynamicArray; -- cgit v1.2.3 From 445696d660804650c7dbaf1fb3f344b59d93fdf4 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 20 Oct 2021 01:06:58 +0100 Subject: Support parapoly matrices --- src/check_expr.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index eb6040320..d98430aec 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -1165,6 +1165,67 @@ bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, return key || value; } return false; + + case Type_Matrix: + if (source->kind == Type_Matrix) { + if (poly->Matrix.generic_row_count != nullptr) { + Type *gt = poly->Matrix.generic_row_count; + GB_ASSERT(gt->kind == Type_Generic); + Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); + GB_ASSERT(e != nullptr); + if (e->kind == Entity_TypeName) { + poly->Matrix.generic_row_count = nullptr; + poly->Matrix.row_count = source->Matrix.row_count; + + e->kind = Entity_Constant; + e->Constant.value = exact_value_i64(source->Matrix.row_count); + e->type = t_untyped_integer; + } else if (e->kind == Entity_Constant) { + poly->Matrix.generic_row_count = nullptr; + if (e->Constant.value.kind != ExactValue_Integer) { + return false; + } + i64 count = big_int_to_i64(&e->Constant.value.value_integer); + if (count != source->Matrix.row_count) { + return false; + } + poly->Matrix.row_count = source->Matrix.row_count; + } else { + return false; + } + } + if (poly->Matrix.generic_column_count != nullptr) { + Type *gt = poly->Matrix.generic_column_count; + GB_ASSERT(gt->kind == Type_Generic); + Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); + GB_ASSERT(e != nullptr); + if (e->kind == Entity_TypeName) { + poly->Matrix.generic_column_count = nullptr; + poly->Matrix.column_count = source->Matrix.column_count; + + e->kind = Entity_Constant; + e->Constant.value = exact_value_i64(source->Matrix.column_count); + e->type = t_untyped_integer; + } else if (e->kind == Entity_Constant) { + poly->Matrix.generic_column_count = nullptr; + if (e->Constant.value.kind != ExactValue_Integer) { + return false; + } + i64 count = big_int_to_i64(&e->Constant.value.value_integer); + if (count != source->Matrix.column_count) { + return false; + } + poly->Matrix.column_count = source->Matrix.column_count; + } else { + return false; + } + } + if (poly->Matrix.row_count == source->Matrix.row_count && + poly->Matrix.column_count == source->Matrix.column_count) { + return is_polymorphic_type_assignable(c, poly->Matrix.elem, source->Matrix.elem, true, modify_type); + } + } + return false; } return false; } -- cgit v1.2.3 From 3eaac057da11d28cbedd7321f9f6368588b0b4ee Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 20 Oct 2021 01:26:55 +0100 Subject: Unify `polymorphic_assign_index` logic --- src/check_expr.cpp | 99 ++++++++++++++++++------------------------------------ 1 file changed, 33 insertions(+), 66 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index d98430aec..299810ce0 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -897,6 +897,34 @@ void check_assignment(CheckerContext *c, Operand *operand, Type *type, String co } } +bool polymorphic_assign_index(Type **gt_, i64 *dst_count, i64 source_count) { + Type *gt = *gt_; + + GB_ASSERT(gt->kind == Type_Generic); + Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); + GB_ASSERT(e != nullptr); + if (e->kind == Entity_TypeName) { + *gt_ = nullptr; + *dst_count = source_count; + + e->kind = Entity_Constant; + e->Constant.value = exact_value_i64(source_count); + e->type = t_untyped_integer; + return true; + } else if (e->kind == Entity_Constant) { + *gt_ = nullptr; + if (e->Constant.value.kind != ExactValue_Integer) { + return false; + } + i64 count = big_int_to_i64(&e->Constant.value.value_integer); + if (count != source_count) { + return false; + } + *dst_count = source_count; + return true; + } + return false; +} bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, bool compound, bool modify_type) { Operand o = {Addressing_Value}; @@ -951,28 +979,7 @@ bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, case Type_Array: if (source->kind == Type_Array) { if (poly->Array.generic_count != nullptr) { - Type *gt = poly->Array.generic_count; - GB_ASSERT(gt->kind == Type_Generic); - Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); - GB_ASSERT(e != nullptr); - if (e->kind == Entity_TypeName) { - poly->Array.generic_count = nullptr; - poly->Array.count = source->Array.count; - - e->kind = Entity_Constant; - e->Constant.value = exact_value_i64(source->Array.count); - e->type = t_untyped_integer; - } else if (e->kind == Entity_Constant) { - poly->Array.generic_count = nullptr; - if (e->Constant.value.kind != ExactValue_Integer) { - return false; - } - i64 count = big_int_to_i64(&e->Constant.value.value_integer); - if (count != source->Array.count) { - return false; - } - poly->Array.count = source->Array.count; - } else { + if (!polymorphic_assign_index(&poly->Array.generic_count, &poly->Array.count, source->Array.count)) { return false; } } @@ -1169,54 +1176,14 @@ bool is_polymorphic_type_assignable(CheckerContext *c, Type *poly, Type *source, case Type_Matrix: if (source->kind == Type_Matrix) { if (poly->Matrix.generic_row_count != nullptr) { - Type *gt = poly->Matrix.generic_row_count; - GB_ASSERT(gt->kind == Type_Generic); - Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); - GB_ASSERT(e != nullptr); - if (e->kind == Entity_TypeName) { - poly->Matrix.generic_row_count = nullptr; - poly->Matrix.row_count = source->Matrix.row_count; - - e->kind = Entity_Constant; - e->Constant.value = exact_value_i64(source->Matrix.row_count); - e->type = t_untyped_integer; - } else if (e->kind == Entity_Constant) { - poly->Matrix.generic_row_count = nullptr; - if (e->Constant.value.kind != ExactValue_Integer) { - return false; - } - i64 count = big_int_to_i64(&e->Constant.value.value_integer); - if (count != source->Matrix.row_count) { - return false; - } - poly->Matrix.row_count = source->Matrix.row_count; - } else { + poly->Matrix.stride_in_bytes = 0; + if (!polymorphic_assign_index(&poly->Matrix.generic_row_count, &poly->Matrix.row_count, source->Matrix.row_count)) { return false; } } if (poly->Matrix.generic_column_count != nullptr) { - Type *gt = poly->Matrix.generic_column_count; - GB_ASSERT(gt->kind == Type_Generic); - Entity *e = scope_lookup(gt->Generic.scope, gt->Generic.name); - GB_ASSERT(e != nullptr); - if (e->kind == Entity_TypeName) { - poly->Matrix.generic_column_count = nullptr; - poly->Matrix.column_count = source->Matrix.column_count; - - e->kind = Entity_Constant; - e->Constant.value = exact_value_i64(source->Matrix.column_count); - e->type = t_untyped_integer; - } else if (e->kind == Entity_Constant) { - poly->Matrix.generic_column_count = nullptr; - if (e->Constant.value.kind != ExactValue_Integer) { - return false; - } - i64 count = big_int_to_i64(&e->Constant.value.value_integer); - if (count != source->Matrix.column_count) { - return false; - } - poly->Matrix.column_count = source->Matrix.column_count; - } else { + poly->Matrix.stride_in_bytes = 0; + if (!polymorphic_assign_index(&poly->Matrix.generic_column_count, &poly->Matrix.column_count, source->Matrix.column_count)) { return false; } } -- cgit v1.2.3 From 7faca7066c30d6e663b268dc1e8ec66710ae3dd5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 20 Oct 2021 01:51:16 +0100 Subject: Add builtin `transpose` --- src/check_builtin.cpp | 34 ++++++++++- src/check_expr.cpp | 36 +++++++----- src/checker_builtin_procs.hpp | 4 ++ src/llvm_backend_expr.cpp | 133 ++++++------------------------------------ src/llvm_backend_proc.cpp | 6 ++ 5 files changed, 80 insertions(+), 133 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_builtin.cpp b/src/check_builtin.cpp index a04302d01..659a74ad7 100644 --- a/src/check_builtin.cpp +++ b/src/check_builtin.cpp @@ -1966,13 +1966,13 @@ bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 return false; } if (!is_operand_value(x)) { - error(call, "'soa_unzip' expects an #soa slice"); + error(call, "'%.*s' expects an #soa slice", LIT(builtin_name)); return false; } Type *t = base_type(x.type); if (!is_type_soa_struct(t) || t->Struct.soa_kind != StructSoa_Slice) { gbString s = type_to_string(x.type); - error(call, "'soa_unzip' expects an #soa slice, got %s", s); + error(call, "'%.*s' expects an #soa slice, got %s", LIT(builtin_name), s); gb_string_free(s); return false; } @@ -1987,6 +1987,36 @@ bool check_builtin_procedure(CheckerContext *c, Operand *operand, Ast *call, i32 operand->mode = Addressing_Value; break; } + + case BuiltinProc_transpose: { + Operand x = {}; + check_expr(c, &x, ce->args[0]); + if (x.mode == Addressing_Invalid) { + return false; + } + if (!is_operand_value(x)) { + error(call, "'%.*s' expects a matrix or array", LIT(builtin_name)); + return false; + } + Type *t = base_type(x.type); + if (!is_type_matrix(t) && !is_type_array(t)) { + gbString s = type_to_string(x.type); + error(call, "'%.*s' expects a matrix or array, got %s", LIT(builtin_name), s); + gb_string_free(s); + return false; + } + + operand->mode = Addressing_Value; + if (is_type_array(t)) { + // Do nothing + operand->type = x.type; + } else { + GB_ASSERT(t->kind == Type_Matrix); + operand->type = alloc_type_matrix(t->Matrix.elem, t->Matrix.column_count, t->Matrix.row_count); + } + operand->type = check_matrix_type_hint(operand->type, type_hint); + break; + } case BuiltinProc_simd_vector: { Operand x = {}; diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 299810ce0..8a1e5fd86 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -2708,6 +2708,25 @@ bool can_use_other_type_as_type_hint(bool use_lhs_as_type_hint, Type *other_type return false; } +Type *check_matrix_type_hint(Type *matrix, Type *type_hint) { + Type *xt = base_type(matrix); + if (type_hint != nullptr) { + Type *th = base_type(type_hint); + if (are_types_identical(th, xt)) { + return type_hint; + } else if (xt->kind == Type_Matrix && th->kind == Type_Array) { + if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) { + // ignore + } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) { + return type_hint; + } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) { + return type_hint; + } + } + } + return matrix; +} + void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand *y, Type *type_hint, bool use_lhs_as_type_hint) { if (!check_binary_op(c, x, op)) { @@ -2791,21 +2810,8 @@ void check_binary_matrix(CheckerContext *c, Token const &op, Operand *x, Operand } matrix_success: - if (type_hint != nullptr) { - Type *th = base_type(type_hint); - if (are_types_identical(th, x->type)) { - x->type = type_hint; - } else if (x->type->kind == Type_Matrix && th->kind == Type_Array) { - Type *xt = x->type; - if (!are_types_identical(xt->Matrix.elem, th->Array.elem)) { - // ignore - } else if (xt->Matrix.row_count == 1 && xt->Matrix.column_count == th->Array.count) { - x->type = type_hint; - } else if (xt->Matrix.column_count == 1 && xt->Matrix.row_count == th->Array.count) { - x->type = type_hint; - } - } - } + x->type = check_matrix_type_hint(x->type, type_hint); + return; diff --git a/src/checker_builtin_procs.hpp b/src/checker_builtin_procs.hpp index 8991d2d5c..21a33bdd3 100644 --- a/src/checker_builtin_procs.hpp +++ b/src/checker_builtin_procs.hpp @@ -34,6 +34,8 @@ enum BuiltinProcId { BuiltinProc_soa_zip, BuiltinProc_soa_unzip, + + BuiltinProc_transpose, BuiltinProc_DIRECTIVE, // NOTE(bill): This is used for specialized hash-prefixed procedures @@ -274,6 +276,8 @@ gb_global BuiltinProc builtin_procs[BuiltinProc_COUNT] = { {STR_LIT("soa_zip"), 1, true, Expr_Expr, BuiltinProcPkg_builtin}, {STR_LIT("soa_unzip"), 1, false, Expr_Expr, BuiltinProcPkg_builtin}, + + {STR_LIT("transpose"), 1, false, Expr_Expr, BuiltinProcPkg_builtin}, {STR_LIT(""), 0, true, Expr_Expr, BuiltinProcPkg_builtin}, // DIRECTIVE diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index 518ce33af..d41a0a127 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -502,116 +502,29 @@ bool lb_matrix_elem_simple(Type *t) { return true; } -LLVMValueRef llvm_matrix_column_major_load(lbProcedure *p, lbValue lhs) { - lbModule *m = p->module; - - Type *mt = base_type(lhs.type); - GB_ASSERT(mt->kind == Type_Matrix); - GB_ASSERT(lb_matrix_elem_simple(mt)); - - - i64 stride = matrix_type_stride_in_elems(mt); - i64 rows = mt->Matrix.row_count; - i64 columns = mt->Matrix.column_count; - unsigned elem_count = cast(unsigned)(rows*columns); - - Type *elem = mt->Matrix.elem; - LLVMTypeRef elem_type = lb_type(m, elem); - - LLVMTypeRef vector_type = LLVMVectorType(elem_type, elem_count); - LLVMTypeRef types[] = {vector_type}; - - char const *name = "llvm.matrix.column.major.load"; - unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); - GB_ASSERT_MSG(id != 0, "Unable to find %s", name); - LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); - - lbValue ptr = lb_address_from_load_or_generate_local(p, lhs); - ptr = lb_emit_matrix_epi(p, ptr, 0, 0); - - LLVMValueRef values[5] = {}; - values[0] = ptr.value; - values[1] = lb_const_int(m, t_u64, stride).value; - values[2] = LLVMConstNull(lb_type(m, t_llvm_bool)); - values[3] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; - values[4] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; - - LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); - gb_printf_err("%s\n", LLVMPrintValueToString(call)); - // LLVMAddAttributeAtIndex(call, 0, lb_create_enum_attribute(p->module->ctx, "align", cast(u64)type_align_of(mt))); - return call; -} - -void llvm_matrix_column_major_store(lbProcedure *p, lbAddr addr, LLVMValueRef vector_value) { - lbModule *m = p->module; - - Type *mt = base_type(lb_addr_type(addr)); +lbValue lb_emit_matrix_tranpose(lbProcedure *p, lbValue m, Type *type) { + if (is_type_array(m.type)) { + m.type = type; + return m; + } + Type *mt = base_type(m.type); GB_ASSERT(mt->kind == Type_Matrix); - GB_ASSERT(lb_matrix_elem_simple(mt)); - - LLVMTypeRef vector_type = LLVMTypeOf(vector_value); - LLVMTypeRef types[] = {vector_type}; - - char const *name = "llvm.matrix.column.major.store"; - unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); - GB_ASSERT_MSG(id != 0, "Unable to find %s", name); - LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); - - lbValue ptr = lb_addr_get_ptr(p, addr); - ptr = lb_emit_matrix_epi(p, ptr, 0, 0); - - unsigned vector_size = LLVMGetVectorSize(vector_type); - GB_ASSERT((mt->Matrix.row_count*mt->Matrix.column_count) == cast(i64)vector_size); - i64 stride = matrix_type_stride_in_elems(mt); - - LLVMValueRef values[6] = {}; - values[0] = vector_value; - values[1] = ptr.value; - values[2] = lb_const_int(m, t_u64, stride).value; - values[3] = LLVMConstNull(lb_type(m, t_llvm_bool)); - values[4] = lb_const_int(m, t_u32, mt->Matrix.row_count).value; - values[5] = lb_const_int(m, t_u32, mt->Matrix.column_count).value; + lbAddr res = lb_add_local_generated(p, type, true); - LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); - gb_printf_err("%s\n", LLVMPrintValueToString(call)); - // LLVMAddAttributeAtIndex(call, 1, lb_create_enum_attribute(p->module->ctx, "align", cast(u64)type_align_of(mt))); - gb_unused(call); -} - + i64 row_count = mt->Matrix.row_count; + i64 column_count = mt->Matrix.column_count; + for (i64 j = 0; j < column_count; j++) { + for (i64 i = 0; i < row_count; i++) { + lbValue src = lb_emit_matrix_ev(p, m, i, j); + lbValue dst = lb_emit_matrix_epi(p, res.addr, j, i); + lb_emit_store(p, dst, src); + } + } + return lb_addr_load(p, res); -LLVMValueRef llvm_matrix_multiply(lbProcedure *p, LLVMValueRef a, LLVMValueRef b, i64 outer_rows, i64 inner, i64 outer_columns) { - lbModule *m = p->module; - - LLVMTypeRef a_type = LLVMTypeOf(a); - LLVMTypeRef b_type = LLVMTypeOf(b); - - GB_ASSERT(LLVMGetElementType(a_type) == LLVMGetElementType(b_type)); - - LLVMTypeRef elem_type = LLVMGetElementType(a_type); - - LLVMTypeRef res_vector_type = LLVMVectorType(elem_type, cast(unsigned)(outer_rows*outer_columns)); - - LLVMTypeRef types[] = {res_vector_type, a_type, b_type}; - - char const *name = "llvm.matrix.multiply"; - unsigned id = LLVMLookupIntrinsicID(name, gb_strlen(name)); - GB_ASSERT_MSG(id != 0, "Unable to find %s", name); - LLVMValueRef ip = LLVMGetIntrinsicDeclaration(m->mod, id, types, gb_count_of(types)); - - LLVMValueRef values[5] = {}; - values[0] = a; - values[1] = b; - values[2] = lb_const_int(m, t_u32, outer_rows).value; - values[3] = lb_const_int(m, t_u32, inner).value; - values[4] = lb_const_int(m, t_u32, outer_columns).value; - - LLVMValueRef call = LLVMBuildCall(p->builder, ip, values, gb_count_of(values), ""); - gb_printf_err("%s\n", LLVMPrintValueToString(call)); - return call; } - lbValue lb_emit_matrix_mul(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) { Type *xt = base_type(lhs.type); Type *yt = base_type(rhs.type); @@ -626,18 +539,6 @@ lbValue lb_emit_matrix_mul(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) goto slow_form; } - if (false) { - // TODO(bill): LLVM ERROR: Do not know how to split the result of this operator! - lbAddr res = lb_add_local_generated(p, type, true); - - LLVMValueRef a = llvm_matrix_column_major_load(p, lhs); gb_unused(a); - LLVMValueRef b = llvm_matrix_column_major_load(p, rhs); gb_unused(b); - LLVMValueRef c = llvm_matrix_multiply(p, a, b, xt->Matrix.row_count, xt->Matrix.column_count, yt->Matrix.column_count); gb_unused(c); - llvm_matrix_column_major_store(p, res, c); - - return lb_addr_load(p, res); - } - slow_form: { Type *elem = xt->Matrix.elem; diff --git a/src/llvm_backend_proc.cpp b/src/llvm_backend_proc.cpp index 222161164..1431fffaa 100644 --- a/src/llvm_backend_proc.cpp +++ b/src/llvm_backend_proc.cpp @@ -1257,6 +1257,12 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, return lb_soa_zip(p, ce, tv); case BuiltinProc_soa_unzip: return lb_soa_unzip(p, ce, tv); + + case BuiltinProc_transpose: + { + lbValue m = lb_build_expr(p, ce->args[0]); + return lb_emit_matrix_tranpose(p, m, tv.type); + } // "Intrinsics" -- cgit v1.2.3 From d67d7168e2d4ed8e0e5f0d1b23aba5e5ebac6847 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 21 Oct 2021 00:04:22 +0100 Subject: Allow scalars with matrices --- src/check_expr.cpp | 8 ++++++++ src/llvm_backend_const.cpp | 2 +- src/llvm_backend_expr.cpp | 32 ++++++++++++++++++++++++-------- 3 files changed, 33 insertions(+), 9 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 8a1e5fd86..498bf78c7 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -657,6 +657,14 @@ i64 check_distance_between_types(CheckerContext *c, Operand *operand, Type *type return distance + 6; } } + + if (is_type_matrix(dst)) { + Type *elem = base_array_type(dst); + i64 distance = check_distance_between_types(c, operand, elem); + if (distance >= 0) { + return distance + 7; + } + } if (is_type_any(dst)) { if (!is_type_polymorphic(src)) { diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index 413fb365b..554255f47 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -527,7 +527,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc i64 total_elem_count = matrix_type_total_elems(type); LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)total_elem_count); for (i64 i = 0; i < row; i++) { - elems[matrix_index_to_offset(type, i)] = single_elem.value; + elems[matrix_indices_to_offset(type, i, i)] = single_elem.value; } for (i64 i = 0; i < total_elem_count; i++) { if (elems[i] == nullptr) { diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index beb860383..cdc1deea1 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -331,7 +331,7 @@ bool lb_try_direct_vector_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbVal z = LLVMBuildFRem(p->builder, x, y, ""); break; default: - GB_PANIC("Unsupported vector operation"); + GB_PANIC("Unsupported vector operation %.*s", LIT(token_strings[op])); break; } @@ -918,10 +918,11 @@ lbValue lb_emit_vector_mul_matrix(lbProcedure *p, lbValue lhs, lbValue rhs, Type lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type, bool component_wise=false) { GB_ASSERT(is_type_matrix(lhs.type) || is_type_matrix(rhs.type)); - Type *xt = base_type(lhs.type); - Type *yt = base_type(rhs.type); if (op == Token_Mul && !component_wise) { + Type *xt = base_type(lhs.type); + Type *yt = base_type(rhs.type); + if (xt->kind == Type_Matrix) { if (yt->kind == Type_Matrix) { return lb_emit_matrix_mul(p, lhs, rhs, type); @@ -934,21 +935,36 @@ lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue } } else { - GB_ASSERT(are_types_identical(xt, yt)); + if (is_type_matrix(lhs.type)) { + rhs = lb_emit_conv(p, rhs, lhs.type); + } else { + lhs = lb_emit_conv(p, lhs, rhs.type); + } + + Type *xt = base_type(lhs.type); + Type *yt = base_type(rhs.type); + + GB_ASSERT_MSG(are_types_identical(xt, yt), "%s %.*s %s", type_to_string(lhs.type), LIT(token_strings[op]), type_to_string(rhs.type)); GB_ASSERT(xt->kind == Type_Matrix); // element-wise arithmetic // pretend it is an array lbValue array_lhs = lhs; lbValue array_rhs = rhs; Type *array_type = alloc_type_array(xt->Matrix.elem, matrix_type_total_elems(xt)); - GB_ASSERT(type_size_of(array_type) == type_size_of(type)); + GB_ASSERT(type_size_of(array_type) == type_size_of(xt)); array_lhs.type = array_type; array_rhs.type = array_type; - lbValue array = lb_emit_arith_array(p, op, array_lhs, array_rhs, array_type); - array.type = type; - return array; + if (token_is_comparison(op)) { + lbValue res = lb_emit_comp(p, op, array_lhs, array_rhs); + return lb_emit_conv(p, res, type); + } else { + lbValue array = lb_emit_arith(p, op, array_lhs, array_rhs, array_type); + array.type = type; + return array; + } + } GB_PANIC("TODO: lb_emit_arith_matrix"); -- cgit v1.2.3 From e0b9475378f4d69ebaf3e141ed941674b2c0d3f3 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 21 Oct 2021 01:14:44 +0100 Subject: Allow casting between square matrices of the same element type --- src/check_expr.cpp | 19 +++++++++++++++++++ src/check_type.cpp | 10 +++++----- src/llvm_backend_expr.cpp | 44 ++++++++++++++++++++++++++++++++------------ 3 files changed, 56 insertions(+), 17 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 498bf78c7..ad12e00c8 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -2460,6 +2460,24 @@ bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) { if (is_type_quaternion(src) && is_type_quaternion(dst)) { return true; } + + if (is_type_matrix(src) && is_type_matrix(dst)) { + GB_ASSERT(src->kind == Type_Matrix); + GB_ASSERT(dst->kind == Type_Matrix); + if (!are_types_identical(src->Matrix.elem, dst->Matrix.elem)) { + return false; + } + + if (src->Matrix.row_count != src->Matrix.column_count) { + return false; + } + + if (dst->Matrix.row_count != dst->Matrix.column_count) { + return false; + } + + return true; + } // Cast between pointers @@ -8838,6 +8856,7 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type case Ast_EnumType: case Ast_MapType: case Ast_BitSetType: + case Ast_MatrixType: o->mode = Addressing_Type; o->type = check_type(c, node); break; diff --git a/src/check_type.cpp b/src/check_type.cpp index d9302c65a..21c8a9f19 100644 --- a/src/check_type.cpp +++ b/src/check_type.cpp @@ -1154,7 +1154,11 @@ Type *determine_type_from_polymorphic(CheckerContext *ctx, Type *poly_type, Oper bool show_error = modify_type && !ctx->hide_polymorphic_errors; if (!is_operand_value(operand)) { if (show_error) { - error(operand.expr, "Cannot determine polymorphic type from parameter"); + gbString pts = type_to_string(poly_type); + gbString ots = type_to_string(operand.type); + defer (gb_string_free(pts)); + defer (gb_string_free(ots)); + error(operand.expr, "Cannot determine polymorphic type from parameter: '%s' to '%s'", ots, pts); } return t_invalid; } @@ -2839,10 +2843,6 @@ bool check_type_internal(CheckerContext *ctx, Ast *e, Type **type, Type *named_t case_ast_node(mt, MatrixType, e); - bool ips = ctx->in_polymorphic_specialization; - defer (ctx->in_polymorphic_specialization = ips); - ctx->in_polymorphic_specialization = false; - check_matrix_type(ctx, type, e); set_base_type(named_type, *type); return true; diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index cdc1deea1..9582be93c 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -476,7 +476,7 @@ lbValue lb_emit_arith_array(lbProcedure *p, TokenKind op, lbValue lhs, lbValue r } } -bool lb_matrix_elem_simple(Type *t) { +bool lb_is_matrix_simdable(Type *t) { Type *mt = base_type(t); GB_ASSERT(mt->kind == Type_Matrix); @@ -555,7 +555,7 @@ lbValue lb_emit_matrix_tranpose(lbProcedure *p, lbValue m, Type *type) { Type *mt = base_type(m.type); GB_ASSERT(mt->kind == Type_Matrix); - if (lb_matrix_elem_simple(mt)) { + if (lb_is_matrix_simdable(mt)) { unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt); unsigned row_count = cast(unsigned)mt->Matrix.row_count; unsigned column_count = cast(unsigned)mt->Matrix.column_count; @@ -623,7 +623,7 @@ lbValue lb_emit_matrix_flatten(lbProcedure *p, lbValue m, Type *type) { Type *mt = base_type(m.type); GB_ASSERT(mt->kind == Type_Matrix); - if (lb_matrix_elem_simple(mt)) { + if (lb_is_matrix_simdable(mt)) { LLVMValueRef vector = lb_matrix_to_trimmed_vector(p, m); return lb_matrix_cast_vector_to_type(p, vector, type); } @@ -690,7 +690,7 @@ lbValue lb_emit_matrix_mul(lbProcedure *p, lbValue lhs, lbValue rhs, Type *type) unsigned inner = cast(unsigned)xt->Matrix.column_count; unsigned outer_columns = cast(unsigned)yt->Matrix.column_count; - if (lb_matrix_elem_simple(xt)) { + if (lb_is_matrix_simdable(xt)) { unsigned x_stride = cast(unsigned)matrix_type_stride_in_elems(xt); unsigned y_stride = cast(unsigned)matrix_type_stride_in_elems(yt); @@ -773,7 +773,7 @@ lbValue lb_emit_matrix_mul_vector(lbProcedure *p, lbValue lhs, lbValue rhs, Type Type *elem = mt->Matrix.elem; - if (lb_matrix_elem_simple(mt)) { + if (lb_is_matrix_simdable(mt)) { unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt); unsigned row_count = cast(unsigned)mt->Matrix.row_count; @@ -819,9 +819,8 @@ lbValue lb_emit_matrix_mul_vector(lbProcedure *p, lbValue lhs, lbValue rhs, Type lbValue a = lb_emit_matrix_ev(p, lhs, i, j); lbValue b = lb_emit_struct_ev(p, rhs, cast(i32)j); - lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); - lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); - lb_emit_store(p, dst, d); + lbValue c = lb_emit_mul_add(p, a, b, d0, elem); + lb_emit_store(p, dst, c); } } @@ -842,7 +841,7 @@ lbValue lb_emit_vector_mul_matrix(lbProcedure *p, lbValue lhs, lbValue rhs, Type Type *elem = mt->Matrix.elem; - if (lb_matrix_elem_simple(mt)) { + if (lb_is_matrix_simdable(mt)) { unsigned stride = cast(unsigned)matrix_type_stride_in_elems(mt); unsigned row_count = cast(unsigned)mt->Matrix.row_count; @@ -903,9 +902,8 @@ lbValue lb_emit_vector_mul_matrix(lbProcedure *p, lbValue lhs, lbValue rhs, Type lbValue a = lb_emit_struct_ev(p, lhs, cast(i32)k); lbValue b = lb_emit_matrix_ev(p, rhs, k, j); - lbValue c = lb_emit_arith(p, Token_Mul, a, b, elem); - lbValue d = lb_emit_arith(p, Token_Add, d0, c, elem); - lb_emit_store(p, dst, d); + lbValue c = lb_emit_mul_add(p, a, b, d0, elem); + lb_emit_store(p, dst, c); } } @@ -1938,6 +1936,28 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return lb_addr_load(p, v); } + + if (is_type_matrix(dst) && is_type_matrix(src)) { + GB_ASSERT(dst->kind == Type_Matrix); + GB_ASSERT(src->kind == Type_Matrix); + lbAddr v = lb_add_local_generated(p, t, true); + for (i64 j = 0; j < dst->Matrix.column_count; j++) { + for (i64 i = 0; i < dst->Matrix.row_count; i++) { + if (i < src->Matrix.row_count && j < src->Matrix.column_count) { + lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); + lbValue s = lb_emit_matrix_ev(p, value, i, j); + lb_emit_store(p, d, s); + } else if (i == j) { + lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); + lbValue s = lb_const_value(p->module, dst->Matrix.elem, exact_value_i64(1), true); + lb_emit_store(p, d, s); + } + } + } + return lb_addr_load(p, v); + } + + if (is_type_any(dst)) { if (is_type_untyped_nil(src)) { -- cgit v1.2.3 From 48d277a3c4604481074df2914efbaba9e0dbed25 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 21 Oct 2021 01:34:39 +0100 Subject: Allow conversions between matrices of the same element count --- src/check_expr.cpp | 4 +++- src/llvm_backend_const.cpp | 4 ++-- src/llvm_backend_expr.cpp | 38 ++++++++++++++++++++++++++++---------- src/types.cpp | 34 +++++++++++++--------------------- 4 files changed, 46 insertions(+), 34 deletions(-) (limited to 'src/check_expr.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index ad12e00c8..ee7493553 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -2469,7 +2469,9 @@ bool check_is_castable_to(CheckerContext *c, Operand *operand, Type *y) { } if (src->Matrix.row_count != src->Matrix.column_count) { - return false; + i64 src_count = src->Matrix.row_count*src->Matrix.column_count; + i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count; + return src_count == dst_count; } if (dst->Matrix.row_count != dst->Matrix.column_count) { diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index 554255f47..b543089e5 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -524,7 +524,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc lbValue single_elem = lb_const_value(m, elem, value, allow_local); single_elem.value = llvm_const_cast(single_elem.value, lb_type(m, elem)); - i64 total_elem_count = matrix_type_total_elems(type); + i64 total_elem_count = matrix_type_total_internal_elems(type); LLVMValueRef *elems = gb_alloc_array(permanent_allocator(), LLVMValueRef, cast(isize)total_elem_count); for (i64 i = 0; i < row; i++) { elems[matrix_indices_to_offset(type, i, i)] = single_elem.value; @@ -990,7 +990,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bool allow_loc } i64 max_count = type->Matrix.row_count*type->Matrix.column_count; - i64 total_count = matrix_type_total_elems(type); + i64 total_count = matrix_type_total_internal_elems(type); LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, cast(isize)total_count); if (cl->elems[0]->kind == Ast_FieldValue) { diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index 9582be93c..eb88bbde0 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -508,7 +508,7 @@ LLVMValueRef lb_matrix_to_vector(lbProcedure *p, lbValue matrix) { GB_ASSERT(mt->kind == Type_Matrix); LLVMTypeRef elem_type = lb_type(p->module, mt->Matrix.elem); - unsigned total_count = cast(unsigned)matrix_type_total_elems(mt); + unsigned total_count = cast(unsigned)matrix_type_total_internal_elems(mt); LLVMTypeRef total_matrix_type = LLVMVectorType(elem_type, total_count); LLVMValueRef ptr = lb_address_from_load_or_generate_local(p, matrix).value; @@ -948,7 +948,7 @@ lbValue lb_emit_arith_matrix(lbProcedure *p, TokenKind op, lbValue lhs, lbValue // pretend it is an array lbValue array_lhs = lhs; lbValue array_rhs = rhs; - Type *array_type = alloc_type_array(xt->Matrix.elem, matrix_type_total_elems(xt)); + Type *array_type = alloc_type_array(xt->Matrix.elem, matrix_type_total_internal_elems(xt)); GB_ASSERT(type_size_of(array_type) == type_size_of(xt)); array_lhs.type = array_type; @@ -1941,15 +1941,33 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { GB_ASSERT(dst->kind == Type_Matrix); GB_ASSERT(src->kind == Type_Matrix); lbAddr v = lb_add_local_generated(p, t, true); - for (i64 j = 0; j < dst->Matrix.column_count; j++) { - for (i64 i = 0; i < dst->Matrix.row_count; i++) { - if (i < src->Matrix.row_count && j < src->Matrix.column_count) { - lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); + + if (is_matrix_square(dst) && is_matrix_square(dst)) { + for (i64 j = 0; j < dst->Matrix.column_count; j++) { + for (i64 i = 0; i < dst->Matrix.row_count; i++) { + if (i < src->Matrix.row_count && j < src->Matrix.column_count) { + lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); + lbValue s = lb_emit_matrix_ev(p, value, i, j); + lb_emit_store(p, d, s); + } else if (i == j) { + lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); + lbValue s = lb_const_value(p->module, dst->Matrix.elem, exact_value_i64(1), true); + lb_emit_store(p, d, s); + } + } + } + } else { + i64 dst_count = dst->Matrix.row_count*dst->Matrix.column_count; + i64 src_count = src->Matrix.row_count*src->Matrix.column_count; + GB_ASSERT(dst_count == src_count); + + for (i64 j = 0; j < src->Matrix.column_count; j++) { + for (i64 i = 0; i < src->Matrix.row_count; i++) { lbValue s = lb_emit_matrix_ev(p, value, i, j); - lb_emit_store(p, d, s); - } else if (i == j) { - lbValue d = lb_emit_matrix_epi(p, v.addr, i, j); - lbValue s = lb_const_value(p->module, dst->Matrix.elem, exact_value_i64(1), true); + i64 index = i + j*src->Matrix.row_count; + i64 dst_i = index%dst->Matrix.row_count; + i64 dst_j = index/dst->Matrix.row_count; + lbValue d = lb_emit_matrix_epi(p, v.addr, dst_i, dst_j); lb_emit_store(p, d, s); } } diff --git a/src/types.cpp b/src/types.cpp index d3fa363c2..3abcebdfb 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1293,7 +1293,7 @@ i64 matrix_type_stride_in_elems(Type *t) { } -i64 matrix_type_total_elems(Type *t) { +i64 matrix_type_total_internal_elems(Type *t) { t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); i64 size = type_size_of(t); @@ -1301,37 +1301,29 @@ i64 matrix_type_total_elems(Type *t) { return size/gb_max(elem_size, 1); } -void matrix_indices_from_index(Type *t, i64 index, i64 *row_index_, i64 *column_index_) { +i64 matrix_indices_to_offset(Type *t, i64 row_index, i64 column_index) { t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); - i64 row_count = t->Matrix.row_count; - i64 column_count = t->Matrix.column_count; - GB_ASSERT(0 <= index && index < row_count*column_count); - - i64 row_index = index / column_count; - i64 column_index = index % column_count; - - if (row_index_) *row_index_ = row_index; - if (column_index_) *column_index_ = column_index; + GB_ASSERT(0 <= row_index && row_index < t->Matrix.row_count); + GB_ASSERT(0 <= column_index && column_index < t->Matrix.column_count); + i64 stride_elems = matrix_type_stride_in_elems(t); + return stride_elems*column_index + row_index; } - i64 matrix_index_to_offset(Type *t, i64 index) { t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); - i64 row_index, column_index; - matrix_indices_from_index(t, index, &row_index, &column_index); - i64 stride_elems = matrix_type_stride_in_elems(t); - return stride_elems*column_index + row_index; + i64 row_index = index%t->Matrix.row_count; + i64 column_index = index/t->Matrix.row_count; + return matrix_indices_to_offset(t, row_index, column_index); } -i64 matrix_indices_to_offset(Type *t, i64 row_index, i64 column_index) { + + +bool is_matrix_square(Type *t) { t = base_type(t); GB_ASSERT(t->kind == Type_Matrix); - GB_ASSERT(0 <= row_index && row_index < t->Matrix.row_count); - GB_ASSERT(0 <= column_index && column_index < t->Matrix.column_count); - i64 stride_elems = matrix_type_stride_in_elems(t); - return stride_elems*column_index + row_index; + return t->Matrix.row_count == t->Matrix.column_count; } bool is_type_valid_for_matrix_elems(Type *t) { -- cgit v1.2.3