From ca442defbbaae4269ff947dfc14059f69a5cdaec Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 14 Jul 2023 17:34:00 +0100 Subject: Mocking out call related stuff --- src/tilde_proc.cpp | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 src/tilde_proc.cpp (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp new file mode 100644 index 000000000..306852db3 --- /dev/null +++ b/src/tilde_proc.cpp @@ -0,0 +1,5 @@ +gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { + ast_node(ce, CallExpr, expr); + // TODO(bill): cg_build_call_expr + return {}; +} \ No newline at end of file -- cgit v1.2.3 From e2e5641a450f4d7ea67eae468f1bd479361ec198 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 15 Jul 2023 13:15:50 +0100 Subject: Update TB; Fix calling nullptr TB_Node* problems --- src/tilde/tb.h | 56 +++++++++++----------- src/tilde/tb.lib | Bin 4295348 -> 4120106 bytes src/tilde_backend.cpp | 32 +++++++------ src/tilde_backend.hpp | 4 +- src/tilde_const.cpp | 14 +++++- src/tilde_expr.cpp | 3 +- src/tilde_proc.cpp | 126 +++++++++++++++++++++++++++++++++++++++++++++++++- src/tilde_stmt.cpp | 19 ++++---- 8 files changed, 196 insertions(+), 58 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 0f0aaf4c6..8b698ff30 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -439,7 +439,7 @@ struct TB_Node { typedef struct { // TB_BRANCH // avoid empty structs with flexible members int64_t _; - int64_t keys[/* input_count - 1 */]; + int64_t keys[]; } TB_NodeBranch; typedef struct { // TB_PROJ @@ -538,19 +538,6 @@ typedef struct { TB_Node* value; } TB_SwitchEntry; -typedef struct TB_Loop { - // refers to another entry in TB_LoopInfo... unless it's -1 - ptrdiff_t parent_loop; - - TB_Node* header; - TB_Node* backedge; -} TB_Loop; - -typedef struct TB_LoopInfo { - size_t count; - TB_Loop* loops; -} TB_LoopInfo; - typedef enum { TB_EXECUTABLE_UNKNOWN, TB_EXECUTABLE_PE, @@ -648,7 +635,7 @@ TB_API void tb_module_destroy(TB_Module* m); // When targetting windows & thread local storage, you'll need to bind a tls index // which is usually just a global that the runtime support has initialized, if you // dont and the tls_index is used, it'll crash -TB_API void tb_module_set_tls_index(TB_Module* m, const char* name); +TB_API void tb_module_set_tls_index(TB_Module* m, ptrdiff_t len, const char* name); // You don't need to manually call this unless you want to resolve locations before // exporting. @@ -756,7 +743,7 @@ TB_API TB_External* tb_next_external(TB_External* e); TB_API TB_ExternalType tb_extern_get_type(TB_External* e); TB_Global* tb_extern_transmute(TB_External* e, TB_DebugType* dbg_type, TB_Linkage linkage); -TB_API TB_External* tb_extern_create(TB_Module* m, const char* name, TB_ExternalType type); +TB_API TB_External* tb_extern_create(TB_Module* m, ptrdiff_t len, const char* name, TB_ExternalType type); TB_API TB_FileID tb_file_create(TB_Module* m, const char* path); // Called once you're done with TB operations on a thread (or i guess when it's @@ -798,7 +785,7 @@ TB_API TB_FunctionPrototype* tb_prototype_create(TB_Module* m, TB_CallingConv cc //////////////////////////////// // Globals //////////////////////////////// -TB_API TB_Global* tb_global_create(TB_Module* m, const char* name, TB_DebugType* dbg_type, TB_Linkage linkage); +TB_API TB_Global* tb_global_create(TB_Module* m, ptrdiff_t len, const char* name, TB_DebugType* dbg_type, TB_Linkage linkage); // allocate space for the global TB_API void tb_global_set_storage(TB_Module* m, TB_ModuleSection* section, TB_Global* global, size_t size, size_t align, size_t max_objects); @@ -818,8 +805,11 @@ TB_API TB_ModuleSection* tb_module_get_tls(TB_Module* m); //////////////////////////////// // Function Attributes //////////////////////////////// +TB_API void tb_node_append_attrib(TB_Node* n, TB_Attrib* a); + // These are parts of a function that describe metadata for instructions -TB_API void tb_function_attrib_variable(TB_Function* f, TB_Node* n, const char* name, TB_DebugType* type); +TB_API TB_Attrib* tb_function_attrib_variable(TB_Function* f, ptrdiff_t len, const char* name, TB_DebugType* type); +TB_API TB_Attrib* tb_function_attrib_scope(TB_Function* f, TB_Attrib* parent_scope); //////////////////////////////// // Debug info Generation @@ -830,9 +820,9 @@ TB_API TB_DebugType* tb_debug_get_integer(TB_Module* m, bool is_signed, int bits TB_API TB_DebugType* tb_debug_get_float(TB_Module* m, TB_FloatFormat fmt); TB_API TB_DebugType* tb_debug_create_ptr(TB_Module* m, TB_DebugType* base); TB_API TB_DebugType* tb_debug_create_array(TB_Module* m, TB_DebugType* base, size_t count); -TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, const char* tag); -TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, const char* tag); -TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, const char* name, TB_CharUnits offset); +TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, ptrdiff_t len, const char* tag); +TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, ptrdiff_t len, const char* tag); +TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, ptrdiff_t len, const char* name, TB_CharUnits offset); TB_API void tb_debug_complete_record(TB_DebugType* type, TB_DebugType** members, size_t count, TB_CharUnits size, TB_CharUnits align); //////////////////////////////// @@ -869,12 +859,14 @@ TB_API void tb_inst_set_location(TB_Function* f, TB_FileID file, int line); TB_API TB_DataType tb_vector_type(TB_DataTypeEnum type, int width); // if section is NULL, default to .text -TB_API TB_Function* tb_function_create(TB_Module* m, const char* name, TB_Linkage linkage, TB_ComdatType comdat); +TB_API TB_Function* tb_function_create(TB_Module* m, ptrdiff_t len, const char* name, TB_Linkage linkage, TB_ComdatType comdat); TB_API void* tb_function_get_jit_pos(TB_Function* f); +// if len is -1, it's null terminated +TB_API void tb_symbol_set_name(TB_Symbol* s, ptrdiff_t len, const char* name); + TB_API void tb_symbol_bind_ptr(TB_Symbol* s, void* ptr); -TB_API void tb_symbol_set_name(TB_Symbol* s, const char* name); TB_API const char* tb_symbol_get_name(TB_Symbol* s); // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources @@ -915,7 +907,6 @@ TB_API TB_Node* tb_inst_load(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_C TB_API void tb_inst_store(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_Node* val, TB_CharUnits align, bool is_volatile); TB_API TB_Node* tb_inst_bool(TB_Function* f, bool imm); -TB_API TB_Node* tb_inst_ptr(TB_Function* f, uint64_t imm); TB_API TB_Node* tb_inst_sint(TB_Function* f, TB_DataType dt, int64_t imm); TB_API TB_Node* tb_inst_uint(TB_Function* f, TB_DataType dt, uint64_t imm); TB_API TB_Node* tb_inst_float32(TB_Function* f, float imm); @@ -923,9 +914,12 @@ TB_API TB_Node* tb_inst_float64(TB_Function* f, double imm); TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* str); TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); -// Broadcasts 'val' across 'count' elements starting 'dst' +// write 'val' over 'count' bytes on 'dst' TB_API void tb_inst_memset(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); +// zero 'count' bytes on 'dst' +TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); + // performs a copy of 'count' elements from one memory location to another // both locations cannot overlap. TB_API void tb_inst_memcpy(TB_Function* f, TB_Node* dst, TB_Node* src, TB_Node* count, TB_CharUnits align, bool is_volatile); @@ -1052,13 +1046,15 @@ TB_API TB_FuncOpt* tb_funcopt_enter(TB_Function* f, TB_Arena* arena); TB_API void tb_funcopt_exit(TB_FuncOpt* opt); TB_API bool tb_funcopt_peephole(TB_FuncOpt* opt); -TB_API bool tb_funcopt_mem2reg(TB_FuncOpt* f); -TB_API bool tb_funcopt_loop(TB_FuncOpt* f); +TB_API bool tb_funcopt_mem2reg(TB_FuncOpt* opt); +TB_API bool tb_funcopt_loop(TB_FuncOpt* opt); -TB_API void tb_funcopt_kill(TB_FuncOpt* restrict queue, TB_Node* n); +// isn't an optimization, just does the name flat form of IR printing +TB_API bool tb_funcopt_print(TB_FuncOpt* opt); -TB_API bool tb_funcopt_mark(TB_FuncOpt* restrict queue, TB_Node* n); -TB_API void tb_funcopt_mark_users(TB_FuncOpt* restrict queue, TB_Node* n); +TB_API void tb_funcopt_kill(TB_FuncOpt* opt, TB_Node* n); +TB_API bool tb_funcopt_mark(TB_FuncOpt* opt, TB_Node* n); +TB_API void tb_funcopt_mark_users(TB_FuncOpt* opt, TB_Node* n); //////////////////////////////// // IR access diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index a1f893968..a6ac5cbff 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index d695c846c..0572e2fd0 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -184,7 +184,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); Type *t = alloc_type_array(t_type_info, max_type_info_count); - TB_Global *g = tb_global_create(m->mod, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); cgValue value = cg_value(g, alloc_type_pointer(t)); @@ -219,7 +219,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_TYPES_NAME; Type *t = alloc_type_array(t_type_info_ptr, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_types = cg_addr(cg_value(g, alloc_type_pointer(t))); @@ -227,14 +227,14 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_NAMES_NAME; Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_names = cg_addr(cg_value(g, alloc_type_pointer(t))); } { char const *name = CG_TYPE_INFO_OFFSETS_NAME; Type *t = alloc_type_array(t_uintptr, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_offsets = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -242,7 +242,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_USINGS_NAME; Type *t = alloc_type_array(t_bool, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_usings = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -250,7 +250,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_TAGS_NAME; Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_tags = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -268,7 +268,7 @@ cgModule *cg_module_create(Checker *c) { TB_FeatureSet feature_set = {}; bool is_jit = false; m->mod = tb_module_create(TB_ARCH_X86_64, TB_SYSTEM_WINDOWS, &feature_set, is_jit); - tb_module_set_tls_index(m->mod, "_tls_index"); + tb_module_set_tls_index(m->mod, 10, "_tls_index"); map_init(&m->values); array_init(&m->procedures_to_generate, heap_allocator()); @@ -634,8 +634,6 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i // p->scope_stack.allocator = a; // map_init(&p->tuple_fix_map, 0); - char const *link_name_c = alloc_cstring(temporary_allocator(), link_name); - TB_Linkage linkage = TB_LINKAGE_PRIVATE; if (p->is_export) { linkage = TB_LINKAGE_PUBLIC; @@ -643,11 +641,11 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i if (ignore_body) { linkage = TB_LINKAGE_PUBLIC; } - p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name_c, TB_EXTERNAL_SO_LOCAL); + p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); } if (p->symbol == nullptr) { - p->func = tb_function_create(m->mod, link_name_c, linkage, TB_COMDAT_NONE); + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); p->symbol = cast(TB_Symbol *)p->func; } @@ -688,12 +686,9 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li // map_init(&p->tuple_fix_map, 0); - - char const *link_name_c = alloc_cstring(temporary_allocator(), link_name); - TB_Linkage linkage = TB_LINKAGE_PRIVATE; - p->func = tb_function_create(m->mod, link_name_c, linkage, TB_COMDAT_NONE); + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); p->symbol = cast(TB_Symbol *)p->func; @@ -715,6 +710,13 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } tb_inst_ret(p->func, 0, nullptr); + if (p->name == "main") { + TB_Arena *arena = tb_default_arena(); + defer (arena->free(arena)); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + tb_funcopt_print(opt); + } tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); } diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 44591190a..6c17f8ba3 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -212,4 +212,6 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); -gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); \ No newline at end of file +gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); + +gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 7a8be70c7..97fee838e 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -8,7 +8,7 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { TB_Module *m = p->module->mod; char name[32] = {}; gb_snprintf(name, 31, "cnil$%u", 1+p->module->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *global = tb_global_create(m, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m, tb_module_get_rdata(m), global, size, align, 0); TB_Symbol *symbol = cast(TB_Symbol *)global; @@ -41,6 +41,18 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_const_nil(p, type); } + if (value.kind == ExactValue_Procedure) { + Ast *expr = unparen_expr(value.value_procedure); + Entity *e = entity_of_node(expr); + if (e != nullptr) { + cgValue found = cg_find_procedure_value_from_entity(m, e); + GB_ASSERT(are_types_identical(type, found.type)); + return found; + } + + } + + GB_ASSERT(node != nullptr); return cg_value(node, type); } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index ccd126747..702cb42ad 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -101,7 +101,7 @@ gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { cgValue res = cg_build_expr_internal(p, expr); if (res.kind == cgValue_Symbol) { - GB_ASSERT(is_type_pointer(res.type)); + GB_ASSERT(is_type_internally_pointer_like(res.type)); res = cg_value(tb_inst_get_symbol_address(p->func, res.symbol), res.type); } @@ -161,6 +161,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { token_pos_to_string(token.pos)); return {}; } else if (e->kind == Entity_Nil) { + GB_PANIC("TODO: cg_find_ident nil"); // TODO(bill): is this correct? return cg_value(cast(TB_Node *)nullptr, e->type); } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 306852db3..dbebae853 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1,5 +1,127 @@ +gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) { + GB_ASSERT(is_type_proc(e->type)); + e = strip_entity_wrapping(e); + GB_ASSERT(e != nullptr); + GB_ASSERT(e->kind == Entity_Procedure); + + cgValue *found = nullptr; + rw_mutex_shared_lock(&m->values_mutex); + found = map_get(&m->values, e); + rw_mutex_shared_unlock(&m->values_mutex); + if (found) { + return *found; + } + + GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); + return {}; +} + + + +gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { + expr = unparen_expr(expr); ast_node(ce, CallExpr, expr); - // TODO(bill): cg_build_call_expr + + cgValue res = cg_build_call_expr_internal(p, expr); + + if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures + GB_PANIC("Handle optional_ok_one"); + // GB_ASSERT(is_type_tuple(res.type)); + // GB_ASSERT(res.type->Tuple.variables.count == 2); + // return cg_emit_struct_ev(p, res, 0); + } + return res; +} + +gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice args) { + if (value.kind == cgValue_Symbol) { + value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); + } + GB_ASSERT(value.kind == cgValue_Value); + + TB_FunctionPrototype *proto = cg_procedure_type_as_prototype(p->module, value.type); + TB_Node *target = value.node; + auto params = slice_make(temporary_allocator(), 0); + + GB_ASSERT(target != nullptr); + TB_MultiOutput multi_output = tb_inst_call(p->func, proto, target, 0, nullptr); + gb_unused(multi_output); return {}; -} \ No newline at end of file +} + +gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { + ast_node(ce, CallExpr, expr); + + TypeAndValue tv = type_and_value_of_expr(expr); + + TypeAndValue proc_tv = type_and_value_of_expr(ce->proc); + AddressingMode proc_mode = proc_tv.mode; + if (proc_mode == Addressing_Type) { + GB_ASSERT(ce->args.count == 1); + cgValue x = cg_build_expr(p, ce->args[0]); + return cg_emit_conv(p, x, tv.type); + } + + Ast *proc_expr = unparen_expr(ce->proc); + if (proc_mode == Addressing_Builtin) { + Entity *e = entity_of_node(proc_expr); + BuiltinProcId id = BuiltinProc_Invalid; + if (e != nullptr) { + id = cast(BuiltinProcId)e->Builtin.id; + } else { + id = BuiltinProc_DIRECTIVE; + } + if (id == BuiltinProc___entry_point) { + if (p->module->info->entry_point) { + cgValue entry_point = cg_find_procedure_value_from_entity(p->module, p->module->info->entry_point); + GB_ASSERT(entry_point.node != nullptr); + cg_emit_call(p, entry_point, {}); + } + return {}; + } + GB_PANIC("TODO(bill): builtin procs %d %.*s", id, LIT(builtin_procs[id].name)); + } + + // NOTE(bill): Regular call + cgValue value = {}; + + Entity *proc_entity = entity_of_node(proc_expr); + if (proc_entity != nullptr) { + if (proc_entity->flags & EntityFlag_Disabled) { + GB_ASSERT(tv.type == nullptr); + return {}; + } + } + + if (proc_expr->tav.mode == Addressing_Constant) { + ExactValue v = proc_expr->tav.value; + switch (v.kind) { + case ExactValue_Integer: + { + u64 u = big_int_to_u64(&v.value_integer); + cgValue x = cg_value(tb_inst_uint(p->func, TB_TYPE_PTR, u), t_rawptr); + value = cg_emit_conv(p, x, proc_expr->tav.type); + break; + } + case ExactValue_Pointer: + { + u64 u = cast(u64)v.value_pointer; + cgValue x = cg_value(tb_inst_uint(p->func, TB_TYPE_PTR, u), t_rawptr); + value = cg_emit_conv(p, x, proc_expr->tav.type); + break; + } + } + } + + if (value.node == nullptr) { + value = cg_build_expr(p, proc_expr); + } + if (value.kind == cgValue_Addr) { + value = cg_emit_load(p, value); + } + GB_ASSERT(value.kind == cgValue_Value); + GB_ASSERT(is_type_proc(value.type)); + + return cg_emit_call(p, value, {}); +} diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index f7e68d483..07bfc0555 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -8,14 +8,16 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol case cgValue_Value: return cg_lvalue_addr(ptr.node, type); case cgValue_Addr: - GB_PANIC("NOT POSSIBLE"); + GB_PANIC("NOT POSSIBLE - Cannot load an lvalue to begin with"); break; case cgValue_Symbol: return cg_lvalue_addr(tb_inst_get_symbol_address(p->func, ptr.symbol), type); } } - TB_CharUnits alignment = 1; // for the time being + // use the natural alignment + // if people need a special alignment, they can use `intrinsics.unaligned_load` + TB_CharUnits alignment = cast(TB_CharUnits)type_align_of(type); TB_Node *the_ptr = nullptr; switch (ptr.kind) { @@ -48,7 +50,9 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, TB_DataType st = cg_data_type(src.type); GB_ASSERT(dt.raw == st.raw); - TB_CharUnits alignment = 1; // for the time being + // use the natural alignment + // if people need a special alignment, they can use `intrinsics.unaligned_store` + TB_CharUnits alignment = cast(TB_CharUnits)type_align_of(dst_type); if (TB_IS_VOID_TYPE(dt)) { TB_Node *dst_ptr = nullptr; @@ -281,10 +285,9 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only - char const *name = alloc_cstring(permanent_allocator(), e->token.string); - - TB_DebugType *debug_type = cg_debug_type(p->module, type); - tb_function_attrib_variable(p->func, local, name, debug_type); + // String name = e->token.string; + // TB_DebugType *debug_type = cg_debug_type(p->module, type); + // tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type); } if (zero_init) { @@ -546,7 +549,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_end; case_ast_node(as, AssignStmt, node); - cg_build_assign_stmt(p, as); + // cg_build_assign_stmt(p, as); case_end; case_ast_node(rs, ReturnStmt, node); -- cgit v1.2.3 From ccb736411bc61a0ccde6835cbbf1876a2616e3e1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 15 Jul 2023 13:30:31 +0100 Subject: Basic `context` creation --- src/tilde_backend.cpp | 289 ------------------------------------------------- src/tilde_backend.hpp | 16 ++- src/tilde_expr.cpp | 147 ++++++++++++++++++++++++- src/tilde_proc.cpp | 290 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/tilde_stmt.cpp | 2 +- 5 files changed, 451 insertions(+), 293 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 0572e2fd0..97f92e3db 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -446,295 +446,6 @@ struct cgGlobalVariable { bool is_initialized; }; - -gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Type *type) { - GB_ASSERT(type != nullptr); - type = base_type(type); - GB_ASSERT(type->kind == Type_Proc); - TypeProc *pt = &type->Proc; - - auto params = array_make(heap_allocator(), 0, pt->param_count); - if (pt->params) for (Entity *e : pt->params->Tuple.variables) { - TB_PrototypeParam param = {}; - - Type *t = core_type(e->type); - i64 sz = type_size_of(t); - switch (t->kind) { - case Type_Basic: - switch (t->Basic.kind) { - case Basic_bool: - case Basic_b8: - case Basic_b16: - case Basic_b32: - case Basic_b64: - case Basic_i8: - case Basic_u8: - case Basic_i16: - case Basic_u16: - case Basic_i32: - case Basic_u32: - case Basic_i64: - case Basic_u64: - case Basic_i128: - case Basic_u128: - case Basic_rune: - case Basic_int: - case Basic_uint: - case Basic_uintptr: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); - break; - - case Basic_f16: param.dt = TB_TYPE_I16; break; - case Basic_f32: param.dt = TB_TYPE_F32; break; - case Basic_f64: param.dt = TB_TYPE_F64; break; - - case Basic_complex32: - case Basic_complex64: - case Basic_complex128: - case Basic_quaternion64: - case Basic_quaternion128: - case Basic_quaternion256: - param.dt = TB_TYPE_PTR; - break; - - - case Basic_rawptr: - param.dt = TB_TYPE_PTR; - break; - case Basic_string: // ^u8 + int - param.dt = TB_TYPE_PTR; - break; - case Basic_cstring: // ^u8 - param.dt = TB_TYPE_PTR; - break; - case Basic_any: // rawptr + ^Type_Info - param.dt = TB_TYPE_PTR; - break; - - case Basic_typeid: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); - break; - - // Endian Specific Types - case Basic_i16le: - case Basic_u16le: - case Basic_i32le: - case Basic_u32le: - case Basic_i64le: - case Basic_u64le: - case Basic_i128le: - case Basic_u128le: - case Basic_i16be: - case Basic_u16be: - case Basic_i32be: - case Basic_u32be: - case Basic_i64be: - case Basic_u64be: - case Basic_i128be: - case Basic_u128be: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); - break; - - case Basic_f16le: param.dt = TB_TYPE_I16; break; - case Basic_f32le: param.dt = TB_TYPE_F32; break; - case Basic_f64le: param.dt = TB_TYPE_F64; break; - - case Basic_f16be: param.dt = TB_TYPE_I16; break; - case Basic_f32be: param.dt = TB_TYPE_F32; break; - case Basic_f64be: param.dt = TB_TYPE_F64; break; - } - - case Type_Pointer: - case Type_MultiPointer: - case Type_Proc: - param.dt = TB_TYPE_PTR; - break; - - default: - switch (sz) { - case 1: param.dt = TB_TYPE_I8; break; - case 2: param.dt = TB_TYPE_I16; break; - case 4: param.dt = TB_TYPE_I32; break; - case 8: param.dt = TB_TYPE_I64; break; - default: - param.dt = TB_TYPE_PTR; - break; - } - } - - if (param.dt.width != 0) { - if (is_blank_ident(e->token)) { - param.name = alloc_cstring(temporary_allocator(), e->token.string); - } - array_add(¶ms, param); - } - } - - auto results = array_make(heap_allocator(), 0, pt->result_count); - // if (pt->results) for (Entity *e : pt->params->Tuple.variables) { - // // TODO(bill): - // } - - - return tb_prototype_create(m->mod, TB_CDECL, params.count, params.data, results.count, results.data, pt->c_vararg); -} - -gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body=false) { - GB_ASSERT(entity != nullptr); - GB_ASSERT(entity->kind == Entity_Procedure); - if (!entity->Procedure.is_foreign) { - if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) { - GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false)); - } - } - - String link_name = cg_get_entity_name(m, entity); - - cgProcedure *p = nullptr; - { - StringHashKey key = string_hash_string(link_name); - cgValue *found = string_map_get(&m->members, key); - if (found) { - cg_add_entity(m, entity, *found); - p = string_map_must_get(&m->procedures, key); - if (!ignore_body && p->func != nullptr) { - return nullptr; - } - } - } - - if (p == nullptr) { - p = gb_alloc_item(permanent_allocator(), cgProcedure); - } - - p->module = m; - p->entity = entity; - p->name = link_name; - - DeclInfo *decl = entity->decl_info; - - ast_node(pl, ProcLit, decl->proc_lit); - Type *pt = base_type(entity->type); - GB_ASSERT(pt->kind == Type_Proc); - - p->type = entity->type; - p->type_expr = decl->type_expr; - p->body = pl->body; - p->inlining = pl->inlining; - p->is_foreign = entity->Procedure.is_foreign; - p->is_export = entity->Procedure.is_export; - p->is_entry_point = false; - - gbAllocator a = heap_allocator(); - p->children.allocator = a; - // p->defer_stmts.allocator = a; - // p->blocks.allocator = a; - // p->branch_blocks.allocator = a; - // p->context_stack.allocator = a; - // p->scope_stack.allocator = a; - // map_init(&p->tuple_fix_map, 0); - - TB_Linkage linkage = TB_LINKAGE_PRIVATE; - if (p->is_export) { - linkage = TB_LINKAGE_PUBLIC; - } else if (p->is_foreign || ignore_body) { - if (ignore_body) { - linkage = TB_LINKAGE_PUBLIC; - } - p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); - } - - if (p->symbol == nullptr) { - p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); - p->symbol = cast(TB_Symbol *)p->func; - } - - cgValue proc_value = cg_value(p->symbol, p->type); - cg_add_entity(m, entity, proc_value); - cg_add_member(m, p->name, proc_value); - cg_add_procedure_value(m, p); - - - return p; -} - -gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &link_name, Type *type) { - auto *prev_found = string_map_get(&m->members, link_name); - GB_ASSERT_MSG(prev_found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name)); - - cgProcedure *p = gb_alloc_item(permanent_allocator(), cgProcedure); - - p->module = m; - p->name = link_name; - - p->type = type; - p->type_expr = nullptr; - p->body = nullptr; - p->tags = 0; - p->inlining = ProcInlining_none; - p->is_foreign = false; - p->is_export = false; - p->is_entry_point = false; - - gbAllocator a = heap_allocator(); - p->children.allocator = a; - // p->defer_stmts.allocator = a; - // p->blocks.allocator = a; - // p->branch_blocks.allocator = a; - // p->context_stack.allocator = a; - // map_init(&p->tuple_fix_map, 0); - - - TB_Linkage linkage = TB_LINKAGE_PRIVATE; - - p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); - p->symbol = cast(TB_Symbol *)p->func; - - cgValue proc_value = cg_value(p->symbol, p->type); - cg_add_member(m, p->name, proc_value); - cg_add_procedure_value(m, p); - - return p; -} - -gb_internal void cg_procedure_begin(cgProcedure *p) { - if (p == nullptr || p->func == nullptr) { - return; - } -} - -gb_internal void cg_procedure_end(cgProcedure *p) { - if (p == nullptr || p->func == nullptr) { - return; - } - tb_inst_ret(p->func, 0, nullptr); - if (p->name == "main") { - TB_Arena *arena = tb_default_arena(); - defer (arena->free(arena)); - TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - defer (tb_funcopt_exit(opt)); - tb_funcopt_print(opt); - } - tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); -} - -gb_internal void cg_procedure_generate(cgProcedure *p) { - if (p->body == nullptr) { - return; - } - cg_procedure_begin(p); - defer (cg_procedure_end(p)); - - if (p->name != "bug.main" && - p->name != "main") { - return; - } - cg_build_stmt(p, p->body); -} - - #include "tilde_const.cpp" #include "tilde_expr.cpp" #include "tilde_proc.cpp" diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 6c17f8ba3..1f7300d73 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -113,7 +113,11 @@ enum cgDeferExitKind { cgDeferExit_Branch, }; - +struct cgContextData { + cgAddr ctx; + isize scope_index; + isize uses; +}; struct cgProcedure { u32 flags; @@ -144,6 +148,12 @@ struct cgProcedure { cgTargetList * target_list; Array branch_blocks; + + Scope *curr_scope; + i32 scope_index; + + Array scope_stack; + Array context_stack; }; @@ -214,4 +224,6 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); -gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); \ No newline at end of file +gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); + +gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); \ No newline at end of file diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 702cb42ad..22da43cbd 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,3 +1,89 @@ +gb_internal cgContextData *cg_push_context_onto_stack(cgProcedure *p, cgAddr ctx) { + ctx.kind = cgAddr_Context; + cgContextData *cd = array_add_and_get(&p->context_stack); + cd->ctx = ctx; + cd->scope_index = p->scope_index; + return cd; +} + +gb_internal cgAddr cg_find_or_generate_context_ptr(cgProcedure *p) { + if (p->context_stack.count > 0) { + return p->context_stack[p->context_stack.count-1].ctx; + } + + Type *pt = base_type(p->type); + GB_ASSERT(pt->kind == Type_Proc); + GB_ASSERT(pt->Proc.calling_convention != ProcCC_Odin); + + cgAddr c = cg_add_local(p, t_context, nullptr, true); + tb_node_append_attrib(c.addr.node, tb_function_attrib_variable(p->func, -1, "context", cg_debug_type(p->module, t_context))); + c.kind = cgAddr_Context; + // lb_emit_init_context(p, c); + cg_push_context_onto_stack(p, c); + // lb_add_debug_context_variable(p, c); + + return c; +} + +gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e) { + e = strip_entity_wrapping(e); + GB_ASSERT(e != nullptr); + + GB_ASSERT(e->token.string != "_"); + + if (e->kind == Entity_Procedure) { + return cg_find_procedure_value_from_entity(m, e); + } + + cgValue *found = nullptr; + rw_mutex_shared_lock(&m->values_mutex); + found = map_get(&m->values, e); + rw_mutex_shared_unlock(&m->values_mutex); + if (found) { + return *found; + } + + // GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); + return {}; +} + +gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *expr) { + GB_ASSERT(e != nullptr); + if (e->kind == Entity_Constant) { + Type *t = default_type(type_of_expr(expr)); + cgValue v = cg_const_value(p, t, e->Constant.value); + GB_PANIC("TODO(bill): cg_add_global_generated"); + // return cg_add_global_generated(p->module, t, v); + return {}; + } + + + cgValue v = {}; + + cgModule *m = p->module; + + rw_mutex_lock(&m->values_mutex); + cgValue *found = map_get(&m->values, e); + rw_mutex_unlock(&m->values_mutex); + if (found) { + v = *found; + } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { + GB_PANIC("TODO(bill): cg_get_using_variable"); + // NOTE(bill): Calculate the using variable every time + // v = cg_get_using_variable(p, e); + } else if (e->flags & EntityFlag_SoaPtrField) { + GB_PANIC("TODO(bill): cg_get_soa_variable_addr"); + // return cg_get_soa_variable_addr(p, e); + } + + + if (v.node == nullptr) { + return cg_addr(cg_find_value_from_entity(m, e)); + } + + return cg_addr(v); +} + gb_internal cgValue cg_typeid(cgModule *m, Type *t) { GB_ASSERT("TODO(bill): cg_typeid"); return {}; @@ -248,6 +334,65 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { } +gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr); gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr) { - return {}; + expr = unparen_expr(expr); + + // IMPORTANT NOTE(bill): + // Selector Call Expressions (foo->bar(...)) + // must only evaluate `foo` once as it gets transformed into + // `foo.bar(foo, ...)` + // And if `foo` is a procedure call or something more complex, storing the value + // once is a very good idea + // If a stored value is found, it must be removed from the cache + if (expr->state_flags & StateFlag_SelectorCallExpr) { + // lbAddr *pp = map_get(&p->selector_addr, expr); + // if (pp != nullptr) { + // lbAddr res = *pp; + // map_remove(&p->selector_addr, expr); + // return res; + // } + } + cgAddr addr = cg_build_addr_internal(p, expr); + if (expr->state_flags & StateFlag_SelectorCallExpr) { + // map_set(&p->selector_addr, expr, addr); + } + return addr; } + + +gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { + switch (expr->kind) { + case_ast_node(i, Implicit, expr); + cgAddr v = {}; + switch (i->kind) { + case Token_context: + v = cg_find_or_generate_context_ptr(p); + break; + } + + GB_ASSERT(v.addr.node != nullptr); + return v; + case_end; + + case_ast_node(i, Ident, expr); + if (is_blank_ident(expr)) { + cgAddr val = {}; + return val; + } + String name = i->token.string; + Entity *e = entity_of_node(expr); + return cg_build_addr_from_entity(p, e, expr); + case_end; + } + + TokenPos token_pos = ast_token(expr).pos; + GB_PANIC("Unexpected address expression\n" + "\tAst: %.*s @ " + "%s\n", + LIT(ast_strings[expr->kind]), + token_pos_to_string(token_pos)); + + + return {}; +} \ No newline at end of file diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index dbebae853..b60e797c3 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1,3 +1,293 @@ +gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Type *type) { + GB_ASSERT(type != nullptr); + type = base_type(type); + GB_ASSERT(type->kind == Type_Proc); + TypeProc *pt = &type->Proc; + + auto params = array_make(heap_allocator(), 0, pt->param_count); + if (pt->params) for (Entity *e : pt->params->Tuple.variables) { + TB_PrototypeParam param = {}; + + Type *t = core_type(e->type); + i64 sz = type_size_of(t); + switch (t->kind) { + case Type_Basic: + switch (t->Basic.kind) { + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + case Basic_i8: + case Basic_u8: + case Basic_i16: + case Basic_u16: + case Basic_i32: + case Basic_u32: + case Basic_i64: + case Basic_u64: + case Basic_i128: + case Basic_u128: + case Basic_rune: + case Basic_int: + case Basic_uint: + case Basic_uintptr: + param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + case Basic_f16: param.dt = TB_TYPE_I16; break; + case Basic_f32: param.dt = TB_TYPE_F32; break; + case Basic_f64: param.dt = TB_TYPE_F64; break; + + case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + case Basic_quaternion64: + case Basic_quaternion128: + case Basic_quaternion256: + param.dt = TB_TYPE_PTR; + break; + + + case Basic_rawptr: + param.dt = TB_TYPE_PTR; + break; + case Basic_string: // ^u8 + int + param.dt = TB_TYPE_PTR; + break; + case Basic_cstring: // ^u8 + param.dt = TB_TYPE_PTR; + break; + case Basic_any: // rawptr + ^Type_Info + param.dt = TB_TYPE_PTR; + break; + + case Basic_typeid: + param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + // Endian Specific Types + case Basic_i16le: + case Basic_u16le: + case Basic_i32le: + case Basic_u32le: + case Basic_i64le: + case Basic_u64le: + case Basic_i128le: + case Basic_u128le: + case Basic_i16be: + case Basic_u16be: + case Basic_i32be: + case Basic_u32be: + case Basic_i64be: + case Basic_u64be: + case Basic_i128be: + case Basic_u128be: + param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + case Basic_f16le: param.dt = TB_TYPE_I16; break; + case Basic_f32le: param.dt = TB_TYPE_F32; break; + case Basic_f64le: param.dt = TB_TYPE_F64; break; + + case Basic_f16be: param.dt = TB_TYPE_I16; break; + case Basic_f32be: param.dt = TB_TYPE_F32; break; + case Basic_f64be: param.dt = TB_TYPE_F64; break; + } + + case Type_Pointer: + case Type_MultiPointer: + case Type_Proc: + param.dt = TB_TYPE_PTR; + break; + + default: + switch (sz) { + case 1: param.dt = TB_TYPE_I8; break; + case 2: param.dt = TB_TYPE_I16; break; + case 4: param.dt = TB_TYPE_I32; break; + case 8: param.dt = TB_TYPE_I64; break; + default: + param.dt = TB_TYPE_PTR; + break; + } + } + + if (param.dt.width != 0) { + if (is_blank_ident(e->token)) { + param.name = alloc_cstring(temporary_allocator(), e->token.string); + } + array_add(¶ms, param); + } + } + + auto results = array_make(heap_allocator(), 0, pt->result_count); + // if (pt->results) for (Entity *e : pt->params->Tuple.variables) { + // // TODO(bill): + // } + + + return tb_prototype_create(m->mod, TB_CDECL, params.count, params.data, results.count, results.data, pt->c_vararg); +} + +gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body=false) { + GB_ASSERT(entity != nullptr); + GB_ASSERT(entity->kind == Entity_Procedure); + if (!entity->Procedure.is_foreign) { + if ((entity->flags & EntityFlag_ProcBodyChecked) == 0) { + GB_PANIC("%.*s :: %s (was parapoly: %d %d)", LIT(entity->token.string), type_to_string(entity->type), is_type_polymorphic(entity->type, true), is_type_polymorphic(entity->type, false)); + } + } + + String link_name = cg_get_entity_name(m, entity); + + cgProcedure *p = nullptr; + { + StringHashKey key = string_hash_string(link_name); + cgValue *found = string_map_get(&m->members, key); + if (found) { + cg_add_entity(m, entity, *found); + p = string_map_must_get(&m->procedures, key); + if (!ignore_body && p->func != nullptr) { + return nullptr; + } + } + } + + if (p == nullptr) { + p = gb_alloc_item(permanent_allocator(), cgProcedure); + } + + p->module = m; + p->entity = entity; + p->name = link_name; + + DeclInfo *decl = entity->decl_info; + + ast_node(pl, ProcLit, decl->proc_lit); + Type *pt = base_type(entity->type); + GB_ASSERT(pt->kind == Type_Proc); + + p->type = entity->type; + p->type_expr = decl->type_expr; + p->body = pl->body; + p->inlining = pl->inlining; + p->is_foreign = entity->Procedure.is_foreign; + p->is_export = entity->Procedure.is_export; + p->is_entry_point = false; + + gbAllocator a = heap_allocator(); + p->children.allocator = a; + // p->defer_stmts.allocator = a; + // p->blocks.allocator = a; + // p->branch_blocks.allocator = a; + p->context_stack.allocator = a; + p->scope_stack.allocator = a; + // map_init(&p->tuple_fix_map, 0); + + TB_Linkage linkage = TB_LINKAGE_PRIVATE; + if (p->is_export) { + linkage = TB_LINKAGE_PUBLIC; + } else if (p->is_foreign || ignore_body) { + if (ignore_body) { + linkage = TB_LINKAGE_PUBLIC; + } + p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); + } + + if (p->symbol == nullptr) { + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); + tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->symbol = cast(TB_Symbol *)p->func; + } + + cgValue proc_value = cg_value(p->symbol, p->type); + cg_add_entity(m, entity, proc_value); + cg_add_member(m, p->name, proc_value); + cg_add_procedure_value(m, p); + + + return p; +} + +gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &link_name, Type *type) { + auto *prev_found = string_map_get(&m->members, link_name); + GB_ASSERT_MSG(prev_found == nullptr, "failed to create dummy procedure for: %.*s", LIT(link_name)); + + cgProcedure *p = gb_alloc_item(permanent_allocator(), cgProcedure); + + p->module = m; + p->name = link_name; + + p->type = type; + p->type_expr = nullptr; + p->body = nullptr; + p->tags = 0; + p->inlining = ProcInlining_none; + p->is_foreign = false; + p->is_export = false; + p->is_entry_point = false; + + gbAllocator a = heap_allocator(); + p->children.allocator = a; + // p->defer_stmts.allocator = a; + // p->blocks.allocator = a; + // p->branch_blocks.allocator = a; + p->scope_stack.allocator = a; + p->context_stack.allocator = a; + // map_init(&p->tuple_fix_map, 0); + + + TB_Linkage linkage = TB_LINKAGE_PRIVATE; + + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); + tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->symbol = cast(TB_Symbol *)p->func; + + cgValue proc_value = cg_value(p->symbol, p->type); + cg_add_member(m, p->name, proc_value); + cg_add_procedure_value(m, p); + + return p; +} + +gb_internal void cg_procedure_begin(cgProcedure *p) { + if (p == nullptr || p->func == nullptr) { + return; + } +} + +gb_internal void cg_procedure_end(cgProcedure *p) { + if (p == nullptr || p->func == nullptr) { + return; + } + tb_inst_ret(p->func, 0, nullptr); + if (p->name == "main") { + TB_Arena *arena = tb_default_arena(); + defer (arena->free(arena)); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + tb_funcopt_print(opt); + } + tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); +} + +gb_internal void cg_procedure_generate(cgProcedure *p) { + if (p->body == nullptr) { + return; + } + cg_procedure_begin(p); + defer (cg_procedure_end(p)); + + if (p->name != "bug.main" && + p->name != "main") { + return; + } + cg_build_stmt(p, p->body); +} + + + gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) { GB_ASSERT(is_type_proc(e->type)); e = strip_entity_wrapping(e); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 07bfc0555..7c3dfcef8 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -549,7 +549,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_end; case_ast_node(as, AssignStmt, node); - // cg_build_assign_stmt(p, as); + cg_build_assign_stmt(p, as); case_end; case_ast_node(rs, ReturnStmt, node); -- cgit v1.2.3 From ee8372145d62bf90c0fe43c78b96a02b6247321e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 15 Jul 2023 14:26:47 +0100 Subject: Begin working on proper expressions --- src/tilde/tb.lib | Bin 4120106 -> 4112646 bytes src/tilde_backend.cpp | 178 ++++++++++++++++++++++++--------- src/tilde_backend.hpp | 11 ++- src/tilde_const.cpp | 97 ++++++++++++++---- src/tilde_expr.cpp | 265 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/tilde_proc.cpp | 84 +++++++++++++++- src/tilde_stmt.cpp | 75 ++++++++++++-- 7 files changed, 630 insertions(+), 80 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index a6ac5cbff..bad51e7e6 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 97f92e3db..dfe39c385 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -33,7 +33,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_typeid: return TB_TYPE_INTN(cast(u16)(8*sz)); - case Basic_f16: return TB_TYPE_I16; + case Basic_f16: return TB_TYPE_F16; case Basic_f32: return TB_TYPE_F32; case Basic_f64: return TB_TYPE_F64; @@ -60,11 +60,11 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_u128be: return TB_TYPE_INTN(cast(u16)(8*sz)); - case Basic_f16le: return TB_TYPE_I16; + case Basic_f16le: return TB_TYPE_F16; case Basic_f32le: return TB_TYPE_F32; case Basic_f64le: return TB_TYPE_F64; - case Basic_f16be: return TB_TYPE_I16; + case Basic_f16be: return TB_TYPE_F16; case Basic_f32be: return TB_TYPE_F32; case Basic_f64be: return TB_TYPE_F64; } @@ -173,9 +173,128 @@ gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_ return -1; } -gb_internal void cg_create_global_variables(cgModule *m) { +struct cgGlobalVariable { + cgValue var; + cgValue init; + DeclInfo *decl; + bool is_initialized; +}; + +// Returns already_has_entry_point +gb_internal bool cg_global_variables_create(cgModule *m) { + isize global_variable_max_count = 0; + bool already_has_entry_point = false; + + for (Entity *e : m->info->entities) { + String name = e->token.string; + + if (e->kind == Entity_Variable) { + global_variable_max_count++; + } else if (e->kind == Entity_Procedure) { + if ((e->scope->flags&ScopeFlag_Init) && name == "main") { + GB_ASSERT(e == m->info->entry_point); + } + if (build_context.command_kind == Command_test && + (e->Procedure.is_export || e->Procedure.link_name.len > 0)) { + String link_name = e->Procedure.link_name; + if (e->pkg->kind == Package_Runtime) { + if (link_name == "main" || + link_name == "DllMain" || + link_name == "WinMain" || + link_name == "wWinMain" || + link_name == "mainCRTStartup" || + link_name == "_start") { + already_has_entry_point = true; + } + } + } + } + } + auto global_variables = array_make(permanent_allocator(), 0, global_variable_max_count); + + auto *min_dep_set = &m->info->minimum_dependency_set; + + for (DeclInfo *d : m->info->variable_init_order) { + Entity *e = d->entity; + + if ((e->scope->flags & ScopeFlag_File) == 0) { + continue; + } + + if (!ptr_set_exists(min_dep_set, e)) { + continue; + } + + DeclInfo *decl = decl_info_of_entity(e); + if (decl == nullptr) { + continue; + } + GB_ASSERT(e->kind == Entity_Variable); + + bool is_foreign = e->Variable.is_foreign; + bool is_export = e->Variable.is_export; + + String name = cg_get_entity_name(m, e); + + TB_Linkage linkage = TB_LINKAGE_PRIVATE; + + if (is_foreign) { + linkage = TB_LINKAGE_PUBLIC; + // lb_add_foreign_library_path(m, e->Variable.foreign_library); + // lb_set_wasm_import_attributes(g.value, e, name); + } else if (is_export) { + linkage = TB_LINKAGE_PUBLIC; + } + // lb_set_linkage_from_entity_flags(m, g.value, e->flags); + + TB_DebugType *debug_type = cg_debug_type(m, e->type); + TB_Global *global = tb_global_create(m->mod, name.len, cast(char const *)name.text, debug_type, linkage); + cgValue g = cg_value(global, alloc_type_pointer(e->type)); + + TB_ModuleSection *section = tb_module_get_data(m->mod); + + if (e->Variable.thread_local_model != "") { + section = tb_module_get_tls(m->mod); + } + if (e->Variable.link_section.len > 0) { + // TODO(bill): custom module sections + // LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section)); + } + + size_t max_objects = 0; + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_objects); + + cgGlobalVariable var = {}; + var.var = g; + var.decl = decl; + + if (decl->init_expr != nullptr) { + // TypeAndValue tav = type_and_value_of_expr(decl->init_expr); + // if (!is_type_any(e->type) && !is_type_union(e->type)) { + // if (tav.mode != Addressing_Invalid) { + // if (tav.value.kind != ExactValue_Invalid) { + // ExactValue v = tav.value; + // lbValue init = lb_const_value(m, tav.type, v); + // LLVMSetInitializer(g.value, init.value); + // var.is_initialized = true; + // } + // } + // } + // if (!var.is_initialized && is_type_untyped_nil(tav.type)) { + // var.is_initialized = true; + // } + } + + array_add(&global_variables, var); + + cg_add_entity(m, e, g); + cg_add_member(m, name, g); + } + + + if (build_context.no_rtti) { - return; + return already_has_entry_point; } CheckerInfo *info = m->info; @@ -256,9 +375,11 @@ gb_internal void cg_create_global_variables(cgModule *m) { } } } + + return already_has_entry_point; } -cgModule *cg_module_create(Checker *c) { +gb_internal cgModule *cg_module_create(Checker *c) { cgModule *m = gb_alloc_item(permanent_allocator(), cgModule); m->checker = c; @@ -286,7 +407,7 @@ cgModule *cg_module_create(Checker *c) { return m; } -void cg_module_destroy(cgModule *m) { +gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); array_free(&m->procedures_to_generate); map_destroy(&m->file_id_map); @@ -391,7 +512,7 @@ gb_internal String cg_mangle_name(cgModule *m, Entity *e) { return mangled_name; } -String cg_get_entity_name(cgModule *m, Entity *e) { +gb_internal String cg_get_entity_name(cgModule *m, Entity *e) { if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) { return e->TypeName.ir_mangled_name; } @@ -438,14 +559,6 @@ String cg_get_entity_name(cgModule *m, Entity *e) { return name; } - -struct cgGlobalVariable { - cgValue var; - cgValue init; - DeclInfo *decl; - bool is_initialized; -}; - #include "tilde_const.cpp" #include "tilde_expr.cpp" #include "tilde_proc.cpp" @@ -463,37 +576,8 @@ gb_internal bool cg_generate_code(Checker *c) { TIME_SECTION("Tilde Global Variables"); - cg_create_global_variables(m); - - // isize global_variable_max_count = 0; - // bool already_has_entry_point = false; - - // for (Entity *e : info->entities) { - // String name = e->token.string; - - // if (e->kind == Entity_Variable) { - // global_variable_max_count++; - // } else if (e->kind == Entity_Procedure) { - // if ((e->scope->flags&ScopeFlag_Init) && name == "main") { - // GB_ASSERT(e == info->entry_point); - // } - // if (build_context.command_kind == Command_test && - // (e->Procedure.is_export || e->Procedure.link_name.len > 0)) { - // String link_name = e->Procedure.link_name; - // if (e->pkg->kind == Package_Runtime) { - // if (link_name == "main" || - // link_name == "DllMain" || - // link_name == "WinMain" || - // link_name == "wWinMain" || - // link_name == "mainCRTStartup" || - // link_name == "_start") { - // already_has_entry_point = true; - // } - // } - // } - // } - // } - // auto global_variables = array_make(permanent_allocator(), 0, global_variable_max_count); + bool already_has_entry_point = cg_global_variables_create(m); + gb_unused(already_has_entry_point); if (true) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 1f7300d73..228afb6af 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -7,6 +7,7 @@ #include "tilde/tb.h" +#define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } #define TB_TYPE_INT TB_TYPE_INTN(cast(u16)build_context.int_size) #define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)build_context.ptr_size) @@ -127,6 +128,7 @@ struct cgProcedure { Array children; TB_Function *func; + TB_FunctionPrototype *proto; TB_Symbol *symbol; Entity * entity; @@ -151,9 +153,12 @@ struct cgProcedure { Scope *curr_scope; i32 scope_index; + bool in_multi_assignment; Array scope_stack; Array context_stack; + + PtrMap variable_map; }; @@ -226,4 +231,8 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); -gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); \ No newline at end of file +gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); + +gb_internal String cg_get_entity_name(cgModule *m, Entity *e); + +gb_internal cgValue cg_typeid(cgModule *m, Type *t); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 97fee838e..35c87641f 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -1,19 +1,31 @@ -gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { +gb_internal bool cg_is_expr_constant_zero(Ast *expr) { + GB_ASSERT(expr != nullptr); + auto v = exact_value_to_integer(expr->tav.value); + if (v.kind == ExactValue_Integer) { + return big_int_cmp_zero(&v.value_integer) == 0; + } + return false; +} + +gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { Type *original_type = type; type = core_type(type); i64 size = type_size_of(type); i64 align = type_align_of(type); TB_DataType dt = cg_data_type(type); if (TB_IS_VOID_TYPE(dt)) { - TB_Module *m = p->module->mod; char name[32] = {}; - gb_snprintf(name, 31, "cnil$%u", 1+p->module->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m, tb_module_get_rdata(m), global, size, align, 0); + gb_snprintf(name, 31, "cnil$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, align, 0); TB_Symbol *symbol = cast(TB_Symbol *)global; - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); + if (p) { + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); + } else { + GB_PANIC("TODO(bill): cg_const_nil"); + } } if (is_type_internally_pointer_like(type)) { @@ -34,24 +46,71 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return {}; } -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { +gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { + return cg_const_nil(p->module, p, type); +} + +gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local = true) { TB_Node *node = nullptr; - if (value.kind == ExactValue_Invalid) { + bool is_local = allow_local && p != nullptr; + gb_unused(is_local); + + TB_DataType dt = cg_data_type(type); + + switch (value.kind) { + case ExactValue_Invalid: return cg_const_nil(p, type); + + case ExactValue_Typeid: + return cg_typeid(m, value.value_typeid); + + case ExactValue_Procedure: + { + Ast *expr = unparen_expr(value.value_procedure); + Entity *e = entity_of_node(expr); + if (e != nullptr) { + cgValue found = cg_find_procedure_value_from_entity(m, e); + GB_ASSERT(are_types_identical(type, found.type)); + return found; + } + GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); + } + break; } - if (value.kind == ExactValue_Procedure) { - Ast *expr = unparen_expr(value.value_procedure); - Entity *e = entity_of_node(expr); - if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(m, e); - GB_ASSERT(are_types_identical(type, found.type)); - return found; + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + + switch (value.kind) { + case ExactValue_Bool: + return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); + + case ExactValue_Integer: + GB_ASSERT(dt.raw != TB_TYPE_I128.raw); + if (is_type_unsigned(type)) { + u64 i = exact_value_to_u64(value); + return cg_value(tb_inst_uint(p->func, dt, i), type); + } else { + i64 i = exact_value_to_i64(value); + return cg_value(tb_inst_sint(p->func, dt, i), type); } + break; + case ExactValue_Float: + GB_ASSERT(dt.raw != TB_TYPE_F16.raw); + GB_ASSERT(!is_type_different_to_arch_endianness(type)); + { + f64 f = exact_value_to_f64(value); + if (type_size_of(type) == 8) { + return cg_value(tb_inst_float64(p->func, f), type); + } else { + return cg_value(tb_inst_float32(p->func, cast(f32)f), type); + } + } + break; } + GB_ASSERT(node != nullptr); return cg_value(node, type); } @@ -59,4 +118,8 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { GB_ASSERT(p != nullptr); return cg_const_value(p->module, p, type, value); -} \ No newline at end of file +} + +gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { + return cg_const_value(p, type, exact_value_i64(i)); +} diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 22da43cbd..fc22e12d9 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,3 +1,11 @@ +gb_internal cgValue cg_flatten_value(cgProcedure *p, cgValue value) { + if (value.kind == cgValue_Symbol) { + GB_ASSERT(is_type_internally_pointer_like(value.type)); + value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); + } + return value; +} + gb_internal cgContextData *cg_push_context_onto_stack(cgProcedure *p, cgAddr ctx) { ctx.kind = cgAddr_Context; cgContextData *cd = array_add_and_get(&p->context_stack); @@ -43,7 +51,7 @@ gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e) { return *found; } - // GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); + GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); return {}; } @@ -57,6 +65,10 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp return {}; } + cgAddr *local_found = map_get(&p->variable_map, e); + if (local_found) { + return *local_found; + } cgValue v = {}; @@ -78,7 +90,9 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp if (v.node == nullptr) { - return cg_addr(cg_find_value_from_entity(m, e)); + cgValue v = cg_find_value_from_entity(m, e); + v = cg_flatten_value(p, v); + return cg_addr(v); } return cg_addr(v); @@ -90,6 +104,17 @@ gb_internal cgValue cg_typeid(cgModule *m, Type *t) { } +gb_internal cgValue cg_correct_endianness(cgProcedure *p, cgValue value) { + Type *src = core_type(value.type); + GB_ASSERT(is_type_integer(src) || is_type_float(src)); + if (is_type_different_to_arch_endianness(src)) { + GB_PANIC("TODO(bill): cg_correct_endianness"); + // Type *platform_src_type = integer_endian_type_to_platform_type(src); + // value = cg_emit_byte_swap(p, value, platform_src_type); + } + return value; +} + gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { // TODO(bill): cg_emit_conv return value; @@ -98,10 +123,7 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) { GB_ASSERT(type_size_of(value.type) == type_size_of(type)); - if (value.kind == cgValue_Symbol) { - GB_ASSERT(is_type_pointer(value.type)); - value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), type); - } + value = cg_flatten_value(p, value); i64 src_align = type_align_of(value.type); i64 dst_align = type_align_of(type); @@ -133,6 +155,217 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) } +gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { + ast_node(se, SliceExpr, expr); + + cgValue low = cg_const_int(p, t_int, 0); + cgValue high = {}; + + if (se->low != nullptr) { + low = cg_correct_endianness(p, cg_build_expr(p, se->low)); + } + if (se->high != nullptr) { + high = cg_correct_endianness(p, cg_build_expr(p, se->high)); + } + + bool no_indices = se->low == nullptr && se->high == nullptr; + gb_unused(no_indices); + + cgAddr addr = cg_build_addr(p, se->expr); + cgValue base = cg_addr_load(p, addr); + Type *type = base_type(base.type); + + if (is_type_pointer(type)) { + type = base_type(type_deref(type)); + addr = cg_addr(base); + base = cg_addr_load(p, addr); + } + + switch (type->kind) { + case Type_Slice: { + // Type *slice_type = type; + // cgValue len = cg_slice_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // cgValue elem = cg_emit_ptr_offset(p, cg_slice_elem(p, base), low); + // cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + + // cgAddr slice = cg_add_local_generated(p, slice_type, false); + // cg_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_Slice"); + break; + } + + case Type_RelativeSlice: + GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the cg_addr_load"); + break; + + case Type_DynamicArray: { + // Type *elem_type = type->DynamicArray.elem; + // Type *slice_type = alloc_type_slice(elem_type); + + // lbValue len = lb_dynamic_array_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr slice = lb_add_local_generated(p, slice_type, false); + // lb_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_DynamicArray"); + break; + } + + case Type_MultiPointer: { + // lbAddr res = lb_add_local_generated(p, type_of_expr(expr), false); + // if (se->high == nullptr) { + // lbValue offset = base; + // LLVMValueRef indices[1] = {low.value}; + // offset.value = LLVMBuildGEP2(p->builder, lb_type(p->module, offset.type->MultiPointer.elem), offset.value, indices, 1, ""); + // lb_addr_store(p, res, offset); + // } else { + // low = lb_emit_conv(p, low, t_int); + // high = lb_emit_conv(p, high, t_int); + + // lb_emit_multi_pointer_slice_bounds_check(p, se->open, low, high); + + // LLVMValueRef indices[1] = {low.value}; + // LLVMValueRef ptr = LLVMBuildGEP2(p->builder, lb_type(p->module, base.type->MultiPointer.elem), base.value, indices, 1, ""); + // LLVMValueRef len = LLVMBuildSub(p->builder, high.value, low.value, ""); + + // LLVMValueRef gep0 = lb_emit_struct_ep(p, res.addr, 0).value; + // LLVMValueRef gep1 = lb_emit_struct_ep(p, res.addr, 1).value; + // LLVMBuildStore(p->builder, ptr, gep0); + // LLVMBuildStore(p->builder, len, gep1); + // } + // return res; + GB_PANIC("cg_build_addr_slice_expr Type_MultiPointer"); + break; + } + + case Type_Array: { + // Type *slice_type = alloc_type_slice(type->Array.elem); + // lbValue len = lb_const_int(p->module, t_int, type->Array.count); + + // if (high.value == nullptr) high = len; + + // bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant; + // bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant; + + // if (!low_const || !high_const) { + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + // } + // lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr slice = lb_add_local_generated(p, slice_type, false); + // lb_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_Array"); + break; + } + + case Type_Basic: { + // GB_ASSERT(type == t_string); + // lbValue len = lb_string_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr str = lb_add_local_generated(p, t_string, false); + // lb_fill_string(p, str, elem, new_len); + // return str; + GB_PANIC("cg_build_addr_slice_expr Type_Basic"); + break; + } + + + case Type_Struct: + // if (is_type_soa_struct(type)) { + // lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr)); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + // #if 1 + + // lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true); + // if (type->Struct.soa_kind == StructSoa_Fixed) { + // i32 field_count = cast(i32)type->Struct.fields.count; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i); + // field_src = lb_emit_array_ep(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } else if (type->Struct.soa_kind == StructSoa_Slice) { + // if (no_indices) { + // lb_addr_store(p, dst, base); + // } else { + // i32 field_count = cast(i32)type->Struct.fields.count - 1; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ev(p, base, i); + // field_src = lb_emit_ptr_offset(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } + // } else if (type->Struct.soa_kind == StructSoa_Dynamic) { + // i32 field_count = cast(i32)type->Struct.fields.count - 3; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ev(p, base, i); + // field_src = lb_emit_ptr_offset(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } + + // return dst; + // #endif + // } + GB_PANIC("cg_build_addr_slice_expr Type_Struct"); + break; + + } + + GB_PANIC("Unknown slicable type"); + return {}; +} + + + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { @@ -252,6 +485,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_value(cast(TB_Node *)nullptr, e->type); } GB_ASSERT(e->kind != Entity_ProcGroup); + + cgAddr *addr = map_get(&p->variable_map, e); + if (addr) { + return cg_addr_load(p, *addr); + } // return cg_find_ident(p, m, e, expr); GB_PANIC("TODO: cg_find_ident"); return {}; @@ -327,6 +565,17 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { cgValue value = cg_build_expr(p, ac->expr); return cg_emit_conv(p, value, type); case_end; + + case_ast_node(se, SliceExpr, expr); + if (is_type_slice(type_of_expr(se->expr))) { + // NOTE(bill): Quick optimization + if (se->high == nullptr && + (se->low == nullptr || cg_is_expr_constant_zero(se->low))) { + return cg_build_expr(p, se->expr); + } + } + return cg_addr_load(p, cg_build_addr(p, expr)); + case_end; } GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; @@ -384,6 +633,10 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { Entity *e = entity_of_node(expr); return cg_build_addr_from_entity(p, e, expr); case_end; + + case_ast_node(se, SliceExpr, expr); + return cg_build_addr_slice_expr(p, expr); + case_end; } TokenPos token_pos = ast_token(expr).pos; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index b60e797c3..99b70a6a8 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -113,7 +113,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty } } - if (param.dt.width != 0) { + if (param.dt.raw != 0) { if (is_blank_ident(e->token)) { param.name = alloc_cstring(temporary_allocator(), e->token.string); } @@ -183,6 +183,7 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i // p->branch_blocks.allocator = a; p->context_stack.allocator = a; p->scope_stack.allocator = a; + map_init(&p->variable_map); // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; @@ -196,8 +197,10 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } if (p->symbol == nullptr) { + TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->proto = cg_procedure_type_as_prototype(m, p->type); + tb_function_set_prototype(p->func, p->proto, arena); p->symbol = cast(TB_Symbol *)p->func; } @@ -235,13 +238,16 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li // p->branch_blocks.allocator = a; p->scope_stack.allocator = a; p->context_stack.allocator = a; + map_init(&p->variable_map); // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; + TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->proto = cg_procedure_type_as_prototype(m, p->type); + tb_function_set_prototype(p->func, p->proto, arena); p->symbol = cast(TB_Symbol *)p->func; cgValue proc_value = cg_value(p->symbol, p->type); @@ -255,6 +261,78 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } + + if (p->body == nullptr) { + return; + } + + GB_ASSERT(p->type->kind == Type_Proc); + TypeProc *pt = &p->type->Proc; + if (pt->params) { + int param_index = 0; + for (Entity *e : pt->params->Tuple.variables) { + if (e->kind != Entity_Variable) { + continue; + } + + if (param_index >= p->proto->param_count) { + break; + } + + TB_Node *ptr = tb_inst_param_addr(p->func, param_index); + cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); + + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + + } + cgAddr addr = cg_addr(local); + if (e) { + map_set(&p->variable_map, e, addr); + } + + // if (arg_type->kind == lbArg_Ignore) { + // continue; + // } else if (arg_type->kind == lbArg_Direct) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // LLVMTypeRef param_type = lb_type(p->module, e->type); + // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); + // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); + + // lbValue param = {}; + // param.value = value; + // param.type = e->type; + + // map_set(&p->direct_parameters, e, param); + + // lbValue ptr = lb_address_from_load_or_generate_local(p, param); + // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); + // lb_add_entity(p->module, e, ptr); + + // lbBlock *block = p->decl_block; + // if (original_value != value) { + // block = p->curr_block; + // } + // LLVMValueRef debug_storage_value = value; + // if (original_value != value && LLVMIsALoadInst(value)) { + // debug_storage_value = LLVMGetOperand(value, 0); + // } + // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); + // } + // } else if (arg_type->kind == lbArg_Indirect) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // lbValue ptr = {}; + // ptr.value = LLVMGetParam(p->value, param_offset+param_index); + // ptr.type = alloc_type_pointer(e->type); + // lb_add_entity(p->module, e, ptr); + // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); + // } + // } + } + } } gb_internal void cg_procedure_end(cgProcedure *p) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 7c3dfcef8..2952539ca 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -131,6 +131,9 @@ gb_internal cgValue cg_address_from_load(cgProcedure *p, cgValue value) { GB_PANIC("Symbol is an invalid use case for cg_address_from_load"); return {}; } + GB_PANIC("Invalid cgValue for cg_address_from_load"); + return {}; + } gb_internal bool cg_addr_is_empty(cgAddr const &addr) { @@ -174,7 +177,14 @@ gb_internal Type *cg_addr_type(cgAddr const &addr) { } gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr) { - GB_PANIC("TODO(bill): cg_addr_load"); + if (addr.addr.node == nullptr) { + return {}; + } + switch (addr.kind) { + case cgAddr_Default: + return cg_emit_load(p, addr.addr); + } + GB_PANIC("TODO(bill): cg_addr_load %p", addr.addr.node); return {}; } @@ -285,19 +295,23 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only - // String name = e->token.string; - // TB_DebugType *debug_type = cg_debug_type(p->module, type); - // tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type); + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, type); + tb_node_append_attrib(local, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); } if (zero_init) { bool is_volatile = false; - TB_Node *zero = tb_inst_uint(p->func, TB_TYPE_I8, 0); + TB_Node *zero = tb_inst_uint(p->func, TB_TYPE_I8, 0); TB_Node *count = tb_inst_uint(p->func, TB_TYPE_I32, cast(u64)size); tb_inst_memset(p->func, local, zero, count, alignment, is_volatile); } - return cg_addr(cg_value(local, alloc_type_pointer(type))); + cgAddr addr = cg_addr(cg_value(local, alloc_type_pointer(type))); + if (e) { + map_set(&p->variable_map, e, addr); + } + return addr; } @@ -313,10 +327,59 @@ gb_internal void cg_emit_defer_stmts(cgProcedure *p, cgDeferExitKind kind, TB_No // TODO(bill): cg_emit_defer_stmts } + +gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value) { + isize init_count = dst_values->count; + Type *t = src_value.type; + if (t && t->kind == Type_Tuple) { + GB_PANIC("TODO(bill): tuple assignments"); + // cgTupleFix *tf = map_get(&p->tuple_fix_map, src_value.value); + // if (tf) { + // for (cgValue const &value : tf->values) { + // array_add(dst_values, value); + // } + // } else { + // for_array(i, t->Tuple.variables) { + // cgValue v = cg_emit_tuple_ev(p, src_value, cast(i32)i); + // array_add(dst_values, v); + // } + // } + } else { + array_add(dst_values, src_value); + } + return dst_values->count - init_count; +} gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, Slice const &values) { if (values.count == 0) { return; } + + auto inits = array_make(permanent_allocator(), 0, lvals.count); + + for (Ast *rhs : values) { + cgValue init = cg_build_expr(p, rhs); + cg_append_tuple_values(p, &inits, init); + } + + bool prev_in_assignment = p->in_multi_assignment; + + isize lval_count = 0; + for (cgAddr const &lval : lvals) { + if (!cg_addr_is_empty(lval)) { + // check if it is not a blank identifier + lval_count += 1; + } + } + p->in_multi_assignment = lval_count > 1; + + GB_ASSERT(lvals.count == inits.count); + for_array(i, inits) { + cgAddr lval = lvals[i]; + cgValue init = inits[i]; + cg_addr_store(p, lval, init); + } + + p->in_multi_assignment = prev_in_assignment; } gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { -- cgit v1.2.3 From d2d243cca8954e686a82f15a37a149c7938362d2 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 16 Jul 2023 23:41:51 +0100 Subject: Mock out `cg_emit_conv` --- src/tilde_backend.hpp | 4 +- src/tilde_expr.cpp | 444 ++++++++++++++++++++++++++++++++++++++++++++++---- src/tilde_proc.cpp | 149 ++++++++++++++++- src/tilde_stmt.cpp | 4 + src/types.cpp | 1 + 5 files changed, 562 insertions(+), 40 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 228afb6af..ec051b105 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -9,8 +9,8 @@ #define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } -#define TB_TYPE_INT TB_TYPE_INTN(cast(u16)build_context.int_size) -#define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)build_context.ptr_size) +#define TB_TYPE_INT TB_TYPE_INTN(cast(u16)(8*build_context.int_size)) +#define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)(8*build_context.ptr_size)) #if defined(GB_SYSTEM_WINDOWS) #pragma warning(pop) diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index fc22e12d9..39fcdd591 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -115,16 +115,19 @@ gb_internal cgValue cg_correct_endianness(cgProcedure *p, cgValue value) { return value; } -gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { - // TODO(bill): cg_emit_conv - return value; -} - gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) { GB_ASSERT(type_size_of(value.type) == type_size_of(type)); value = cg_flatten_value(p, value); + if (are_types_identical(value.type, type)) { + return value; + } + if (are_types_identical(core_type(value.type), core_type(type))) { + value.type = type; + return value; + } + i64 src_align = type_align_of(value.type); i64 dst_align = type_align_of(type); @@ -153,6 +156,380 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) return value; } +gb_internal cgValue cg_emit_byte_swap(cgProcedure *p, cgValue value, Type *end_type) { + GB_ASSERT(type_size_of(value.type) == type_size_of(end_type)); + + if (type_size_of(value.type) < 2) { + return value; + } + + if (is_type_float(value.type)) { + i64 sz = type_size_of(value.type); + Type *integer_type = nullptr; + switch (sz) { + case 2: integer_type = t_u16; break; + case 4: integer_type = t_u32; break; + case 8: integer_type = t_u64; break; + } + GB_ASSERT(integer_type != nullptr); + value = cg_emit_transmute(p, value, integer_type); + } + + GB_ASSERT(value.kind == cgValue_Value); + + value.node = tb_inst_bswap(p->func, value.node); + return cg_emit_transmute(p, value, end_type); +} + +gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { + t = reduce_tuple_to_single_type(t); + + value = cg_flatten_value(p, value); + + Type *src_type = value.type; + if (are_types_identical(t, src_type)) { + return value; + } + + Type *src = core_type(src_type); + Type *dst = core_type(t); + GB_ASSERT(src != nullptr); + GB_ASSERT(dst != nullptr); + + if (are_types_identical(src, dst)) { + return cg_emit_transmute(p, value, t); + } + + TB_DataType st = cg_data_type(src); + TB_DataType dt = cg_data_type(t); + + if (is_type_integer(src) && is_type_integer(dst)) { + GB_ASSERT(src->kind == Type_Basic && + dst->kind == Type_Basic); + GB_ASSERT(value.kind == cgValue_Value); + + i64 sz = type_size_of(default_type(src)); + i64 dz = type_size_of(default_type(dst)); + + if (sz == dz) { + if (dz > 1 && !types_have_same_internal_endian(src, dst)) { + return cg_emit_byte_swap(p, value, t); + } + value.type = t; + return value; + } + + if (sz > 1 && is_type_different_to_arch_endianness(src)) { + Type *platform_src_type = integer_endian_type_to_platform_type(src); + value = cg_emit_byte_swap(p, value, platform_src_type); + } + + TB_Node* (*op)(TB_Function* f, TB_Node* src, TB_DataType dt) = tb_inst_trunc; + + if (dz < sz) { + op = tb_inst_trunc; + } else if (dz == sz) { + op = tb_inst_bitcast; + } else if (dz > sz) { + op = is_type_unsigned(src) ? tb_inst_zxt : tb_inst_sxt; // zero extent + } + + if (dz > 1 && is_type_different_to_arch_endianness(dst)) { + Type *platform_dst_type = integer_endian_type_to_platform_type(dst); + + cgValue res = cg_value(op(p->func, value.node, cg_data_type(platform_dst_type)), platform_dst_type); + return cg_emit_byte_swap(p, res, t); + } else { + return cg_value(op(p->func, value.node, dt), t); + } + } + + // boolean -> boolean/integer + if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) { + TB_Node *v = tb_inst_cmp_ne(p->func, value.node, tb_inst_uint(p->func, st, 0)); + return cg_value(tb_inst_zxt(p->func, v, dt), t); + } + + // integer -> boolean + if (is_type_integer(src) && is_type_boolean(dst)) { + TB_Node *v = tb_inst_cmp_ne(p->func, value.node, tb_inst_uint(p->func, st, 0)); + return cg_value(tb_inst_zxt(p->func, v, dt), t); + } + + if (is_type_cstring(src) && is_type_u8_ptr(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_u8_ptr(src) && is_type_cstring(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_cstring(src) && is_type_u8_multi_ptr(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_u8_multi_ptr(src) && is_type_cstring(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_cstring(src) && is_type_rawptr(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_rawptr(src) && is_type_cstring(dst)) { + return cg_emit_transmute(p, value, dst); + } + + + if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { + GB_PANIC("TODO(bill): cstring_to_string call"); + // TEMPORARY_ALLOCATOR_GUARD(); + // lbValue c = lb_emit_conv(p, value, t_cstring); + // auto args = array_make(temporary_allocator(), 1); + // args[0] = c; + // lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args); + // return lb_emit_conv(p, s, dst); + } + + // float -> float + if (is_type_float(src) && is_type_float(dst)) { + i64 sz = type_size_of(src); + i64 dz = type_size_of(dst); + + if (sz == 2 || dz == 2) { + GB_PANIC("TODO(bill): f16 conversions"); + } + + + if (dz == sz) { + if (types_have_same_internal_endian(src, dst)) { + return cg_value(value.node, t); + } else { + return cg_emit_byte_swap(p, value, t); + } + } + + if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) { + Type *platform_src_type = integer_endian_type_to_platform_type(src); + Type *platform_dst_type = integer_endian_type_to_platform_type(dst); + cgValue res = {}; + res = cg_emit_conv(p, value, platform_src_type); + res = cg_emit_conv(p, res, platform_dst_type); + if (is_type_different_to_arch_endianness(dst)) { + res = cg_emit_byte_swap(p, res, t); + } + return cg_emit_conv(p, res, t); + } + + + if (dz >= sz) { + return cg_value(tb_inst_fpxt(p->func, value.node, dt), t); + } + return cg_value(tb_inst_trunc(p->func, value.node, dt), t); + } + + if (is_type_complex(src) && is_type_complex(dst)) { + GB_PANIC("TODO(bill): complex -> complex"); + } + + if (is_type_quaternion(src) && is_type_quaternion(dst)) { + // @QuaternionLayout + GB_PANIC("TODO(bill): quaternion -> quaternion"); + } + if (is_type_integer(src) && is_type_complex(dst)) { + GB_PANIC("TODO(bill): int -> complex"); + } + if (is_type_float(src) && is_type_complex(dst)) { + GB_PANIC("TODO(bill): float -> complex"); + } + if (is_type_integer(src) && is_type_quaternion(dst)) { + GB_PANIC("TODO(bill): int -> quaternion"); + } + if (is_type_float(src) && is_type_quaternion(dst)) { + GB_PANIC("TODO(bill): float -> quaternion"); + } + if (is_type_complex(src) && is_type_quaternion(dst)) { + GB_PANIC("TODO(bill): complex -> quaternion"); + } + + + // float <-> integer + if (is_type_float(src) && is_type_integer(dst)) { + if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) { + Type *platform_src_type = integer_endian_type_to_platform_type(src); + Type *platform_dst_type = integer_endian_type_to_platform_type(dst); + cgValue res = {}; + res = cg_emit_conv(p, value, platform_src_type); + res = cg_emit_conv(p, res, platform_dst_type); + return cg_emit_conv(p, res, t); + } + + // if (is_type_integer_128bit(dst)) { + // TEMPORARY_ALLOCATOR_GUARD(); + + // auto args = array_make(temporary_allocator(), 1); + // args[0] = value; + // char const *call = "fixunsdfdi"; + // if (is_type_unsigned(dst)) { + // call = "fixunsdfti"; + // } + // lbValue res_i128 = lb_emit_runtime_call(p, call, args); + // return lb_emit_conv(p, res_i128, t); + // } + + bool is_signed = !is_type_unsigned(dst); + return cg_value(tb_inst_float2int(p->func, value.node, dt, is_signed), t); + } + if (is_type_integer(src) && is_type_float(dst)) { + if (is_type_different_to_arch_endianness(src) || is_type_different_to_arch_endianness(dst)) { + Type *platform_src_type = integer_endian_type_to_platform_type(src); + Type *platform_dst_type = integer_endian_type_to_platform_type(dst); + cgValue res = {}; + res = cg_emit_conv(p, value, platform_src_type); + res = cg_emit_conv(p, res, platform_dst_type); + if (is_type_different_to_arch_endianness(dst)) { + res = cg_emit_byte_swap(p, res, t); + } + return cg_emit_conv(p, res, t); + } + + // if (is_type_integer_128bit(src)) { + // TEMPORARY_ALLOCATOR_GUARD(); + + // auto args = array_make(temporary_allocator(), 1); + // args[0] = value; + // char const *call = "floattidf"; + // if (is_type_unsigned(src)) { + // call = "floattidf_unsigned"; + // } + // lbValue res_f64 = lb_emit_runtime_call(p, call, args); + // return lb_emit_conv(p, res_f64, t); + // } + + bool is_signed = !is_type_unsigned(dst); + return cg_value(tb_inst_int2float(p->func, value.node, dt, is_signed), t); + } + + if (is_type_simd_vector(dst)) { + GB_PANIC("TODO(bill): ? -> #simd vector"); + } + + + // Pointer <-> uintptr + if (is_type_pointer(src) && is_type_uintptr(dst)) { + return cg_value(tb_inst_ptr2int(p->func, value.node, dt), t); + } + if (is_type_uintptr(src) && is_type_pointer(dst)) { + return cg_value(tb_inst_int2ptr(p->func, value.node), t); + } + if (is_type_multi_pointer(src) && is_type_uintptr(dst)) { + return cg_value(tb_inst_ptr2int(p->func, value.node, dt), t); + } + if (is_type_uintptr(src) && is_type_multi_pointer(dst)) { + return cg_value(tb_inst_int2ptr(p->func, value.node), t); + } + + if (is_type_union(dst)) { + GB_PANIC("TODO(bill): ? -> union"); + } + + // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's + // subtype polymorphism casting + if (check_is_assignable_to_using_subtype(src_type, t)) { + GB_PANIC("TODO(bill): ? -> subtyping"); + } + + // Pointer <-> Pointer + if (is_type_pointer(src) && is_type_pointer(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + if (is_type_multi_pointer(src) && is_type_pointer(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + if (is_type_pointer(src) && is_type_multi_pointer(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + if (is_type_multi_pointer(src) && is_type_multi_pointer(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + + // proc <-> proc + if (is_type_proc(src) && is_type_proc(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + + // pointer -> proc + if (is_type_pointer(src) && is_type_proc(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + // proc -> pointer + if (is_type_proc(src) && is_type_pointer(dst)) { + return cg_value(tb_inst_bitcast(p->func, value.node, dt), t); + } + + // []byte/[]u8 <-> string + if (is_type_u8_slice(src) && is_type_string(dst)) { + return cg_emit_transmute(p, value, t); + } + if (is_type_string(src) && is_type_u8_slice(dst)) { + return cg_emit_transmute(p, value, t); + } + + if (is_type_matrix(dst) && !is_type_matrix(src)) { + GB_PANIC("TODO(bill): !matrix -> matrix"); + } + + if (is_type_matrix(dst) && is_type_matrix(src)) { + GB_PANIC("TODO(bill): matrix -> matrix"); + } + + if (is_type_any(dst)) { + GB_PANIC("TODO(bill): ? -> any"); + } + + i64 src_sz = type_size_of(src); + i64 dst_sz = type_size_of(dst); + + if (src_sz == dst_sz) { + // bit_set <-> integer + if (is_type_integer(src) && is_type_bit_set(dst)) { + cgValue v = cg_emit_conv(p, value, bit_set_to_int(dst)); + return cg_emit_transmute(p, v, t); + } + if (is_type_bit_set(src) && is_type_integer(dst)) { + cgValue bs = cg_emit_transmute(p, value, bit_set_to_int(src)); + return cg_emit_conv(p, bs, dst); + } + + // typeid <-> integer + if (is_type_integer(src) && is_type_typeid(dst)) { + return cg_emit_transmute(p, value, dst); + } + if (is_type_typeid(src) && is_type_integer(dst)) { + return cg_emit_transmute(p, value, dst); + } + } + + + if (is_type_untyped(src)) { + if (is_type_string(src) && is_type_string(dst)) { + cgAddr result = cg_add_local(p, t, nullptr, false); + cg_addr_store(p, result, value); + return cg_addr_load(p, result); + } + } + + + gb_printf_err("%.*s\n", LIT(p->name)); + gb_printf_err("cg_emit_conv: src -> dst\n"); + gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t)); + gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst)); + gb_printf_err("Not Identical %p != %p\n", src_type, t); + gb_printf_err("Not Identical %p != %p\n", src, dst); + + + GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'", + type_to_string(src_type), type_to_string(t), + LIT(p->name)); + + return {}; +} + gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { @@ -227,30 +604,39 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { } case Type_MultiPointer: { - // lbAddr res = lb_add_local_generated(p, type_of_expr(expr), false); - // if (se->high == nullptr) { - // lbValue offset = base; - // LLVMValueRef indices[1] = {low.value}; - // offset.value = LLVMBuildGEP2(p->builder, lb_type(p->module, offset.type->MultiPointer.elem), offset.value, indices, 1, ""); - // lb_addr_store(p, res, offset); - // } else { - // low = lb_emit_conv(p, low, t_int); - // high = lb_emit_conv(p, high, t_int); - - // lb_emit_multi_pointer_slice_bounds_check(p, se->open, low, high); - - // LLVMValueRef indices[1] = {low.value}; - // LLVMValueRef ptr = LLVMBuildGEP2(p->builder, lb_type(p->module, base.type->MultiPointer.elem), base.value, indices, 1, ""); - // LLVMValueRef len = LLVMBuildSub(p->builder, high.value, low.value, ""); - - // LLVMValueRef gep0 = lb_emit_struct_ep(p, res.addr, 0).value; - // LLVMValueRef gep1 = lb_emit_struct_ep(p, res.addr, 1).value; - // LLVMBuildStore(p->builder, ptr, gep0); - // LLVMBuildStore(p->builder, len, gep1); - // } - // return res; - GB_PANIC("cg_build_addr_slice_expr Type_MultiPointer"); - break; + Type *res_type = type_of_expr(expr); + if (se->high == nullptr) { + cgAddr res = cg_add_local(p, res_type, nullptr, false); + GB_ASSERT(base.kind == cgValue_Value); + GB_ASSERT(low.kind == cgValue_Value); + + i64 stride = type_size_of(type->MultiPointer.elem); + cgValue offset = cg_value(tb_inst_array_access(p->func, base.node, low.node, stride), base.type); + cg_addr_store(p, res, offset); + return res; + } else { + cgAddr res = cg_add_local(p, res_type, nullptr, true); + low = cg_emit_conv(p, low, t_int); + high = cg_emit_conv(p, high, t_int); + + // cg_emit_multi_pointer_slice_bounds_check(p, se->open, low, high); + + i64 stride = type_size_of(type->MultiPointer.elem); + TB_Node *offset = tb_inst_array_access(p->func, base.node, low.node, stride); + TB_Node *len = tb_inst_sub(p->func, high.node, low.node, cast(TB_ArithmeticBehavior)0); + + TB_Node *data_ptr = tb_inst_member_access(p->func, res.addr.node, type_offset_of(res_type, 0)); + TB_Node *len_ptr = tb_inst_member_access(p->func, res.addr.node, type_offset_of(res_type, 1)); + + tb_inst_store(p->func, TB_TYPE_PTR, data_ptr, offset, cast(TB_CharUnits)build_context.ptr_size, false); + tb_inst_store(p->func, TB_TYPE_INT, len_ptr, len, cast(TB_CharUnits)build_context.int_size, false); + + // LLVMValueRef gep0 = cg_emit_struct_ep(p, res.addr, 0).value; + // LLVMValueRef gep1 = cg_emit_struct_ep(p, res.addr, 1).value; + // LLVMBuildStore(p->builder, ptr, gep0); + // LLVMBuildStore(p->builder, len, gep1); + return res; + } } case Type_Array: { diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 99b70a6a8..d763e2f8c 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1,4 +1,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Type *type) { + // TODO(bill): cache the procedure type generation + GB_ASSERT(build_context.metrics.os == TargetOs_windows); + GB_ASSERT(type != nullptr); type = base_type(type); GB_ASSERT(type->kind == Type_Proc); @@ -35,7 +38,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); break; - case Basic_f16: param.dt = TB_TYPE_I16; break; + case Basic_f16: param.dt = TB_TYPE_F16; break; case Basic_f32: param.dt = TB_TYPE_F32; break; case Basic_f64: param.dt = TB_TYPE_F64; break; @@ -86,11 +89,11 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); break; - case Basic_f16le: param.dt = TB_TYPE_I16; break; + case Basic_f16le: param.dt = TB_TYPE_F16; break; case Basic_f32le: param.dt = TB_TYPE_F32; break; case Basic_f64le: param.dt = TB_TYPE_F64; break; - case Basic_f16be: param.dt = TB_TYPE_I16; break; + case Basic_f16be: param.dt = TB_TYPE_F16; break; case Basic_f32be: param.dt = TB_TYPE_F32; break; case Basic_f64be: param.dt = TB_TYPE_F64; break; } @@ -117,15 +120,139 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty if (is_blank_ident(e->token)) { param.name = alloc_cstring(temporary_allocator(), e->token.string); } + param.debug_type = cg_debug_type(m, e->type); array_add(¶ms, param); } } - auto results = array_make(heap_allocator(), 0, pt->result_count); - // if (pt->results) for (Entity *e : pt->params->Tuple.variables) { - // // TODO(bill): - // } + auto results = array_make(heap_allocator(), 0, 1); + + Type *result_type = reduce_tuple_to_single_type(pt->results); + + if (result_type) { + bool return_is_tuple = result_type->kind == Type_Tuple && is_calling_convention_odin(pt->calling_convention); + if (return_is_tuple) { + for (isize i = 0; i < result_type->Tuple.variables.count-1; i++) { + Entity *e = result_type->Tuple.variables[i]; + TB_PrototypeParam param = {}; + param.dt = TB_TYPE_PTR; + param.debug_type = cg_debug_type(m, alloc_type_pointer(e->type)); + array_add(¶ms, param); + } + + result_type = result_type->Tuple.variables[result_type->Tuple.variables.count-1]->type; + } + + Type *rt = core_type(result_type); + i64 sz = type_size_of(rt); + + TB_PrototypeParam result = {}; + + switch (rt->kind) { + case Type_Basic: + switch (rt->Basic.kind) { + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + case Basic_i8: + case Basic_u8: + case Basic_i16: + case Basic_u16: + case Basic_i32: + case Basic_u32: + case Basic_i64: + case Basic_u64: + case Basic_i128: + case Basic_u128: + case Basic_rune: + case Basic_int: + case Basic_uint: + case Basic_uintptr: + result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + case Basic_f16: result.dt = TB_TYPE_I16; break; + case Basic_f32: result.dt = TB_TYPE_F32; break; + case Basic_f64: result.dt = TB_TYPE_F64; break; + + case Basic_rawptr: + result.dt = TB_TYPE_PTR; + break; + case Basic_cstring: // ^u8 + result.dt = TB_TYPE_PTR; + break; + + case Basic_typeid: + result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + // Endian Specific Types + case Basic_i16le: + case Basic_u16le: + case Basic_i32le: + case Basic_u32le: + case Basic_i64le: + case Basic_u64le: + case Basic_i128le: + case Basic_u128le: + case Basic_i16be: + case Basic_u16be: + case Basic_i32be: + case Basic_u32be: + case Basic_i64be: + case Basic_u64be: + case Basic_i128be: + case Basic_u128be: + result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + break; + + case Basic_f16le: result.dt = TB_TYPE_I16; break; + case Basic_f32le: result.dt = TB_TYPE_F32; break; + case Basic_f64le: result.dt = TB_TYPE_F64; break; + + case Basic_f16be: result.dt = TB_TYPE_I16; break; + case Basic_f32be: result.dt = TB_TYPE_F32; break; + case Basic_f64be: result.dt = TB_TYPE_F64; break; + } + + case Type_Pointer: + case Type_MultiPointer: + case Type_Proc: + result.dt = TB_TYPE_PTR; + break; + + default: + switch (sz) { + case 1: result.dt = TB_TYPE_I8; break; + case 2: result.dt = TB_TYPE_I16; break; + case 4: result.dt = TB_TYPE_I32; break; + case 8: result.dt = TB_TYPE_I64; break; + } + } + + if (result.dt.raw != 0) { + result.debug_type = cg_debug_type(m, result_type); + array_add(&results, result); + } else { + result.debug_type = cg_debug_type(m, alloc_type_pointer(result_type)); + result.dt = TB_TYPE_PTR; + + array_resize(¶ms, params.count+1); + array_copy(¶ms, params, 1); + params[0] = result; + } + } + + if (pt->calling_convention == ProcCC_Odin) { + TB_PrototypeParam param = {}; + param.dt = TB_TYPE_PTR; + param.debug_type = cg_debug_type(m, t_context_ptr); + param.name = "__.context_ptr"; + array_add(¶ms, param); + } return tb_prototype_create(m->mod, TB_CDECL, params.count, params.data, results.count, results.data, pt->c_vararg); } @@ -408,12 +535,16 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice } GB_ASSERT(value.kind == cgValue_Value); + // TODO(bill): abstract out the function prototype stuff so that you handle the ABI correctly (at least for win64 at the moment) TB_FunctionPrototype *proto = cg_procedure_type_as_prototype(p->module, value.type); TB_Node *target = value.node; - auto params = slice_make(temporary_allocator(), 0); + auto params = slice_make(temporary_allocator(), 0 /*proto->param_count*/); + for_array(i, params) { + // params[i] = proto + } GB_ASSERT(target != nullptr); - TB_MultiOutput multi_output = tb_inst_call(p->func, proto, target, 0, nullptr); + TB_MultiOutput multi_output = tb_inst_call(p->func, proto, target, params.count, params.data); gb_unused(multi_output); return {}; } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 2952539ca..2f2bdd55f 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -376,6 +376,10 @@ gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, for_array(i, inits) { cgAddr lval = lvals[i]; cgValue init = inits[i]; + if (init.type == nullptr) { + // TODO(bill): figure out how to do this + continue; + } cg_addr_store(p, lval, init); } diff --git a/src/types.cpp b/src/types.cpp index 385ca926d..98be2b6cf 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -3952,6 +3952,7 @@ gb_internal i64 type_offset_of(Type *t, i32 index) { case -1: return align_formula(t->Union.variant_block_size, build_context.ptr_size); // __type_info } } + GB_ASSERT(index == 0); return 0; } -- cgit v1.2.3 From bd73834e196d21aaed0bb1fd0a3d84e323b8aba7 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 17 Jul 2023 16:56:10 +0100 Subject: Update Tilde; mock out `cg_build_return_stmt` 128-bit types are broken --- src/tilde/tb.h | 26 +++++++--- src/tilde/tb.lib | Bin 4112646 -> 4113018 bytes src/tilde_backend.cpp | 4 +- src/tilde_backend.hpp | 3 +- src/tilde_const.cpp | 2 +- src/tilde_proc.cpp | 139 ++++++++++++++++++++++++++------------------------ src/tilde_stmt.cpp | 28 +++++++++- 7 files changed, 125 insertions(+), 77 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 8b698ff30..4fb5d30ef 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -195,8 +195,6 @@ typedef union TB_DataType { typedef enum TB_NodeTypeEnum { TB_NULL = 0, - TB_RETURN, // fn(r: region, x: data) - // only one per function TB_START, // fn() @@ -823,7 +821,16 @@ TB_API TB_DebugType* tb_debug_create_array(TB_Module* m, TB_DebugType* base, siz TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, ptrdiff_t len, const char* name, TB_CharUnits offset); -TB_API void tb_debug_complete_record(TB_DebugType* type, TB_DebugType** members, size_t count, TB_CharUnits size, TB_CharUnits align); + +// returns the array you need to fill with fields +TB_API TB_DebugType** tb_debug_record_begin(TB_DebugType* type, size_t count); +TB_API void tb_debug_record_end(TB_DebugType* type, TB_CharUnits size, TB_CharUnits align); + +TB_API TB_DebugType* tb_debug_create_func(TB_Module* m, TB_CallingConv cc, size_t param_count, size_t return_count, bool has_varargs); + +// you'll need to fill these if you make a function +TB_API TB_DebugType** tb_debug_func_params(TB_DebugType* type); +TB_API TB_DebugType** tb_debug_func_returns(TB_DebugType* type); //////////////////////////////// // IR access @@ -850,6 +857,8 @@ TB_API TB_Global* tb_symbol_as_global(TB_Symbol* s); //////////////////////////////// // Function IR Generation //////////////////////////////// +TB_API void tb_get_data_type_size(TB_Module* mod, TB_DataType dt, size_t* size, size_t* align); + // the user_data is expected to be a valid FILE* TB_API void tb_default_print_callback(void* user_data, const char* fmt, ...); @@ -869,6 +878,12 @@ TB_API void tb_symbol_set_name(TB_Symbol* s, ptrdiff_t len, const char* name); TB_API void tb_symbol_bind_ptr(TB_Symbol* s, void* ptr); TB_API const char* tb_symbol_get_name(TB_Symbol* s); +// same as tb_function_set_prototype except it will handle lowering from types like the TB_DebugType +// into the correct ABI and exposing sane looking nodes to the parameters. +// +// returns the parameters +TB_API TB_Node** tb_function_set_prototype_from_dbg(TB_Function* f, TB_DebugType* dbg, TB_Arena* arena, size_t* out_param_count); + // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources TB_API void tb_function_set_prototype(TB_Function* f, TB_FunctionPrototype* p, TB_Arena* arena); TB_API TB_FunctionPrototype* tb_function_get_prototype(TB_Function* f); @@ -890,7 +905,6 @@ TB_API void tb_inst_keep_alive(TB_Function* f, TB_Node* src); TB_API TB_Node* tb_inst_poison(TB_Function* f); TB_API TB_Node* tb_inst_param(TB_Function* f, int param_id); -TB_API TB_Node* tb_inst_param_addr(TB_Function* f, int param_id); TB_API TB_Node* tb_inst_fpxt(TB_Function* f, TB_Node* src, TB_DataType dt); TB_API TB_Node* tb_inst_sxt(TB_Function* f, TB_Node* src, TB_DataType dt); @@ -902,7 +916,7 @@ TB_API TB_Node* tb_inst_int2float(TB_Function* f, TB_Node* src, TB_DataType dt, TB_API TB_Node* tb_inst_float2int(TB_Function* f, TB_Node* src, TB_DataType dt, bool is_signed); TB_API TB_Node* tb_inst_bitcast(TB_Function* f, TB_Node* src, TB_DataType dt); -TB_API TB_Node* tb_inst_local(TB_Function* f, uint32_t size, TB_CharUnits align); +TB_API TB_Node* tb_inst_local(TB_Function* f, TB_CharUnits size, TB_CharUnits align); TB_API TB_Node* tb_inst_load(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_CharUnits align, bool is_volatile); TB_API void tb_inst_store(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_Node* val, TB_CharUnits align, bool is_volatile); @@ -918,7 +932,7 @@ TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); TB_API void tb_inst_memset(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); // zero 'count' bytes on 'dst' -TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); +TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* count, TB_CharUnits align, bool is_volatile); // performs a copy of 'count' elements from one memory location to another // both locations cannot overlap. diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index bad51e7e6..b52ce4c55 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index dfe39c385..db759b767 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -31,7 +31,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_uint: case Basic_uintptr: case Basic_typeid: - return TB_TYPE_INTN(cast(u16)(8*sz)); + return TB_TYPE_INTN(cast(u16)gb_min(8*sz, 64)); case Basic_f16: return TB_TYPE_F16; case Basic_f32: return TB_TYPE_F32; @@ -58,7 +58,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_u64be: case Basic_i128be: case Basic_u128be: - return TB_TYPE_INTN(cast(u16)(8*sz)); + return TB_TYPE_INTN(cast(u16)gb_min(8*sz, 64)); case Basic_f16le: return TB_TYPE_F16; case Basic_f32le: return TB_TYPE_F32; diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 073e81f5d..b2192cce4 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -8,7 +8,8 @@ #include "tilde/tb.h" #define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } -#define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } +// #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } +#define TB_TYPE_I128 TB_TYPE_INTN(64) #define TB_TYPE_INT TB_TYPE_INTN(cast(u16)(8*build_context.int_size)) #define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)(8*build_context.ptr_size)) diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 35c87641f..75b66567e 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -86,7 +86,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: - GB_ASSERT(dt.raw != TB_TYPE_I128.raw); + // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { u64 i = exact_value_to_u64(value); return cg_value(tb_inst_uint(p->func, dt, i), type); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index d763e2f8c..af9bee189 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -35,7 +35,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_int: case Basic_uint: case Basic_uintptr: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16: param.dt = TB_TYPE_F16; break; @@ -66,7 +66,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty break; case Basic_typeid: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; // Endian Specific Types @@ -86,7 +86,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_u64be: case Basic_i128be: case Basic_u128be: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16le: param.dt = TB_TYPE_F16; break; @@ -171,7 +171,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_int: case Basic_uint: case Basic_uintptr: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16: result.dt = TB_TYPE_I16; break; @@ -186,7 +186,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty break; case Basic_typeid: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; // Endian Specific Types @@ -206,7 +206,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_u64be: case Basic_i128be: case Basic_u128be: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16le: result.dt = TB_TYPE_I16; break; @@ -395,70 +395,75 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; - if (pt->params) { - int param_index = 0; - for (Entity *e : pt->params->Tuple.variables) { - if (e->kind != Entity_Variable) { - continue; - } - - if (param_index >= p->proto->param_count) { - break; - } + if (pt->params == nullptr) { + return; + } + int param_index = 0; + for (Entity *e : pt->params->Tuple.variables) { + if (e->kind != Entity_Variable) { + continue; + } - TB_Node *ptr = tb_inst_param_addr(p->func, param_index); - cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); + if (param_index >= p->proto->param_count) { + break; + } - if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { - // NOTE(bill): for debugging purposes only - String name = e->token.string; - TB_DebugType *debug_type = cg_debug_type(p->module, e->type); - tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + // TB_Node *ptr = tb_inst_param_addr(p->func, param_index); + TB_Node *param = tb_inst_param(p->func, param_index); + TB_Node *ptr = tb_inst_local(p->func, cast(TB_CharUnits)type_size_of(e->type), cast(TB_CharUnits)type_align_of(e->type)); + TB_DataType dt = cg_data_type(e->type); + tb_inst_store(p->func, dt, ptr, param, cast(TB_CharUnits)type_align_of(e->type), false); + cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); - } - cgAddr addr = cg_addr(local); - if (e) { - map_set(&p->variable_map, e, addr); - } + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); - // if (arg_type->kind == lbArg_Ignore) { - // continue; - // } else if (arg_type->kind == lbArg_Direct) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // LLVMTypeRef param_type = lb_type(p->module, e->type); - // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); - // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); - - // lbValue param = {}; - // param.value = value; - // param.type = e->type; - - // map_set(&p->direct_parameters, e, param); - - // lbValue ptr = lb_address_from_load_or_generate_local(p, param); - // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); - // lb_add_entity(p->module, e, ptr); - - // lbBlock *block = p->decl_block; - // if (original_value != value) { - // block = p->curr_block; - // } - // LLVMValueRef debug_storage_value = value; - // if (original_value != value && LLVMIsALoadInst(value)) { - // debug_storage_value = LLVMGetOperand(value, 0); - // } - // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); - // } - // } else if (arg_type->kind == lbArg_Indirect) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // lbValue ptr = {}; - // ptr.value = LLVMGetParam(p->value, param_offset+param_index); - // ptr.type = alloc_type_pointer(e->type); - // lb_add_entity(p->module, e, ptr); - // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); - // } - // } } + cgAddr addr = cg_addr(local); + if (e) { + map_set(&p->variable_map, e, addr); + } + + // if (arg_type->kind == lbArg_Ignore) { + // continue; + // } else if (arg_type->kind == lbArg_Direct) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // LLVMTypeRef param_type = lb_type(p->module, e->type); + // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); + // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); + + // lbValue param = {}; + // param.value = value; + // param.type = e->type; + + // map_set(&p->direct_parameters, e, param); + + // lbValue ptr = lb_address_from_load_or_generate_local(p, param); + // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); + // lb_add_entity(p->module, e, ptr); + + // lbBlock *block = p->decl_block; + // if (original_value != value) { + // block = p->curr_block; + // } + // LLVMValueRef debug_storage_value = value; + // if (original_value != value && LLVMIsALoadInst(value)) { + // debug_storage_value = LLVMGetOperand(value, 0); + // } + // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); + // } + // } else if (arg_type->kind == lbArg_Indirect) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // lbValue ptr = {}; + // ptr.value = LLVMGetParam(p->value, param_offset+param_index); + // ptr.type = alloc_type_pointer(e->type); + // lb_add_entity(p->module, e, ptr); + // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); + // } + // } } } @@ -466,7 +471,9 @@ gb_internal void cg_procedure_end(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } - tb_inst_ret(p->func, 0, nullptr); + if (tb_inst_get_control(p->func)) { + tb_inst_ret(p->func, 0, nullptr); + } if (p->name == "main") { TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index a38886c2e..787b94a58 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -736,7 +736,33 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { } gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { - + TypeTuple *tuple = &p->type->Proc.results->Tuple; + isize return_count = p->type->Proc.result_count; + gb_unused(tuple); + isize res_count = return_results.count; + gb_unused(res_count); + + if (return_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + return; + } else if (return_count == 1) { + Entity *e = tuple->variables[0]; + if (res_count == 0) { + cgValue zero = cg_const_nil(p, tuple->variables[0]->type); + if (zero.kind == cgValue_Value) { + tb_inst_ret(p->func, 1, &zero.node); + } + return; + } + cgValue res = cg_build_expr(p, return_results[0]); + res = cg_emit_conv(p, res, e->type); + if (res.kind == cgValue_Value) { + tb_inst_ret(p->func, 1, &res.node); + } + return; + } else { + GB_PANIC("TODO(bill): MUTLIPLE RETURN VALUES"); + } } -- cgit v1.2.3 From b2c75dc3a22f72bcf7b4a47348bd46e4ddb05200 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 17 Jul 2023 22:18:15 +0100 Subject: Mostly fill in `cg_debug_type` --- src/tilde_backend.cpp | 3 + src/tilde_backend.hpp | 3 + src/tilde_proc.cpp | 2 +- src/tilde_stmt.cpp | 338 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 345 insertions(+), 1 deletion(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index db759b767..798f51bb3 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -396,6 +396,8 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->file_id_map); + map_init(&m->debug_type_map); + for_array(id, global_files) { if (AstFile *f = global_files[id]) { @@ -411,6 +413,7 @@ gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); array_free(&m->procedures_to_generate); map_destroy(&m->file_id_map); + map_destroy(&m->debug_type_map); tb_module_destroy(m->mod); } diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index b2192cce4..032229193 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -176,6 +176,9 @@ struct cgModule { PtrMap procedure_values; Array procedures_to_generate; + RecursiveMutex debug_type_mutex; + PtrMap debug_type_map; + PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) std::atomic nested_type_name_guid; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index af9bee189..49af695ee 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -409,7 +409,7 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { } // TB_Node *ptr = tb_inst_param_addr(p->func, param_index); - TB_Node *param = tb_inst_param(p->func, param_index); + TB_Node *param = tb_inst_param(p->func, param_index++); TB_Node *ptr = tb_inst_local(p->func, cast(TB_CharUnits)type_size_of(e->type), cast(TB_CharUnits)type_align_of(e->type)); TB_DataType dt = cg_data_type(e->type); tb_inst_store(p->func, dt, ptr, param, cast(TB_CharUnits)type_align_of(e->type), false); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 6c0e8cf76..4e49199f9 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -629,7 +629,345 @@ gb_internal void cg_pop_target_list(cgProcedure *p) { p->target_list = p->target_list->prev; } +gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type); gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type) { + mutex_lock(&m->debug_type_mutex); + defer (mutex_unlock(&m->debug_type_mutex)); + TB_DebugType **found = map_get(&m->debug_type_map, type); + if (found) { + return *found; + } + + TB_DebugType *res = cg_debug_type_internal(m, type); + map_set(&m->debug_type_map, type, res); + return res; +} + +gb_internal TB_DebugType *cg_debug_type_internal_record(cgModule *m, Type *type, String const &record_name) { + Type *bt = base_type(type); + switch (bt->kind) { + case Type_Struct: + { + type_set_offsets(bt); + + TB_DebugType *record = nullptr; + if (bt->Struct.is_raw_union) { + record = tb_debug_create_union(m->mod, record_name.len, cast(char const *)record_name.text); + } else { + record = tb_debug_create_struct(m->mod, record_name.len, cast(char const *)record_name.text); + } + if (record_name.len != 0) { + map_set(&m->debug_type_map, type, record); + } + + TB_DebugType **fields = tb_debug_record_begin(record, bt->Struct.fields.count); + for_array(i, bt->Struct.fields) { + Entity *e = bt->Struct.fields[i]; + Type *type = e->type; + if (is_type_proc(type)) { + type = t_rawptr; + } + TB_DebugType *field_type = cg_debug_type(m, type); + String name = e->token.string; + TB_CharUnits offset = cast(TB_CharUnits)bt->Struct.offsets[i]; + if (name.len == 0) { + name = str_lit("_"); + } + + fields[i] = tb_debug_create_field(m->mod, field_type, name.len, cast(char const *)name.text, offset); + } + tb_debug_record_end( + record, + cast(TB_CharUnits)type_size_of(type), + cast(TB_CharUnits)type_align_of(type) + ); + return record; + } + break; + case Type_Union: + { + TB_DebugType *record = tb_debug_create_struct(m->mod, record_name.len, cast(char const *)record_name.text); + if (record_name.len != 0) { + map_set(&m->debug_type_map, type, record); + } + + i64 variant_count = bt->Union.variants.count; + if (is_type_union_maybe_pointer(bt)) { + // NO TAG + GB_ASSERT(variant_count == 1); + TB_DebugType **fields = tb_debug_record_begin(record, variant_count); + TB_DebugType *variant_type = cg_debug_type(m, bt->Union.variants[0]); + fields[0] = tb_debug_create_field(m->mod, variant_type, -1, "v0", 0); + tb_debug_record_end( + record, + cast(TB_CharUnits)type_size_of(type), + cast(TB_CharUnits)type_align_of(type) + ); + } else { + TB_DebugType **fields = tb_debug_record_begin(record, variant_count+1); + for_array(i, bt->Union.variants) { + Type *v = bt->Union.variants[i]; + TB_DebugType *variant_type = cg_debug_type(m, v); + char name[32] = {}; + u32 v_index = cast(u32)i; + if (bt->Union.kind != UnionType_no_nil) { + v_index += 1; + } + gb_snprintf(name, 31, "v%u", v_index); + fields[i] = tb_debug_create_field(m->mod, variant_type, -1, name, 0); + } + + TB_DebugType *tag_type = cg_debug_type(m, union_tag_type(bt)); + fields[variant_count] = tb_debug_create_field(m->mod, tag_type, -1, "tag", cast(TB_CharUnits)bt->Union.variant_block_size); + + } + tb_debug_record_end( + record, + cast(TB_CharUnits)type_size_of(type), + cast(TB_CharUnits)type_align_of(type) + ); + return record; + } + break; + } + return nullptr; +} + + +gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { + if (type == nullptr) { + return tb_debug_get_void(m->mod); + } + if (type->kind == Type_Named) { + String name = type->Named.name; + TB_DebugType *res = cg_debug_type_internal_record(m, type, name); + if (res) { + return res; + } + type = base_type(type->Named.base); + } + + TB_CharUnits int_size = cast(TB_CharUnits)build_context.int_size; + TB_CharUnits ptr_size = cast(TB_CharUnits)build_context.ptr_size; + TB_CharUnits size = cast(TB_CharUnits)type_size_of(type); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(type); + int bits = cast(int)(8*size); + bool is_signed = is_type_integer(core_type(type)) && !is_type_unsigned(core_type(type)); + + switch (type->kind) { + case Type_Basic: + switch (type->Basic.kind) { + case Basic_bool: return tb_debug_get_bool(m->mod); + case Basic_b8: return tb_debug_get_bool(m->mod); + case Basic_b16: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_b32: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_b64: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i8: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u8: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i16: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u16: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i32: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u32: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i64: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u64: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i128: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_u128: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_rune: return tb_debug_get_integer(m->mod, is_signed, bits); + + case Basic_f16: return tb_debug_get_integer(m->mod, false, bits); + case Basic_f32: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64: return tb_debug_get_float(m->mod,TB_FLT_64); + + case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + { + String name = basic_types[type->Basic.kind].Basic.name; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + Type *et = base_complex_elem_type(type); + TB_CharUnits elem_size = cast(TB_CharUnits)type_size_of(et); + TB_DebugType *elem = cg_debug_type(m, et); + + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, elem, -1, "real", 0*elem_size); + fields[1] = tb_debug_create_field(m->mod, elem, -1, "imag", 1*elem_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Basic_quaternion64: + case Basic_quaternion128: + case Basic_quaternion256: + { + String name = basic_types[type->Basic.kind].Basic.name; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + Type *et = base_complex_elem_type(type); + TB_CharUnits elem_size = cast(TB_CharUnits)type_size_of(et); + TB_DebugType *elem = cg_debug_type(m, et); + + // @QuaternionLayout + TB_DebugType **fields = tb_debug_record_begin(record, 4); + fields[0] = tb_debug_create_field(m->mod, elem, -1, "imag", 0*elem_size); + fields[1] = tb_debug_create_field(m->mod, elem, -1, "jmag", 1*elem_size); + fields[2] = tb_debug_create_field(m->mod, elem, -1, "kmag", 2*elem_size); + fields[3] = tb_debug_create_field(m->mod, elem, -1, "real", 3*elem_size); + + tb_debug_record_end(record, size, align); + return record; + } + + case Basic_int: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_uint: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_uintptr: return tb_debug_get_integer(m->mod, is_signed, bits); + + case Basic_rawptr: return tb_debug_create_ptr(m->mod, tb_debug_get_void(m->mod)); + case Basic_string: + { + String name = basic_types[type->Basic.kind].Basic.name; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + // @QuaternionLayout + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, cg_debug_type(m, t_u8_ptr), -1, "data", 0*int_size); + fields[1] = tb_debug_create_field(m->mod, cg_debug_type(m, t_int), -1, "len", 1*int_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Basic_cstring: + return tb_debug_create_ptr(m->mod, tb_debug_get_integer(m->mod, false, 8)); + + case Basic_any: + { + String name = basic_types[type->Basic.kind].Basic.name; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + // @QuaternionLayout + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, cg_debug_type(m, t_rawptr), -1, "data", 0*ptr_size); + fields[1] = tb_debug_create_field(m->mod, cg_debug_type(m, t_typeid), -1, "id", 1*ptr_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Basic_typeid: return tb_debug_get_integer(m->mod, is_signed, bits); + + case Basic_i16le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u16le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i32le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u32le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i64le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u64le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i128le: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_u128le: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_i16be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u16be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i32be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u32be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i64be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u64be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_i128be: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_u128be: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + + case Basic_f16le: return tb_debug_get_integer(m->mod, false, bits); + case Basic_f32le: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64le: return tb_debug_get_float(m->mod,TB_FLT_64); + case Basic_f16be: return tb_debug_get_integer(m->mod, false, bits); + case Basic_f32be: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64be: return tb_debug_get_float(m->mod,TB_FLT_64); + } + break; + case Type_Generic: + GB_PANIC("SHOULD NEVER HIT"); + break; + case Type_Pointer: + return tb_debug_create_ptr(m->mod, cg_debug_type(m, type->Pointer.elem)); + case Type_MultiPointer: + return tb_debug_create_ptr(m->mod, cg_debug_type(m, type->MultiPointer.elem)); + case Type_Array: + return tb_debug_create_array(m->mod, cg_debug_type(m, type->Array.elem), type->Array.count); + case Type_EnumeratedArray: + return tb_debug_create_array(m->mod, cg_debug_type(m, type->EnumeratedArray.elem), type->EnumeratedArray.count); + case Type_Slice: + { + String name = {}; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, cg_debug_type(m, alloc_type_pointer(type->Slice.elem)), -1, "data", 0*int_size); + fields[1] = tb_debug_create_field(m->mod, cg_debug_type(m, t_int), -1, "len", 1*int_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Type_DynamicArray: + { + String name = {}; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + TB_DebugType **fields = tb_debug_record_begin(record, 4); + fields[0] = tb_debug_create_field(m->mod, cg_debug_type(m, alloc_type_pointer(type->Slice.elem)), -1, "data", 0*int_size); + fields[1] = tb_debug_create_field(m->mod, cg_debug_type(m, t_int), -1, "len", 1*int_size); + fields[2] = tb_debug_create_field(m->mod, cg_debug_type(m, t_int), -1, "cap", 2*int_size); + fields[3] = tb_debug_create_field(m->mod, cg_debug_type(m, t_allocator), -1, "allocator", 3*int_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Type_Map: + return cg_debug_type(m, t_raw_map); + case Type_Struct: + return cg_debug_type_internal_record(m, type, {}); + case Type_Union: + return cg_debug_type_internal_record(m, type, {}); + case Type_Enum: + return tb_debug_get_integer(m->mod, is_signed, bits); + case Type_Tuple: + GB_PANIC("SHOULD NEVER HIT"); + break; + case Type_Proc: + { + TypeProc *pt = &type->Proc; + isize param_count = 0; + isize return_count = 0; + TB_DebugType *func = tb_debug_create_func(m->mod, TB_CDECL, param_count, return_count, pt->c_vararg); + return func; + } + break; + case Type_BitSet: + return cg_debug_type(m, bit_set_to_int(type)); + case Type_SimdVector: + return tb_debug_create_array(m->mod, cg_debug_type(m, type->SimdVector.elem), type->SimdVector.count); + case Type_RelativePointer: + return cg_debug_type(m, type->RelativePointer.base_integer); + case Type_RelativeSlice: + { + String name = {}; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + + TB_DebugType *base_integer = cg_debug_type(m, type->RelativeSlice.base_integer); + TB_CharUnits bi_size = cast(TB_CharUnits)type_size_of(type->RelativeSlice.base_integer); + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, base_integer, -1, "data", 0*bi_size); + fields[1] = tb_debug_create_field(m->mod, base_integer, -1, "len", 1*bi_size); + + tb_debug_record_end(record, size, align); + return record; + } + case Type_Matrix: + { + i64 count = matrix_type_total_internal_elems(type); + return tb_debug_create_array(m->mod, cg_debug_type(m, type->Matrix.elem), count); + } + case Type_SoaPointer: + { + String name = {}; + TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); + TB_DebugType **fields = tb_debug_record_begin(record, 2); + fields[0] = tb_debug_create_field(m->mod, cg_debug_type(m, alloc_type_pointer(type->SoaPointer.elem)), -1, "ptr", 0*int_size); + fields[1] = tb_debug_create_field(m->mod, cg_debug_type(m, t_int), -1, "offset", 1*int_size); + + tb_debug_record_end(record, size, align); + return record; + } + } + // TODO(bill): cg_debug_type return tb_debug_get_void(m->mod); } -- cgit v1.2.3 From 988926b59d84aced0f5c4e5bf68d82f105f5d0da Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 17 Jul 2023 22:51:18 +0100 Subject: Flesh out debug procedure type --- src/tilde/tb.h | 2 +- src/tilde_backend.hpp | 2 ++ src/tilde_debug.cpp | 26 +++++++++++++++++++++++--- src/tilde_proc.cpp | 24 ++++++++++++++++++++---- 4 files changed, 46 insertions(+), 8 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index f49b28c38..4fb5d30ef 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -941,7 +941,7 @@ TB_API void tb_inst_memcpy(TB_Function* f, TB_Node* dst, TB_Node* src, TB_Node* // result = base + (index * stride) TB_API TB_Node* tb_inst_array_access(TB_Function* f, TB_Node* base, TB_Node* index, int64_t stride); -// result = base + +// result = base + offset // where base is a pointer TB_API TB_Node* tb_inst_member_access(TB_Function* f, TB_Node* base, int64_t offset); diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 4bc0a90fb..9e88cb4c7 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -145,6 +145,8 @@ struct cgProcedure { bool is_entry_point; bool is_startup; + TB_DebugType *debug_type; + cgValue value; Ast *curr_stmt; diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index a1ed04aaa..21e3a52ed 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -12,6 +12,20 @@ gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type) { return res; } +gb_internal TB_DebugType *cg_debug_type_for_proc(cgModule *m, Type *type) { + GB_ASSERT(is_type_proc(type)); + TB_DebugType **func_found = nullptr; + TB_DebugType *func_ptr = cg_debug_type(m, type); + GB_ASSERT(func_ptr != nullptr); + + mutex_lock(&m->debug_type_mutex); + func_found = map_get(&m->proc_debug_type_map, type); + mutex_unlock(&m->debug_type_mutex); + GB_ASSERT(func_found != nullptr); + return *func_found; +} + + gb_internal TB_DebugType *cg_debug_type_internal_record(cgModule *m, Type *type, String const &record_name) { Type *bt = base_type(type); switch (bt->kind) { @@ -345,7 +359,7 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { } } - if (is_odin_cc) { + if (pt->calling_convention == ProcCC_Odin) { // `context` ptr param_count += 1; } @@ -406,8 +420,14 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { } } - GB_ASSERT(param_index == param_count); - GB_ASSERT(return_index == return_count); + if (pt->calling_convention == ProcCC_Odin) { + Type *type = t_context_ptr; + String name = str_lit("__.context_ptr"); + params[param_index++] = tb_debug_create_field(m->mod, cg_debug_type(m, type), name.len, cast(char const *)name.text, 0); + } + + GB_ASSERT_MSG(param_index == param_count, "%td vs %td for %s", param_index, param_count, type_to_string(type)); + GB_ASSERT_MSG(return_index == return_count, "%td vs %td for %s", return_index, return_count, type_to_string(type)); return func_ptr; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 49af695ee..078c2ef9c 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -326,8 +326,16 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i if (p->symbol == nullptr) { TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - p->proto = cg_procedure_type_as_prototype(m, p->type); - tb_function_set_prototype(p->func, p->proto, arena); + + // p->proto = cg_procedure_type_as_prototype(m, p->type); + // tb_function_set_prototype(p->func, p->proto, arena); + + size_t out_param_count = 0; + p->debug_type = cg_debug_type_for_proc(m, p->type); + TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); + gb_unused(params); + p->proto = tb_function_get_prototype(p->func); + p->symbol = cast(TB_Symbol *)p->func; } @@ -373,8 +381,16 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - p->proto = cg_procedure_type_as_prototype(m, p->type); - tb_function_set_prototype(p->func, p->proto, arena); + + // p->proto = cg_procedure_type_as_prototype(m, p->type); + // tb_function_set_prototype(p->func, p->proto, arena); + size_t out_param_count = 0; + p->debug_type = cg_debug_type_for_proc(m, p->type); + TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); + gb_unused(params); + p->proto = tb_function_get_prototype(p->func); + + p->symbol = cast(TB_Symbol *)p->func; cgValue proc_value = cg_value(p->symbol, p->type); -- cgit v1.2.3 From 55733171c19aa53aebbe343d7541c3c5a1597c46 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 17 Jul 2023 23:16:50 +0100 Subject: Planning for multi-valued expressions in the tilde backend --- src/tilde_backend.cpp | 13 +++++++++++++ src/tilde_backend.hpp | 9 +++++++++ src/tilde_expr.cpp | 4 ++++ src/tilde_proc.cpp | 9 ++++----- src/tilde_stmt.cpp | 15 +++++++++++++++ 5 files changed, 45 insertions(+), 5 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 00e665b62..97f2dcccd 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -118,7 +118,20 @@ gb_internal cgValue cg_lvalue_addr(TB_Node *node, Type *type) { return v; } +gb_internal cgValue cg_value_multi(cgValueMultiNodes *multi_nodes, Type *type) { + GB_ASSERT(type->kind == Type_Tuple); + GB_ASSERT(multi_nodes != nullptr); + GB_ASSERT(type->Tuple.variables.count > 1); + GB_ASSERT(multi_nodes->nodes.count == type->Tuple.variables.count); + cgValue v = {}; + v.kind = cgValue_Multi; + v.type = type; + v.multi_nodes = multi_nodes; + return v; +} + gb_internal cgAddr cg_addr(cgValue const &value) { + GB_ASSERT(value.kind != cgValue_Multi); cgAddr addr = {}; addr.kind = cgAddr_Default; addr.addr = value; diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 9e88cb4c7..54d84302d 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -34,6 +34,11 @@ enum cgValueKind : u32 { cgValue_Value, cgValue_Addr, cgValue_Symbol, + cgValue_Multi, +}; + +struct cgValueMultiNodes { + Slice nodes; }; struct cgValue { @@ -42,6 +47,7 @@ struct cgValue { union { TB_Symbol *symbol; TB_Node * node; + cgValueMultiNodes *multi_nodes; }; }; @@ -132,6 +138,9 @@ struct cgProcedure { TB_FunctionPrototype *proto; TB_Symbol *symbol; + // includes parameters, pointers to return values, and context ptr + Slice param_nodes; + Entity * entity; cgModule *module; String name; diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 4e43089b2..473baf763 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,4 +1,5 @@ gb_internal cgValue cg_flatten_value(cgProcedure *p, cgValue value) { + GB_ASSERT(value.kind != cgValue_Multi); if (value.kind == cgValue_Symbol) { GB_ASSERT(is_type_internally_pointer_like(value.type)); value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); @@ -152,6 +153,9 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) case cgValue_Symbol: GB_PANIC("should be handled above"); break; + case cgValue_Multi: + GB_PANIC("cannot transmute multiple values at once"); + break; } return value; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 078c2ef9c..d08f611fc 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -333,7 +333,7 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); - gb_unused(params); + p->param_nodes = {params, cast(isize)out_param_count}; p->proto = tb_function_get_prototype(p->func); p->symbol = cast(TB_Symbol *)p->func; @@ -387,7 +387,7 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); - gb_unused(params); + p->param_nodes = {params, cast(isize)out_param_count}; p->proto = tb_function_get_prototype(p->func); @@ -420,12 +420,11 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { continue; } - if (param_index >= p->proto->param_count) { + if (param_index >= p->param_nodes.count) { break; } - // TB_Node *ptr = tb_inst_param_addr(p->func, param_index); - TB_Node *param = tb_inst_param(p->func, param_index++); + TB_Node *param = p->param_nodes[param_index++]; TB_Node *ptr = tb_inst_local(p->func, cast(TB_CharUnits)type_size_of(e->type), cast(TB_CharUnits)type_align_of(e->type)); TB_DataType dt = cg_data_type(e->type); tb_inst_store(p->func, dt, ptr, param, cast(TB_CharUnits)type_align_of(e->type), false); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index afc915115..6680277ed 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -10,6 +10,9 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol case cgValue_Addr: GB_PANIC("NOT POSSIBLE - Cannot load an lvalue to begin with"); break; + case cgValue_Multi: + GB_PANIC("NOT POSSIBLE - Cannot load multiple values at once"); + break; case cgValue_Symbol: return cg_lvalue_addr(tb_inst_get_symbol_address(p->func, ptr.symbol), type); } @@ -27,6 +30,9 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol case cgValue_Addr: the_ptr = tb_inst_load(p->func, TB_TYPE_PTR, ptr.node, alignment, is_volatile); break; + case cgValue_Multi: + GB_PANIC("NOT POSSIBLE - Cannot load multiple values at once"); + break; case cgValue_Symbol: the_ptr = tb_inst_get_symbol_address(p->func, ptr.symbol); break; @@ -35,6 +41,8 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol } gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile) { + GB_ASSERT_MSG(dst.kind != cgValue_Multi, "cannot store to multiple values at once"); + if (dst.kind == cgValue_Addr) { dst = cg_emit_load(p, dst, is_volatile); } else if (dst.kind == cgValue_Symbol) { @@ -130,6 +138,9 @@ gb_internal cgValue cg_address_from_load(cgProcedure *p, cgValue value) { case cgValue_Symbol: GB_PANIC("Symbol is an invalid use case for cg_address_from_load"); return {}; + case cgValue_Multi: + GB_PANIC("Multi is an invalid use case for cg_address_from_load"); + break; } GB_PANIC("Invalid cgValue for cg_address_from_load"); return {}; @@ -143,6 +154,8 @@ gb_internal bool cg_addr_is_empty(cgAddr const &addr) { return addr.addr.node == nullptr; case cgValue_Symbol: return addr.addr.symbol == nullptr; + case cgValue_Multi: + return addr.addr.multi_nodes == nullptr; } return true; } @@ -670,6 +683,8 @@ gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgVal break; case cgValue_Addr: return cg_value(value.node, alloc_type_pointer(value.type)); + case cgValue_Multi: + GB_PANIC("cgValue_Multi not allowed"); } cgAddr res = cg_add_local(p, value.type, nullptr, false); -- cgit v1.2.3 From 4d8d3919c0cf0610e523c8bd13f8ffeaef56d1e4 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 18 Jul 2023 13:16:35 +0100 Subject: Update tilde; procedure type determination from debug types --- src/tilde/tb.h | 2 + src/tilde/tb.lib | Bin 4113018 -> 4141318 bytes src/tilde_backend.cpp | 2 + src/tilde_backend.hpp | 6 +- src/tilde_debug.cpp | 33 +++--- src/tilde_proc.cpp | 275 +++----------------------------------------------- 6 files changed, 40 insertions(+), 278 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 4fb5d30ef..e240966c6 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -818,6 +818,7 @@ TB_API TB_DebugType* tb_debug_get_integer(TB_Module* m, bool is_signed, int bits TB_API TB_DebugType* tb_debug_get_float(TB_Module* m, TB_FloatFormat fmt); TB_API TB_DebugType* tb_debug_create_ptr(TB_Module* m, TB_DebugType* base); TB_API TB_DebugType* tb_debug_create_array(TB_Module* m, TB_DebugType* base, size_t count); +TB_API TB_DebugType* tb_debug_create_alias(TB_Module* m, TB_DebugType* base, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, ptrdiff_t len, const char* name, TB_CharUnits offset); @@ -883,6 +884,7 @@ TB_API const char* tb_symbol_get_name(TB_Symbol* s); // // returns the parameters TB_API TB_Node** tb_function_set_prototype_from_dbg(TB_Function* f, TB_DebugType* dbg, TB_Arena* arena, size_t* out_param_count); +TB_API TB_FunctionPrototype* tb_prototype_from_dbg(TB_Module* m, TB_DebugType* dbg); // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources TB_API void tb_function_set_prototype(TB_Function* f, TB_FunctionPrototype* p, TB_Arena* arena); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index b52ce4c55..60b197014 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 97f2dcccd..9c4b9b9a2 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -411,6 +411,7 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->debug_type_map); map_init(&m->proc_debug_type_map); + map_init(&m->proc_proto_map); for_array(id, global_files) { @@ -429,6 +430,7 @@ gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->file_id_map); map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); + map_destroy(&m->proc_proto_map); tb_module_destroy(m->mod); } diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 54d84302d..f84a6feae 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -8,8 +8,7 @@ #include "tilde/tb.h" #define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } -// #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } -#define TB_TYPE_I128 TB_TYPE_INTN(64) +#define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } #define TB_TYPE_INT TB_TYPE_INTN(cast(u16)(8*build_context.int_size)) #define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)(8*build_context.ptr_size)) @@ -191,6 +190,9 @@ struct cgModule { PtrMap debug_type_map; PtrMap proc_debug_type_map; // not pointer to + RecursiveMutex proc_proto_mutex; + PtrMap proc_proto_map; + PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) std::atomic nested_type_name_guid; diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index 21e3a52ed..e3b45ff1b 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -185,13 +185,13 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { case Basic_u32: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_i64: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u64: return tb_debug_get_integer(m->mod, is_signed, bits); - case Basic_i128: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); - case Basic_u128: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_i128: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u128: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_rune: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_f16: return tb_debug_get_integer(m->mod, false, bits); - case Basic_f32: return tb_debug_get_float(m->mod, TB_FLT_32); - case Basic_f64: return tb_debug_get_float(m->mod,TB_FLT_64); + case Basic_f32: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64: return tb_debug_get_float(m->mod, TB_FLT_64); case Basic_complex32: case Basic_complex64: @@ -263,7 +263,7 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { tb_debug_record_end(record, size, align); return record; } - case Basic_typeid: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_typeid: return tb_debug_get_integer(m->mod, false, bits); case Basic_i16le: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u16le: return tb_debug_get_integer(m->mod, is_signed, bits); @@ -271,23 +271,23 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { case Basic_u32le: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_i64le: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u64le: return tb_debug_get_integer(m->mod, is_signed, bits); - case Basic_i128le: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); - case Basic_u128le: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_i128le: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u128le: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_i16be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u16be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_i32be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u32be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_i64be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_u64be: return tb_debug_get_integer(m->mod, is_signed, bits); - case Basic_i128be: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); - case Basic_u128be: return tb_debug_get_integer(m->mod, is_signed, 64/*bits*/); + case Basic_i128be: return tb_debug_get_integer(m->mod, is_signed, bits); + case Basic_u128be: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_f16le: return tb_debug_get_integer(m->mod, false, bits); - case Basic_f32le: return tb_debug_get_float(m->mod, TB_FLT_32); - case Basic_f64le: return tb_debug_get_float(m->mod,TB_FLT_64); + case Basic_f32le: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64le: return tb_debug_get_float(m->mod, TB_FLT_64); case Basic_f16be: return tb_debug_get_integer(m->mod, false, bits); - case Basic_f32be: return tb_debug_get_float(m->mod, TB_FLT_32); - case Basic_f64be: return tb_debug_get_float(m->mod,TB_FLT_64); + case Basic_f32be: return tb_debug_get_float(m->mod, TB_FLT_32); + case Basic_f64be: return tb_debug_get_float(m->mod, TB_FLT_64); } break; case Type_Generic: @@ -350,8 +350,9 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { } } - if (pt->results) { + if (pt->result_count > 0) { if (is_odin_cc) { + // Split returns param_count += pt->result_count-1; return_count = 1; } else { @@ -392,8 +393,10 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { } } - if (pt->results) { + if (pt->result_count) { + GB_ASSERT(pt->results); if (is_odin_cc) { + // Split Returns for (isize i = 0; i < pt->results->Tuple.variables.count-1; i++) { Entity *e = pt->results->Tuple.variables[i]; GB_ASSERT(e->kind == Entity_Variable); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index d08f611fc..2862f1345 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1,260 +1,21 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Type *type) { - // TODO(bill): cache the procedure type generation - GB_ASSERT(build_context.metrics.os == TargetOs_windows); - - GB_ASSERT(type != nullptr); - type = base_type(type); - GB_ASSERT(type->kind == Type_Proc); - TypeProc *pt = &type->Proc; - - auto params = array_make(heap_allocator(), 0, pt->param_count); - if (pt->params) for (Entity *e : pt->params->Tuple.variables) { - TB_PrototypeParam param = {}; - - Type *t = core_type(e->type); - i64 sz = type_size_of(t); - switch (t->kind) { - case Type_Basic: - switch (t->Basic.kind) { - case Basic_bool: - case Basic_b8: - case Basic_b16: - case Basic_b32: - case Basic_b64: - case Basic_i8: - case Basic_u8: - case Basic_i16: - case Basic_u16: - case Basic_i32: - case Basic_u32: - case Basic_i64: - case Basic_u64: - case Basic_i128: - case Basic_u128: - case Basic_rune: - case Basic_int: - case Basic_uint: - case Basic_uintptr: - param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - case Basic_f16: param.dt = TB_TYPE_F16; break; - case Basic_f32: param.dt = TB_TYPE_F32; break; - case Basic_f64: param.dt = TB_TYPE_F64; break; - - case Basic_complex32: - case Basic_complex64: - case Basic_complex128: - case Basic_quaternion64: - case Basic_quaternion128: - case Basic_quaternion256: - param.dt = TB_TYPE_PTR; - break; - + GB_ASSERT(is_type_proc(type)); + mutex_lock(&m->proc_proto_mutex); + defer (mutex_unlock(&m->proc_proto_mutex)); - case Basic_rawptr: - param.dt = TB_TYPE_PTR; - break; - case Basic_string: // ^u8 + int - param.dt = TB_TYPE_PTR; - break; - case Basic_cstring: // ^u8 - param.dt = TB_TYPE_PTR; - break; - case Basic_any: // rawptr + ^Type_Info - param.dt = TB_TYPE_PTR; - break; - - case Basic_typeid: - param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - // Endian Specific Types - case Basic_i16le: - case Basic_u16le: - case Basic_i32le: - case Basic_u32le: - case Basic_i64le: - case Basic_u64le: - case Basic_i128le: - case Basic_u128le: - case Basic_i16be: - case Basic_u16be: - case Basic_i32be: - case Basic_u32be: - case Basic_i64be: - case Basic_u64be: - case Basic_i128be: - case Basic_u128be: - param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - case Basic_f16le: param.dt = TB_TYPE_F16; break; - case Basic_f32le: param.dt = TB_TYPE_F32; break; - case Basic_f64le: param.dt = TB_TYPE_F64; break; - - case Basic_f16be: param.dt = TB_TYPE_F16; break; - case Basic_f32be: param.dt = TB_TYPE_F32; break; - case Basic_f64be: param.dt = TB_TYPE_F64; break; - } - - case Type_Pointer: - case Type_MultiPointer: - case Type_Proc: - param.dt = TB_TYPE_PTR; - break; - - default: - switch (sz) { - case 1: param.dt = TB_TYPE_I8; break; - case 2: param.dt = TB_TYPE_I16; break; - case 4: param.dt = TB_TYPE_I32; break; - case 8: param.dt = TB_TYPE_I64; break; - default: - param.dt = TB_TYPE_PTR; - break; - } - } - - if (param.dt.raw != 0) { - if (is_blank_ident(e->token)) { - param.name = alloc_cstring(temporary_allocator(), e->token.string); - } - param.debug_type = cg_debug_type(m, e->type); - array_add(¶ms, param); - } + if (type->kind == Type_Named) { + type = base_type(type); } - - auto results = array_make(heap_allocator(), 0, 1); - - Type *result_type = reduce_tuple_to_single_type(pt->results); - - if (result_type) { - bool return_is_tuple = result_type->kind == Type_Tuple && is_calling_convention_odin(pt->calling_convention); - - if (return_is_tuple) { - for (isize i = 0; i < result_type->Tuple.variables.count-1; i++) { - Entity *e = result_type->Tuple.variables[i]; - TB_PrototypeParam param = {}; - param.dt = TB_TYPE_PTR; - param.debug_type = cg_debug_type(m, alloc_type_pointer(e->type)); - array_add(¶ms, param); - } - - result_type = result_type->Tuple.variables[result_type->Tuple.variables.count-1]->type; - } - - Type *rt = core_type(result_type); - i64 sz = type_size_of(rt); - - TB_PrototypeParam result = {}; - - switch (rt->kind) { - case Type_Basic: - switch (rt->Basic.kind) { - case Basic_bool: - case Basic_b8: - case Basic_b16: - case Basic_b32: - case Basic_b64: - case Basic_i8: - case Basic_u8: - case Basic_i16: - case Basic_u16: - case Basic_i32: - case Basic_u32: - case Basic_i64: - case Basic_u64: - case Basic_i128: - case Basic_u128: - case Basic_rune: - case Basic_int: - case Basic_uint: - case Basic_uintptr: - result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - case Basic_f16: result.dt = TB_TYPE_I16; break; - case Basic_f32: result.dt = TB_TYPE_F32; break; - case Basic_f64: result.dt = TB_TYPE_F64; break; - - case Basic_rawptr: - result.dt = TB_TYPE_PTR; - break; - case Basic_cstring: // ^u8 - result.dt = TB_TYPE_PTR; - break; - - case Basic_typeid: - result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - // Endian Specific Types - case Basic_i16le: - case Basic_u16le: - case Basic_i32le: - case Basic_u32le: - case Basic_i64le: - case Basic_u64le: - case Basic_i128le: - case Basic_u128le: - case Basic_i16be: - case Basic_u16be: - case Basic_i32be: - case Basic_u32be: - case Basic_i64be: - case Basic_u64be: - case Basic_i128be: - case Basic_u128be: - result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); - break; - - case Basic_f16le: result.dt = TB_TYPE_I16; break; - case Basic_f32le: result.dt = TB_TYPE_F32; break; - case Basic_f64le: result.dt = TB_TYPE_F64; break; - - case Basic_f16be: result.dt = TB_TYPE_I16; break; - case Basic_f32be: result.dt = TB_TYPE_F32; break; - case Basic_f64be: result.dt = TB_TYPE_F64; break; - } - - case Type_Pointer: - case Type_MultiPointer: - case Type_Proc: - result.dt = TB_TYPE_PTR; - break; - - default: - switch (sz) { - case 1: result.dt = TB_TYPE_I8; break; - case 2: result.dt = TB_TYPE_I16; break; - case 4: result.dt = TB_TYPE_I32; break; - case 8: result.dt = TB_TYPE_I64; break; - } - } - - if (result.dt.raw != 0) { - result.debug_type = cg_debug_type(m, result_type); - array_add(&results, result); - } else { - result.debug_type = cg_debug_type(m, alloc_type_pointer(result_type)); - result.dt = TB_TYPE_PTR; - - array_resize(¶ms, params.count+1); - array_copy(¶ms, params, 1); - params[0] = result; - } + TB_FunctionPrototype **found = map_get(&m->proc_proto_map, type); + if (found) { + return *found; } - if (pt->calling_convention == ProcCC_Odin) { - TB_PrototypeParam param = {}; - param.dt = TB_TYPE_PTR; - param.debug_type = cg_debug_type(m, t_context_ptr); - param.name = "__.context_ptr"; - array_add(¶ms, param); - } + TB_DebugType *dbg = cg_debug_type_for_proc(m, type); + TB_FunctionPrototype *proto = tb_prototype_from_dbg(m->mod, dbg); - return tb_prototype_create(m->mod, TB_CDECL, params.count, params.data, results.count, results.data, pt->c_vararg); + map_set(&m->proc_proto_map, type, proto); + return proto; } gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body=false) { @@ -327,9 +88,6 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - // p->proto = cg_procedure_type_as_prototype(m, p->type); - // tb_function_set_prototype(p->func, p->proto, arena); - size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); @@ -382,8 +140,6 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - // p->proto = cg_procedure_type_as_prototype(m, p->type); - // tb_function_set_prototype(p->func, p->proto, arena); size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); @@ -425,16 +181,13 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { } TB_Node *param = p->param_nodes[param_index++]; - TB_Node *ptr = tb_inst_local(p->func, cast(TB_CharUnits)type_size_of(e->type), cast(TB_CharUnits)type_align_of(e->type)); - TB_DataType dt = cg_data_type(e->type); - tb_inst_store(p->func, dt, ptr, param, cast(TB_CharUnits)type_align_of(e->type), false); - cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); + cgValue local = cg_value(param, alloc_type_pointer(e->type)); if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only String name = e->token.string; TB_DebugType *debug_type = cg_debug_type(p->module, e->type); - tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + tb_node_append_attrib(param, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); } cgAddr addr = cg_addr(local); -- cgit v1.2.3 From c6593e8cdee3bbe3057be7a4728db3293265b663 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 18 Jul 2023 13:27:47 +0100 Subject: Mock out binary expressions and variable declarations --- src/tilde_expr.cpp | 182 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/tilde_proc.cpp | 3 +- src/tilde_stmt.cpp | 25 +++++++- 3 files changed, 206 insertions(+), 4 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 473baf763..33a1b5379 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -7,6 +7,19 @@ gb_internal cgValue cg_flatten_value(cgProcedure *p, cgValue value) { return value; } +gb_internal bool cg_is_expr_untyped_const(Ast *expr) { + auto const &tv = type_and_value_of_expr(expr); + if (is_type_untyped(tv.type)) { + return tv.value.kind != ExactValue_Invalid; + } + return false; +} +gb_internal cgValue cg_expr_untyped_const_to_typed(cgProcedure *p, Ast *expr, Type *t) { + GB_ASSERT(is_type_typed(t)); + auto const &tv = type_and_value_of_expr(expr); + return cg_const_value(p, t, tv.value); +} + gb_internal cgContextData *cg_push_context_onto_stack(cgProcedure *p, cgAddr ctx) { ctx.kind = cgAddr_Context; cgContextData *cd = array_add_and_get(&p->context_stack); @@ -909,7 +922,173 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { return {}; } +gb_internal cgValue cg_build_binary_expr(cgProcedure *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)) { + cgValue left = cg_build_expr(p, be->left); + cgValue right = cg_build_expr(p, be->right); + GB_PANIC("TODO(bill): cg_emit_arith_matrix"); + // return cg_emit_arith_matrix(p, be->op.kind, left, right, default_type(tv.type), false); + } + + + switch (be->op.kind) { + case Token_Add: + case Token_Sub: + case Token_Mul: + case Token_Quo: + case Token_Mod: + case Token_ModMod: + case Token_And: + case Token_Or: + case Token_Xor: + case Token_AndNot: { + Type *type = default_type(tv.type); + cgValue left = cg_build_expr(p, be->left); + cgValue right = cg_build_expr(p, be->right); + return cg_emit_arith(p, be->op.kind, left, right, type); + } + + case Token_Shl: + case Token_Shr: { + cgValue left, right; + Type *type = default_type(tv.type); + left = cg_build_expr(p, be->left); + + if (cg_is_expr_untyped_const(be->right)) { + // NOTE(bill): RHS shift operands can still be untyped + // Just bypass the standard cg_build_expr + right = cg_expr_untyped_const_to_typed(p, be->right, type); + } else { + right = cg_build_expr(p, be->right); + } + return cg_emit_arith(p, be->op.kind, left, right, type); + } + + case Token_CmpEq: + case Token_NotEq: + GB_PANIC("TODO(bill): comparisons"); + // if (is_type_untyped_nil(be->right->tav.type)) { + // // `x == nil` or `x != nil` + // cgValue left = cg_build_expr(p, be->left); + // cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, left); + // Type *type = default_type(tv.type); + // return cg_emit_conv(p, cmp, type); + // } else if (is_type_untyped_nil(be->left->tav.type)) { + // // `nil == x` or `nil != x` + // cgValue right = cg_build_expr(p, be->right); + // cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, right); + // Type *type = default_type(tv.type); + // return cg_emit_conv(p, cmp, type); + // } else if (cg_is_empty_string_constant(be->right)) { + // // `x == ""` or `x != ""` + // cgValue s = cg_build_expr(p, be->left); + // s = cg_emit_conv(p, s, t_string); + // cgValue len = cg_string_len(p, s); + // cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); + // Type *type = default_type(tv.type); + // return cg_emit_conv(p, cmp, type); + // } else if (cg_is_empty_string_constant(be->left)) { + // // `"" == x` or `"" != x` + // cgValue s = cg_build_expr(p, be->right); + // s = cg_emit_conv(p, s, t_string); + // cgValue len = cg_string_len(p, s); + // cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); + // Type *type = default_type(tv.type); + // return cg_emit_conv(p, cmp, type); + // } + /*fallthrough*/ + case Token_Lt: + case Token_LtEq: + case Token_Gt: + case Token_GtEq: + { + cgValue left = {}; + cgValue right = {}; + + if (be->left->tav.mode == Addressing_Type) { + left = cg_typeid(p->module, be->left->tav.type); + } + if (be->right->tav.mode == Addressing_Type) { + right = cg_typeid(p->module, be->right->tav.type); + } + if (left.node == nullptr) left = cg_build_expr(p, be->left); + if (right.node == nullptr) right = cg_build_expr(p, be->right); + GB_PANIC("TODO(bill): cg_emit_comp"); + // cgValue cmp = cg_emit_comp(p, be->op.kind, left, right); + // Type *type = default_type(tv.type); + // return cg_emit_conv(p, cmp, type); + } + case Token_CmpAnd: + case Token_CmpOr: + GB_PANIC("TODO(bill): cg_emit_logical_binary_expr"); + // return cg_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); + + case Token_in: + case Token_not_in: + { + cgValue left = cg_build_expr(p, be->left); + cgValue right = cg_build_expr(p, be->right); + Type *rt = base_type(right.type); + if (is_type_pointer(rt)) { + right = cg_emit_load(p, right); + rt = base_type(type_deref(rt)); + } + + switch (rt->kind) { + case Type_Map: + { + GB_PANIC("TODO(bill): in/not_in for maps"); + // cgValue map_ptr = cg_address_from_load_or_generate_local(p, right); + // cgValue key = left; + // cgValue ptr = cg_internal_dynamic_map_get_ptr(p, map_ptr, key); + // if (be->op.kind == Token_in) { + // return cg_emit_conv(p, cg_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool); + // } else { + // return cg_emit_conv(p, cg_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool); + // } + } + break; + case Type_BitSet: + { + Type *key_type = rt->BitSet.elem; + GB_ASSERT(are_types_identical(left.type, key_type)); + + Type *it = bit_set_to_int(rt); + left = cg_emit_conv(p, left, it); + if (is_type_different_to_arch_endianness(it)) { + left = cg_emit_byte_swap(p, left, integer_endian_type_to_platform_type(it)); + } + + cgValue lower = cg_const_value(p, left.type, exact_value_i64(rt->BitSet.lower)); + cgValue key = cg_emit_arith(p, Token_Sub, left, lower, left.type); + cgValue bit = cg_emit_arith(p, Token_Shl, cg_const_int(p, left.type, 1), key, left.type); + bit = cg_emit_conv(p, bit, it); + + cgValue old_value = cg_emit_transmute(p, right, it); + cgValue new_value = cg_emit_arith(p, Token_And, old_value, bit, it); + + GB_PANIC("TODO(bill): cg_emit_comp"); + // TokenKind op = (be->op.kind == Token_in) ? Token_NotEq : Token_CmpEq; + // return cg_emit_conv(p, cg_emit_comp(p, op, new_value, cg_const_int(p, new_value.type, 0)), t_bool); + } + break; + default: + GB_PANIC("Invalid 'in' type"); + } + break; + } + break; + default: + GB_PANIC("Invalid binary expression"); + break; + } + return {}; +} gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); @@ -1130,6 +1309,9 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_addr_load(p, cg_build_addr(p, expr)); case_end; + case_ast_node(ie, BinaryExpr, expr); + return cg_build_binary_expr(p, expr); + case_end; } GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 2862f1345..85219ae44 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -242,7 +242,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { if (tb_inst_get_control(p->func)) { tb_inst_ret(p->func, 0, nullptr); } - if (p->name == "main") { + // if (p->name == "main") { + if (p->name == "bug.main") { TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 6680277ed..cc15c2abc 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -966,13 +966,32 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { for (Ast *name : vd->names) { if (!is_blank_ident(name)) { Entity *e = entity_of_node(name); - bool zero_init = true; - cgAddr addr = cg_add_local(p, e->type, e, zero_init); + cgAddr addr = cg_add_local(p, e->type, e, true); gb_unused(addr); } } } else { - GB_PANIC("TODO multiple variables"); + auto lvals = slice_make(temporary_allocator(), vd->names.count); + auto inits = array_make(temporary_allocator(), 0, lvals.count); + for (Ast *rhs : values) { + rhs = unparen_expr(rhs); + cgValue init = cg_build_expr(p, rhs); + cg_append_tuple_values(p, &inits, init); + } + + for_array(i, vd->names) { + Ast *name = vd->names[i]; + if (!is_blank_ident(name)) { + Entity *e = entity_of_node(name); + lvals[i] = cg_add_local(p, e->type, e, true); + } + } + GB_ASSERT(lvals.count == inits.count); + for_array(i, inits) { + cgAddr lval = lvals[i]; + cgValue init = inits[i]; + cg_addr_store(p, lval, init); + } } case_end; -- cgit v1.2.3 From 3535d16c3a9f2a16b420f34777cbbc56ccadfd5d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 18 Jul 2023 18:58:56 +0100 Subject: Implement Ternary If Expression --- src/tilde/tb.lib | Bin 4141318 -> 4141318 bytes src/tilde_expr.cpp | 106 ++++++++++++++++++++++++++++++++++++++++++++++++++--- src/tilde_proc.cpp | 12 +++--- 3 files changed, 108 insertions(+), 10 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 60b197014..84dba790b 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 63b1feb6e..351ee7b45 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -799,6 +799,9 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { } TB_DataType st = cg_data_type(src); + if (value.kind == cgValue_Value && !TB_IS_VOID_TYPE(value.node->dt)) { + st = value.node->dt; + } TB_DataType dt = cg_data_type(t); if (is_type_integer(src) && is_type_integer(dst)) { @@ -1751,10 +1754,9 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { } if (left.node == nullptr) left = cg_build_expr(p, be->left); if (right.node == nullptr) right = cg_build_expr(p, be->right); - GB_PANIC("TODO(bill): cg_emit_comp"); - // cgValue cmp = cg_emit_comp(p, be->op.kind, left, right); - // Type *type = default_type(tv.type); - // return cg_emit_conv(p, cmp, type); + cgValue cmp = cg_emit_comp(p, be->op.kind, left, right); + Type *type = default_type(tv.type); + return cg_emit_conv(p, cmp, type); } case Token_CmpAnd: @@ -1824,6 +1826,60 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { return {}; } +gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block, TB_Node *false_block) { + cond = unparen_expr(cond); + + GB_ASSERT(cond != nullptr); + GB_ASSERT(true_block != nullptr); + GB_ASSERT(false_block != nullptr); + + // Use to signal not to do compile time short circuit for consts + cgValue no_comptime_short_circuit = {}; + + switch (cond->kind) { + case_ast_node(ue, UnaryExpr, cond); + if (ue->op.kind == Token_Not) { + cgValue cond_val = cg_build_cond(p, ue->expr, false_block, true_block); + return cond_val; + // if (cond_val.value && LLVMIsConstant(cond_val.value)) { + // return cg_const_bool(p->module, cond_val.type, LLVMConstIntGetZExtValue(cond_val.value) == 0); + // } + // return no_comptime_short_circuit; + } + case_end; + + case_ast_node(be, BinaryExpr, cond); + if (be->op.kind == Token_CmpAnd) { + TB_Node *block = tb_inst_region(p->func); + tb_inst_set_region_name(block, -1, "cmp.and"); + cg_build_cond(p, be->left, block, false_block); + tb_inst_set_control(p->func, block); + cg_build_cond(p, be->right, true_block, false_block); + return no_comptime_short_circuit; + } else if (be->op.kind == Token_CmpOr) { + TB_Node *block = tb_inst_region(p->func); + tb_inst_set_region_name(block, -1, "cmp.or"); + cg_build_cond(p, be->left, true_block, block); + tb_inst_set_control(p->func, block); + cg_build_cond(p, be->right, true_block, false_block); + return no_comptime_short_circuit; + } + case_end; + } + + cgValue v = {}; + if (cg_is_expr_untyped_const(cond)) { + v = cg_expr_untyped_const_to_typed(p, cond, t_llvm_bool); + } else { + v = cg_build_expr(p, cond); + } + + v = cg_emit_conv(p, v, t_llvm_bool); + + tb_inst_if(p->func, v.node, true_block, false_block); + + return v; +} gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { @@ -1994,7 +2050,47 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(te, TernaryIfExpr, expr); - GB_PANIC("TODO(bill): TernaryIfExpr"); + cgValue incoming_values[2] = {}; + TB_Node *incoming_regions[2] = {}; + + TB_Node *then = tb_inst_region(p->func); + TB_Node *done = tb_inst_region(p->func); + TB_Node *else_ = tb_inst_region(p->func); + tb_inst_set_region_name(then, -1, "if.then"); + tb_inst_set_region_name(done, -1, "if.done"); + tb_inst_set_region_name(else_, -1, "if.else"); + + cg_build_cond(p, te->cond, then, else_); + tb_inst_set_control(p->func, then); + + Type *type = default_type(type_of_expr(expr)); + + incoming_values[0] = cg_emit_conv(p, cg_build_expr(p, te->x), type); + incoming_regions[0] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, else_); + + incoming_values[1] = cg_emit_conv(p, cg_build_expr(p, te->y), type); + incoming_regions[1] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + GB_ASSERT(incoming_values[0].kind == cgValue_Value || + incoming_values[0].kind == cgValue_Addr); + GB_ASSERT(incoming_values[0].kind == incoming_values[1].kind); + cgValue res = {}; + res.kind = incoming_values[0].kind; + res.type = type; + TB_DataType dt = cg_data_type(type); + if (res.kind == cgValue_Addr) { + dt = TB_TYPE_PTR; + } + res.node = tb_inst_incomplete_phi(p->func, dt, done, 2); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[0], incoming_values[0].node); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[1], incoming_values[1].node); + return res; case_end; case_ast_node(te, TernaryWhenExpr, expr); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 85219ae44..b3ab0b778 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -244,11 +244,13 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } // if (p->name == "main") { if (p->name == "bug.main") { - TB_Arena *arena = tb_default_arena(); - defer (arena->free(arena)); - TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - defer (tb_funcopt_exit(opt)); - tb_funcopt_print(opt); + // TB_Arena *arena = tb_default_arena(); + // defer (arena->free(arena)); + // TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + // defer (tb_funcopt_exit(opt)); + // tb_funcopt_print(opt); + + tb_function_print(p->func, tb_default_print_callback, stdout); } tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); } -- cgit v1.2.3 From 569397bd7eeb8db7aeff0033b3d8cb79af2c9893 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 11:39:37 +0100 Subject: Update TB --- src/tilde/tb.h | 5 +++-- src/tilde/tb.lib | Bin 4141318 -> 4146174 bytes src/tilde_expr.cpp | 7 ++++--- src/tilde_proc.cpp | 12 ++++++------ 4 files changed, 13 insertions(+), 11 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index e240966c6..3924bbe8e 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -33,8 +33,9 @@ // These are flags typedef enum TB_ArithmeticBehavior { - TB_ARITHMATIC_NSW = 1, - TB_ARITHMATIC_NUW = 2, + TB_ARITHMATIC_NONE = 0, + TB_ARITHMATIC_NSW = 1, + TB_ARITHMATIC_NUW = 2, } TB_ArithmeticBehavior; typedef enum TB_DebugFormat { diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 84dba790b..c42e02d98 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 351ee7b45..e754d473f 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1185,7 +1185,7 @@ handle_op:; } } - TB_ArithmeticBehavior arith_behavior = cast(TB_ArithmeticBehavior)50; + TB_ArithmeticBehavior arith_behavior = cast(TB_ArithmeticBehavior)0; Type *integral_type = type; if (is_type_simd_vector(integral_type)) { @@ -2065,13 +2065,13 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { Type *type = default_type(type_of_expr(expr)); - incoming_values[0] = cg_emit_conv(p, cg_build_expr(p, te->x), type); + incoming_values [0] = cg_emit_conv(p, cg_build_expr(p, te->x), type); incoming_regions[0] = tb_inst_get_control(p->func); tb_inst_goto(p->func, done); tb_inst_set_control(p->func, else_); - incoming_values[1] = cg_emit_conv(p, cg_build_expr(p, te->y), type); + incoming_values [1] = cg_emit_conv(p, cg_build_expr(p, te->y), type); incoming_regions[1] = tb_inst_get_control(p->func); tb_inst_goto(p->func, done); @@ -2080,6 +2080,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { GB_ASSERT(incoming_values[0].kind == cgValue_Value || incoming_values[0].kind == cgValue_Addr); GB_ASSERT(incoming_values[0].kind == incoming_values[1].kind); + cgValue res = {}; res.kind = incoming_values[0].kind; res.type = type; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index b3ab0b778..c925ee692 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -244,13 +244,13 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } // if (p->name == "main") { if (p->name == "bug.main") { - // TB_Arena *arena = tb_default_arena(); - // defer (arena->free(arena)); - // TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - // defer (tb_funcopt_exit(opt)); - // tb_funcopt_print(opt); + TB_Arena *arena = tb_default_arena(); + defer (arena->free(arena)); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + tb_funcopt_print(opt); - tb_function_print(p->func, tb_default_print_callback, stdout); + // tb_function_print(p->func, tb_default_print_callback, stdout); } tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); } -- cgit v1.2.3 From 32ac319525832794f3758daf3a08869deca30770 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 12:55:44 +0100 Subject: Implement if statements --- src/tilde_backend.hpp | 10 +++++++-- src/tilde_expr.cpp | 15 +++++-------- src/tilde_proc.cpp | 4 ++-- src/tilde_stmt.cpp | 58 +++++++++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 71 insertions(+), 16 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 8fc02e3fa..bed3fd6a7 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -203,7 +203,7 @@ struct cgModule { }; #ifndef ABI_PKG_NAME_SEPARATOR -#define ABI_PKG_NAME_SEPARATOR "." +#define ABI_PKG_NAME_SEPARATOR "@" #endif gb_global Entity *cg_global_type_info_data_entity = {}; @@ -271,4 +271,10 @@ gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t); gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, cgValue x); gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right); -gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgValue rhs, Type *type); \ No newline at end of file +gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgValue rhs, Type *type); + +gb_internal TB_Node *tb_inst_region_with_name(TB_Function *f, ptrdiff_t n, char const *name) { + TB_Node *region = tb_inst_region(f); + tb_inst_set_region_name(region, n, name); + return region; +} diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index e754d473f..61dabbb52 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1850,15 +1850,13 @@ gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block case_ast_node(be, BinaryExpr, cond); if (be->op.kind == Token_CmpAnd) { - TB_Node *block = tb_inst_region(p->func); - tb_inst_set_region_name(block, -1, "cmp.and"); + TB_Node *block = tb_inst_region_with_name(p->func, -1, "cmp_and"); cg_build_cond(p, be->left, block, false_block); tb_inst_set_control(p->func, block); cg_build_cond(p, be->right, true_block, false_block); return no_comptime_short_circuit; } else if (be->op.kind == Token_CmpOr) { - TB_Node *block = tb_inst_region(p->func); - tb_inst_set_region_name(block, -1, "cmp.or"); + TB_Node *block = tb_inst_region_with_name(p->func, -1, "cmp_or"); cg_build_cond(p, be->left, true_block, block); tb_inst_set_control(p->func, block); cg_build_cond(p, be->right, true_block, false_block); @@ -2053,12 +2051,9 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { cgValue incoming_values[2] = {}; TB_Node *incoming_regions[2] = {}; - TB_Node *then = tb_inst_region(p->func); - TB_Node *done = tb_inst_region(p->func); - TB_Node *else_ = tb_inst_region(p->func); - tb_inst_set_region_name(then, -1, "if.then"); - tb_inst_set_region_name(done, -1, "if.done"); - tb_inst_set_region_name(else_, -1, "if.else"); + TB_Node *then = tb_inst_region_with_name(p->func, -1, "if_then"); + TB_Node *done = tb_inst_region_with_name(p->func, -1, "if_done"); + TB_Node *else_ = tb_inst_region_with_name(p->func, -1, "if_else"); cg_build_cond(p, te->cond, then, else_); tb_inst_set_control(p->func, then); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index c925ee692..7f67f3a5c 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -243,7 +243,7 @@ gb_internal void cg_procedure_end(cgProcedure *p) { tb_inst_ret(p->func, 0, nullptr); } // if (p->name == "main") { - if (p->name == "bug.main") { + if (p->name == "bug" ABI_PKG_NAME_SEPARATOR "main") { TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); @@ -262,7 +262,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { cg_procedure_begin(p); defer (cg_procedure_end(p)); - if (p->name != "bug.main" && + if (p->name != "bug" ABI_PKG_NAME_SEPARATOR "main" && p->name != "main") { return; } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index ff4c007ea..bd856e542 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -852,6 +852,57 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return } } +gb_internal void cg_build_if_stmt(cgProcedure *p, Ast *node) { + ast_node(is, IfStmt, node); + cg_scope_open(p, is->scope); // Scope #1 + defer (cg_scope_close(p, cgDeferExit_Default, nullptr)); + + if (is->init != nullptr) { + TB_Node *init = tb_inst_region_with_name(p->func, -1, "if_init"); + tb_inst_goto(p->func, init); + tb_inst_set_control(p->func, init); + cg_build_stmt(p, is->init); + } + + TB_Node *then = tb_inst_region_with_name(p->func, -1, "if_then"); + TB_Node *done = tb_inst_region_with_name(p->func, -1, "if_done"); + TB_Node *else_ = done; + if (is->else_stmt != nullptr) { + else_ = tb_inst_region_with_name(p->func, -1, "if_else"); + } + + cgValue cond = cg_build_cond(p, is->cond, then, else_); + gb_unused(cond); + + if (is->label != nullptr) { + cgTargetList *tl = cg_push_target_list(p, is->label, done, nullptr, nullptr); + tl->is_block = true; + } + + // TODO(bill): should we do a constant check? + // Which philosophy are we following? + // - IR represents what the code represents (probably this) + // - IR represents what the code executes + + tb_inst_set_control(p->func, then); + + cg_build_stmt(p, is->body); + + tb_inst_goto(p->func, done); + + if (is->else_stmt != nullptr) { + tb_inst_set_control(p->func, else_); + + cg_scope_open(p, scope_of_node(is->else_stmt)); + cg_build_stmt(p, is->else_stmt); + cg_scope_close(p, cgDeferExit_Default, nullptr); + + tb_inst_goto(p->func, done); + } + + tb_inst_set_control(p->func, done); +} + gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { Ast *prev_stmt = p->curr_stmt; @@ -907,8 +958,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_ast_node(bs, BlockStmt, node); TB_Node *done = nullptr; if (bs->label != nullptr) { - done = tb_inst_region(p->func); - tb_inst_set_region_name(done, -1, "block.done"); + done = tb_inst_region_with_name(p->func, -1, "block_done"); cgTargetList *tl = cg_push_target_list(p, bs->label, done, nullptr, nullptr); tl->is_block = true; } @@ -1040,6 +1090,10 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { cg_build_return_stmt(p, rs->results); case_end; + case_ast_node(is, IfStmt, node); + cg_build_if_stmt(p, node); + case_end; + default: GB_PANIC("TODO cg_build_stmt %.*s", LIT(ast_strings[node->kind])); break; -- cgit v1.2.3 From b2edab193f26355020c5c13af432145712d8cf0f Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 14:19:01 +0100 Subject: Support branch statements `break`/`continue`/`fallthrough` --- src/tilde_proc.cpp | 14 ++++++++++++-- src/tilde_stmt.cpp | 8 ++------ 2 files changed, 14 insertions(+), 8 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 7f67f3a5c..f51435390 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -68,7 +68,7 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i p->children.allocator = a; // p->defer_stmts.allocator = a; // p->blocks.allocator = a; - // p->branch_blocks.allocator = a; + p->branch_blocks.allocator = a; p->context_stack.allocator = a; p->scope_stack.allocator = a; map_init(&p->variable_map); @@ -128,7 +128,7 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li p->children.allocator = a; // p->defer_stmts.allocator = a; // p->blocks.allocator = a; - // p->branch_blocks.allocator = a; + p->branch_blocks.allocator = a; p->scope_stack.allocator = a; p->context_stack.allocator = a; map_init(&p->variable_map); @@ -165,6 +165,16 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { return; } + + DeclInfo *decl = decl_info_of_entity(p->entity); + if (decl != nullptr) { + for_array(i, decl->labels) { + BlockLabel bl = decl->labels[i]; + cgBranchBlocks bb = {bl.label, nullptr, nullptr}; + array_add(&p->branch_blocks, bb); + } + } + GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; if (pt->params == nullptr) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 06be4f111..e94ac5d18 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1330,14 +1330,10 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { } } } - if (block != nullptr) { - cg_emit_defer_stmts(p, cgDeferExit_Branch, block); - } - + GB_ASSERT(block != nullptr); + cg_emit_defer_stmts(p, cgDeferExit_Branch, block); tb_inst_goto(p->func, block); - tb_inst_set_control(p->func, block); - tb_inst_unreachable(p->func); tb_inst_set_control(p->func, prev_block); case_end; -- cgit v1.2.3 From 9abf43b0d29abf3c560cd26081fb4adf0b38a5c6 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 15:24:07 +0100 Subject: Mock out `defer` handling logic (before handling `defer` statements) --- src/tilde_backend.hpp | 55 +++++++++++-------- src/tilde_expr.cpp | 10 ++-- src/tilde_proc.cpp | 28 +++++----- src/tilde_stmt.cpp | 146 +++++++++++++++++++++++++++++++++++++++++--------- 4 files changed, 177 insertions(+), 62 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index a203bd729..99a97a664 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -111,7 +111,7 @@ struct cgTargetList { TB_Node * fallthrough_; }; -struct cgBranchBlocks { +struct cgBranchRegions { Ast * label; TB_Node *break_; TB_Node *continue_; @@ -123,12 +123,37 @@ enum cgDeferExitKind { cgDeferExit_Branch, }; +enum cgDeferKind { + cgDefer_Node, + cgDefer_Proc, +}; + +struct cgDefer { + cgDeferKind kind; + isize scope_index; + isize context_stack_count; + TB_Node * control_region; + union { + Ast *stmt; + struct { + cgValue deferred; + Slice result_as_args; + } proc; + }; +}; + + struct cgContextData { cgAddr ctx; isize scope_index; isize uses; }; +struct cgControlRegion { + TB_Node *control_region; + isize scope_index; +}; + struct cgProcedure { u32 flags; u16 state_flags; @@ -162,15 +187,18 @@ struct cgProcedure { Ast *curr_stmt; - cgTargetList * target_list; - Array branch_blocks; + cgTargetList * target_list; + Array defer_stack; + Array scope_stack; + Array context_stack; + + Array control_regions; + Array branch_regions; Scope *curr_scope; i32 scope_index; bool in_multi_assignment; - Array scope_stack; - Array context_stack; PtrMap variable_map; }; @@ -275,20 +303,5 @@ gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgV gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); -gb_internal TB_Node *tb_inst_region_with_name(TB_Function *f, ptrdiff_t n, char const *name) { - #if 1 - if (n < 0) { - n = gb_strlen(name); - } - static std::atomic id; - - char *new_name = gb_alloc_array(temporary_allocator(), char, n+12); - n = -1 + gb_snprintf(new_name, n+11, "%.*s_%u", cast(int)n, name, 1+id.fetch_add(1)); - - name = new_name; - #endif - TB_Node *region = tb_inst_region(f); - tb_inst_set_region_name(region, n, name); - return region; -} +gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); \ No newline at end of file diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index e584d67e3..c2453b571 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1850,13 +1850,13 @@ gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block case_ast_node(be, BinaryExpr, cond); if (be->op.kind == Token_CmpAnd) { - TB_Node *block = tb_inst_region_with_name(p->func, -1, "cmp_and"); + TB_Node *block = cg_control_region(p, "cmp_and"); cg_build_cond(p, be->left, block, false_block); tb_inst_set_control(p->func, block); cg_build_cond(p, be->right, true_block, false_block); return no_comptime_short_circuit; } else if (be->op.kind == Token_CmpOr) { - TB_Node *block = tb_inst_region_with_name(p->func, -1, "cmp_or"); + TB_Node *block = cg_control_region(p, "cmp_or"); cg_build_cond(p, be->left, true_block, block); tb_inst_set_control(p->func, block); cg_build_cond(p, be->right, true_block, false_block); @@ -2048,9 +2048,9 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { cgValue incoming_values[2] = {}; TB_Node *incoming_regions[2] = {}; - TB_Node *then = tb_inst_region_with_name(p->func, -1, "if_then"); - TB_Node *done = tb_inst_region_with_name(p->func, -1, "if_done"); - TB_Node *else_ = tb_inst_region_with_name(p->func, -1, "if_else"); + TB_Node *then = cg_control_region(p, "if_then"); + TB_Node *done = cg_control_region(p, "if_done"); + TB_Node *else_ = cg_control_region(p, "if_else"); cg_build_cond(p, te->cond, then, else_); tb_inst_set_control(p->func, then); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index f51435390..2bb18a2de 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -66,13 +66,15 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i gbAllocator a = heap_allocator(); p->children.allocator = a; - // p->defer_stmts.allocator = a; - // p->blocks.allocator = a; - p->branch_blocks.allocator = a; - p->context_stack.allocator = a; + + p->defer_stack.allocator = a; p->scope_stack.allocator = a; + p->context_stack.allocator = a; + + p->control_regions.allocator = a; + p->branch_regions.allocator = a; + map_init(&p->variable_map); - // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; if (p->is_export) { @@ -126,13 +128,15 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li gbAllocator a = heap_allocator(); p->children.allocator = a; - // p->defer_stmts.allocator = a; - // p->blocks.allocator = a; - p->branch_blocks.allocator = a; - p->scope_stack.allocator = a; + + p->defer_stack.allocator = a; + p->scope_stack.allocator = a; p->context_stack.allocator = a; + + p->control_regions.allocator = a; + p->branch_regions.allocator = a; + map_init(&p->variable_map); - // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; @@ -170,8 +174,8 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (decl != nullptr) { for_array(i, decl->labels) { BlockLabel bl = decl->labels[i]; - cgBranchBlocks bb = {bl.label, nullptr, nullptr}; - array_add(&p->branch_blocks, bb); + cgBranchRegions bb = {bl.label, nullptr, nullptr}; + array_add(&p->branch_regions, bb); } } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 0f12ddf9c..85e719f29 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -6,6 +6,23 @@ gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region) { return false; } +gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name) { + TEMPORARY_ALLOCATOR_GUARD(); + + isize n = gb_strlen(name); + + char *new_name = gb_alloc_array(temporary_allocator(), char, n+12); + n = -1 + gb_snprintf(new_name, n+11, "%.*s_%u", cast(int)n, name, p->control_regions.count); + + TB_Node *region = tb_inst_region(p->func); + tb_inst_set_region_name(region, n, new_name); + + GB_ASSERT(p->scope_index >= 0); + array_add(&p->control_regions, cgControlRegion{region, p->scope_index}); + + return region; +} + gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile) { GB_ASSERT(is_type_pointer(ptr.type)); Type *type = type_deref(ptr.type); @@ -604,18 +621,18 @@ gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection -gb_internal cgBranchBlocks cg_lookup_branch_blocks(cgProcedure *p, Ast *ident) { +gb_internal cgBranchRegions cg_lookup_branch_regions(cgProcedure *p, Ast *ident) { GB_ASSERT(ident->kind == Ast_Ident); Entity *e = entity_of_node(ident); GB_ASSERT(e->kind == Entity_Label); - for (cgBranchBlocks const &b : p->branch_blocks) { + for (cgBranchRegions const &b : p->branch_regions) { if (b.label == e->Label.node) { return b; } } GB_PANIC("Unreachable"); - cgBranchBlocks empty = {}; + cgBranchRegions empty = {}; return empty; } @@ -630,7 +647,7 @@ gb_internal cgTargetList *cg_push_target_list(cgProcedure *p, Ast *label, TB_Nod if (label != nullptr) { // Set label blocks GB_ASSERT(label->kind == Ast_Label); - for (cgBranchBlocks &b : p->branch_blocks) { + for (cgBranchRegions &b : p->branch_regions) { GB_ASSERT(b.label != nullptr && label != nullptr); GB_ASSERT(b.label->kind == Ast_Label); if (b.label == label) { @@ -701,16 +718,97 @@ gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgVal } -gb_internal void cg_scope_open(cgProcedure *p, Scope *scope) { - // TODO(bill): cg_scope_open -} +gb_internal void cg_build_defer_stmt(cgProcedure *p, cgDefer const &d) { + TB_Node *curr_region = tb_inst_get_control(p->func); + if (curr_region == nullptr) { + return; + } + + // NOTE(bill): The prev block may defer injection before it's terminator + TB_Node *last_instr = nullptr; + if (curr_region->input_count) { + last_instr = *(curr_region->inputs + curr_region->input_count); + } + if (last_instr && TB_IS_NODE_TERMINATOR(last_instr->type)) { + // NOTE(bill): ReturnStmt defer stuff will be handled previously + return; + } -gb_internal void cg_scope_close(cgProcedure *p, cgDeferExitKind kind, TB_Node *control_region, bool pop_stack=true) { - // TODO(bill): cg_scope_close + isize prev_context_stack_count = p->context_stack.count; + GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity); + defer (p->context_stack.count = prev_context_stack_count); + p->context_stack.count = d.context_stack_count; + + TB_Node *b = cg_control_region(p, "defer"); + if (last_instr == nullptr) { + cg_emit_goto(p, b); + } + + tb_inst_set_control(p->func, b); + if (d.kind == cgDefer_Node) { + cg_build_stmt(p, d.stmt); + } else if (d.kind == cgDefer_Proc) { + cg_emit_call(p, d.proc.deferred, d.proc.result_as_args); + } } + gb_internal void cg_emit_defer_stmts(cgProcedure *p, cgDeferExitKind kind, TB_Node *control_region) { - // TODO(bill): cg_emit_defer_stmts + isize count = p->defer_stack.count; + isize i = count; + while (i --> 0) { + cgDefer const &d = p->defer_stack[i]; + + if (kind == cgDeferExit_Default) { + if (p->scope_index == d.scope_index && + d.scope_index > 0) { + cg_build_defer_stmt(p, d); + array_pop(&p->defer_stack); + continue; + } else { + break; + } + } else if (kind == cgDeferExit_Return) { + cg_build_defer_stmt(p, d); + } else if (kind == cgDeferExit_Branch) { + GB_PANIC("TODO(bill): cgDeferExit_Branch"); + GB_ASSERT(control_region != nullptr); + isize lower_limit = -1; + for (auto const &cr : p->control_regions) { + if (cr.control_region == control_region) { + lower_limit = cr.scope_index; + break; + } + } + GB_ASSERT(lower_limit >= 0); + if (lower_limit < d.scope_index) { + cg_build_defer_stmt(p, d); + } + } + } +} + +gb_internal void cg_scope_open(cgProcedure *p, Scope *scope) { + // TODO(bill): debug scope information + + p->scope_index += 1; + array_add(&p->scope_stack, scope); +} + +gb_internal void cg_scope_close(cgProcedure *p, cgDeferExitKind kind, TB_Node *control_region) { + cg_emit_defer_stmts(p, kind, control_region); + GB_ASSERT(p->scope_index > 0); + + while (p->context_stack.count > 0) { + auto *ctx = &p->context_stack[p->context_stack.count-1]; + if (ctx->scope_index < p->scope_index) { + break; + } + array_pop(&p->context_stack); + } + + p->scope_index -= 1; + array_pop(&p->scope_stack); } @@ -864,17 +962,17 @@ gb_internal void cg_build_if_stmt(cgProcedure *p, Ast *node) { defer (cg_scope_close(p, cgDeferExit_Default, nullptr)); if (is->init != nullptr) { - TB_Node *init = tb_inst_region_with_name(p->func, -1, "if_init"); + TB_Node *init = cg_control_region(p, "if_init"); cg_emit_goto(p, init); tb_inst_set_control(p->func, init); cg_build_stmt(p, is->init); } - TB_Node *then = tb_inst_region_with_name(p->func, -1, "if_then"); - TB_Node *done = tb_inst_region_with_name(p->func, -1, "if_done"); + TB_Node *then = cg_control_region(p, "if_then"); + TB_Node *done = cg_control_region(p, "if_done"); TB_Node *else_ = done; if (is->else_stmt != nullptr) { - else_ = tb_inst_region_with_name(p->func, -1, "if_else"); + else_ = cg_control_region(p, "if_else"); } cgValue cond = cg_build_cond(p, is->cond, then, else_); @@ -916,20 +1014,20 @@ gb_internal void cg_build_for_stmt(cgProcedure *p, Ast *node) { defer (cg_scope_close(p, cgDeferExit_Default, nullptr)); if (fs->init != nullptr) { - TB_Node *init = tb_inst_region_with_name(p->func, -1, "for_init"); + TB_Node *init = cg_control_region(p, "for_init"); cg_emit_goto(p, init); tb_inst_set_control(p->func, init); cg_build_stmt(p, fs->init); } - TB_Node *body = tb_inst_region_with_name(p->func, -1, "for_body"); - TB_Node *done = tb_inst_region_with_name(p->func, -1, "for_done"); + TB_Node *body = cg_control_region(p, "for_body"); + TB_Node *done = cg_control_region(p, "for_done"); TB_Node *loop = body; if (fs->cond != nullptr) { - loop = tb_inst_region_with_name(p->func, -1, "for_loop"); + loop = cg_control_region(p, "for_loop"); } TB_Node *post = loop; if (fs->post != nullptr) { - post = tb_inst_region_with_name(p->func, -1, "for_post"); + post = cg_control_region(p, "for_post"); } cg_emit_goto(p, loop); @@ -1018,7 +1116,7 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { tag = cg_const_bool(p, t_bool, true); } - TB_Node *done = tb_inst_region_with_name(p->func, -1, "switch_done"); + TB_Node *done = cg_control_region(p, "switch_done"); ast_node(body, BlockStmt, ss->body); @@ -1036,7 +1134,7 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { Ast *clause = body->stmts[i]; ast_node(cc, CaseClause, clause); - body_regions[i] = tb_inst_region_with_name(p->func, -1, cc->list.count == 0 ? "switch_default_body" : "switch_case_body"); + body_regions[i] = cg_control_region(p, cc->list.count == 0 ? "switch_default_body" : "switch_case_body"); body_scopes[i] = cc->scope; if (cc->list.count == 0) { default_block = body_regions[i]; @@ -1110,7 +1208,7 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { if (!is_trivial) for (Ast *expr : cc->list) { expr = unparen_expr(expr); - next_cond = tb_inst_region_with_name(p->func, -1, "switch_case_next"); + next_cond = cg_control_region(p, "switch_case_next"); cgValue cond = {}; if (is_ast_range(expr)) { @@ -1231,7 +1329,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_ast_node(bs, BlockStmt, node); TB_Node *done = nullptr; if (bs->label != nullptr) { - done = tb_inst_region_with_name(p->func, -1, "block_done"); + done = cg_control_region(p, "block_done"); cgTargetList *tl = cg_push_target_list(p, bs->label, done, nullptr, nullptr); tl->is_block = true; } @@ -1316,7 +1414,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { TB_Node *block = nullptr; if (bs->label != nullptr) { - cgBranchBlocks bb = cg_lookup_branch_blocks(p, bs->label); + cgBranchRegions bb = cg_lookup_branch_regions(p, bs->label); switch (bs->token.kind) { case Token_break: block = bb.break_; break; case Token_continue: block = bb.continue_; break; -- cgit v1.2.3 From fb041033528ca03d1a3240cd1e4712b0d57a959c Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 15:37:33 +0100 Subject: Add `defer` statements; add implicit `context` pointer to context stack --- src/tilde_proc.cpp | 27 +++++++++++++++++++++++---- src/tilde_stmt.cpp | 36 ++++++++++++++++++++++++++---------- 2 files changed, 49 insertions(+), 14 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 2bb18a2de..e2764bc50 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -181,11 +181,8 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; - if (pt->params == nullptr) { - return; - } int param_index = 0; - for (Entity *e : pt->params->Tuple.variables) { + if (pt->params != nullptr) for (Entity *e : pt->params->Tuple.variables) { if (e->kind != Entity_Variable) { continue; } @@ -247,6 +244,28 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } // } } + + if (p->type->Proc.calling_convention == ProcCC_Odin) { + // NOTE(bill): Push context on to stack from implicit parameter + + String name = str_lit("__.context_ptr"); + + Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false); + e->flags |= EntityFlag_NoAlias; + + TB_Node *param = p->param_nodes[p->param_nodes.count-1]; + param = tb_inst_load(p->func, TB_TYPE_PTR, param, cast(TB_CharUnits)build_context.ptr_size, false); + + cgValue local = cg_value(param, t_context_ptr); + cgAddr addr = cg_addr(local); + map_set(&p->variable_map, e, addr); + + + cgContextData *cd = array_add_and_get(&p->context_stack); + cd->ctx = addr; + cd->scope_index = -1; + cd->uses = +1; // make sure it has been used already + } } gb_internal void cg_procedure_end(cgProcedure *p) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 85e719f29..996506c84 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -725,14 +725,14 @@ gb_internal void cg_build_defer_stmt(cgProcedure *p, cgDefer const &d) { } // NOTE(bill): The prev block may defer injection before it's terminator - TB_Node *last_instr = nullptr; - if (curr_region->input_count) { - last_instr = *(curr_region->inputs + curr_region->input_count); - } - if (last_instr && TB_IS_NODE_TERMINATOR(last_instr->type)) { - // NOTE(bill): ReturnStmt defer stuff will be handled previously - return; - } + TB_Node *last_inst = nullptr; + // if (curr_region->input_count) { + // last_inst = *(curr_region->inputs + curr_region->input_count); + // } + // if (last_inst && TB_IS_NODE_TERMINATOR(last_inst->type)) { + // // NOTE(bill): ReturnStmt defer stuff will be handled previously + // return; + // } isize prev_context_stack_count = p->context_stack.count; GB_ASSERT(prev_context_stack_count <= p->context_stack.capacity); @@ -740,7 +740,7 @@ gb_internal void cg_build_defer_stmt(cgProcedure *p, cgDefer const &d) { p->context_stack.count = d.context_stack_count; TB_Node *b = cg_control_region(p, "defer"); - if (last_instr == nullptr) { + if (last_inst == nullptr) { cg_emit_goto(p, b); } @@ -771,7 +771,6 @@ gb_internal void cg_emit_defer_stmts(cgProcedure *p, cgDeferExitKind kind, TB_No } else if (kind == cgDeferExit_Return) { cg_build_defer_stmt(p, d); } else if (kind == cgDeferExit_Branch) { - GB_PANIC("TODO(bill): cgDeferExit_Branch"); GB_ASSERT(control_region != nullptr); isize lower_limit = -1; for (auto const &cr : p->control_regions) { @@ -1465,6 +1464,23 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { cg_build_switch_stmt(p, node); case_end; + case_ast_node(ds, DeferStmt, node); + Type *pt = base_type(p->type); + GB_ASSERT(pt->kind == Type_Proc); + if (pt->Proc.calling_convention == ProcCC_Odin) { + GB_ASSERT(p->context_stack.count != 0); + } + + cgDefer *d = array_add_and_get(&p->defer_stack); + d->kind = cgDefer_Node; + d->scope_index = p->scope_index; + d->context_stack_count = p->context_stack.count; + d->control_region = tb_inst_get_control(p->func); + GB_ASSERT(d->control_region != nullptr); + d->stmt = ds->stmt; + case_end; + + default: GB_PANIC("TODO cg_build_stmt %.*s", LIT(ast_strings[node->kind])); break; -- cgit v1.2.3 From e5f9458905f27b027403a5a0b94cc7762984a08e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 07:56:13 +0100 Subject: Update Tilde to get procedure passing rules --- src/tilde.cpp | 95 +++++--------------------------------- src/tilde.hpp | 3 ++ src/tilde/tb.h | 62 +++++++++++++++++-------- src/tilde/tb.lib | Bin 4158782 -> 4162738 bytes src/tilde_proc.cpp | 132 ++++++++++++++++++++++++++++++++++++++++++++++++----- src/tilde_stmt.cpp | 40 +++++++++++++++- 6 files changed, 217 insertions(+), 115 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 188f5e0d0..78aa3640d 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -1,5 +1,12 @@ #include "tilde.hpp" + +gb_global Slice global_tb_arenas; + +gb_internal TB_Arena *cg_arena(void) { + return global_tb_arenas[current_thread_index()]; +} + // returns TB_TYPE_VOID if not trivially possible gb_internal TB_DataType cg_data_type(Type *t) { GB_ASSERT(t != nullptr); @@ -672,6 +679,11 @@ gb_internal bool cg_generate_code(Checker *c) { CheckerInfo *info = &c->info; gb_unused(info); + global_tb_arenas = slice_make(permanent_allocator(), global_thread_pool.threads.count); + for_array(i, global_tb_arenas) { + global_tb_arenas[i] = tb_default_arena(); + } + cgModule *m = cg_module_create(c); defer (cg_module_destroy(m)); @@ -750,89 +762,6 @@ gb_internal bool cg_generate_code(Checker *c) { char const *path = "W:/Odin/tilde_main.obj"; GB_ASSERT(tb_export_buffer_to_file(export_buffer, path)); - - //////////////////////////////////////////////////////////////////////////////////// - - - // TB_Arena *arena = tb_default_arena(); - - // TB_Global *str = nullptr; - // { - // TB_Global *str_data = nullptr; - // { - // str_data = tb_global_create(m->mod, "csb$1", nullptr, TB_LINKAGE_PRIVATE); - // tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_data, 8, 1, 1); - // void *region = tb_global_add_region(m->mod, str_data, 0, 8); - // memcpy(region, "Hellope\x00", 8); - // } - - // str = tb_global_create(m->mod, "global$str", nullptr, TB_LINKAGE_PRIVATE); - // tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str, 16, 8, 2); - // tb_global_add_symbol_reloc(m->mod, str, 0, cast(TB_Symbol *)str_data); - // void *len = tb_global_add_region(m->mod, str, 8, 8); - // *cast(i64 *)len = 7; - // } - - // { - // TB_PrototypeParam printf_ret = {TB_TYPE_I32}; - // TB_PrototypeParam printf_params = {TB_TYPE_PTR}; - // TB_FunctionPrototype *printf_proto = tb_prototype_create(m->mod, TB_STDCALL, 1, &printf_params, 1, &printf_ret, true); - // TB_External *printf_proc = tb_extern_create(m->mod, "printf", TB_EXTERNAL_SO_LOCAL); - - // TB_PrototypeParam main_ret = {TB_TYPE_I32}; - // TB_FunctionPrototype *main_proto = tb_prototype_create(m->mod, TB_STDCALL, 0, nullptr, 1, &main_ret, false); - // TB_Function * p = tb_function_create(m->mod, "main", TB_LINKAGE_PUBLIC, TB_COMDAT_NONE); - // tb_function_set_prototype(p, main_proto, arena); - - - // auto str_ptr = tb_inst_get_symbol_address(p, cast(TB_Symbol *)str); - // auto str_data_ptr_ptr = tb_inst_member_access(p, str_ptr, 0); - // auto str_data_ptr = tb_inst_load(p, TB_TYPE_PTR, str_data_ptr_ptr, 1, false); - // auto str_len_ptr = tb_inst_member_access(p, str_ptr, 8); - // auto str_len = tb_inst_load(p, TB_TYPE_I64, str_len_ptr, 8, false); - - - // TB_Node *params[4] = {}; - // params[0] = tb_inst_cstring(p, "%.*s %s!\n"); - // params[1] = tb_inst_trunc(p, str_len, TB_TYPE_I32); - // params[2] = str_data_ptr; - // params[3] = tb_inst_cstring(p, "World"); - // TB_MultiOutput output = tb_inst_call(p, printf_proto, tb_inst_get_symbol_address(p, cast(TB_Symbol *)printf_proc), gb_count_of(params), params); - // gb_unused(output); - // TB_Node *printf_return_value = output.single; - - // TB_Node *zero = tb_inst_uint(p, TB_TYPE_I32, 0); - // TB_Node *one = tb_inst_uint(p, TB_TYPE_I32, 1); - - // TB_Node *prev_case = tb_inst_get_control(p); - - // TB_Node *true_case = tb_inst_region(p); - // TB_Node *false_case = tb_inst_region(p); - - // TB_Node *cond = tb_inst_cmp_igt(p, printf_return_value, zero, true); - // tb_inst_if(p, cond, true_case, false_case); - - // tb_inst_set_control(p, true_case); - // tb_inst_ret(p, 1, &zero); - - // tb_inst_set_control(p, false_case); - // tb_inst_ret(p, 1, &one); - - // tb_inst_set_control(p, prev_case); - - - // tb_module_compile_function(m->mod, p, TB_ISEL_FAST); - - // tb_function_print(p, tb_default_print_callback, stdout); - - - // TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; - // TB_ExportBuffer export_buffer = tb_module_object_export(m->mod, debug_format); - // defer (tb_export_buffer_free(export_buffer)); - - // char const *path = "W:/Odin/tilde_main.obj"; - // GB_ASSERT(tb_export_buffer_to_file(export_buffer, path)); - // } return true; } diff --git a/src/tilde.hpp b/src/tilde.hpp index 99a97a664..633eb63db 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -248,6 +248,9 @@ gb_global isize cg_global_type_info_member_offsets_index = 0; gb_global isize cg_global_type_info_member_usings_index = 0; gb_global isize cg_global_type_info_member_tags_index = 0; + +gb_internal TB_Arena *cg_arena(void); + gb_internal cgValue cg_value(TB_Global * g, Type *type); gb_internal cgValue cg_value(TB_External *e, Type *type); gb_internal cgValue cg_value(TB_Function *f, Type *type); diff --git a/src/tilde/tb.h b/src/tilde/tb.h index c2dc3922b..048fce598 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -210,9 +210,6 @@ typedef enum TB_NodeTypeEnum { // projection TB_PROJ, - // metadata - TB_KEEPALIVE, - TB_CALL, // normal call TB_SCALL, // system call @@ -640,14 +637,32 @@ TB_API void tb_module_set_tls_index(TB_Module* m, ptrdiff_t len, const char* nam TB_API void tb_module_layout_sections(TB_Module* m); //////////////////////////////// -// Exporter +// Compiled code introspection //////////////////////////////// +enum { TB_ASSEMBLY_CHUNK_CAP = 4*1024 - sizeof(size_t[2]) }; + +typedef struct TB_Assembly TB_Assembly; +struct TB_Assembly { + TB_Assembly* next; + + // nice chunk of text here + size_t length; + char data[]; +}; // this is where the machine code and other relevant pieces go. typedef struct TB_FunctionOutput TB_FunctionOutput; // returns NULL if it fails -TB_API TB_FunctionOutput* tb_module_compile_function(TB_Module* m, TB_Function* f, TB_ISelMode isel_mode); +TB_API TB_FunctionOutput* tb_module_compile_function(TB_Module* m, TB_Function* f, TB_ISelMode isel_mode, bool emit_asm); + +TB_API uint8_t* tb_output_get_code(TB_FunctionOutput* out, size_t* out_length); + +// returns NULL if no assembly was generated +TB_API TB_Assembly* tb_output_get_asm(TB_FunctionOutput* out); + +// this is relative to the start of the function (the start of the prologue) +TB_API TB_Safepoint* tb_safepoint_get(TB_Function* f, uint32_t relative_ip); //////////////////////////////// // Exporter @@ -780,6 +795,27 @@ struct TB_FunctionPrototype { // matching signatures. TB_API TB_FunctionPrototype* tb_prototype_create(TB_Module* m, TB_CallingConv cc, size_t param_count, const TB_PrototypeParam* params, size_t return_count, const TB_PrototypeParam* returns, bool has_varargs); +// same as tb_function_set_prototype except it will handle lowering from types like the TB_DebugType +// into the correct ABI and exposing sane looking nodes to the parameters. +// +// returns the parameters +TB_API TB_Node** tb_function_set_prototype_from_dbg(TB_Function* f, TB_DebugType* dbg, TB_Arena* arena, size_t* out_param_count); +TB_API TB_FunctionPrototype* tb_prototype_from_dbg(TB_Module* m, TB_DebugType* dbg); + +// used for ABI parameter passing +typedef enum { + // needs a direct value + TB_PASSING_DIRECT, + + // needs an address to the value + TB_PASSING_INDIRECT, + + // doesn't use this parameter + TB_PASSING_IGNORE, +} TB_PassingRule; + +TB_API TB_PassingRule tb_get_passing_rule_from_dbg(TB_Module* mod, TB_DebugType* param_type, bool is_return); + //////////////////////////////// // Globals //////////////////////////////// @@ -829,6 +865,8 @@ TB_API void tb_debug_record_end(TB_DebugType* type, TB_CharUnits size, TB_CharUn TB_API TB_DebugType* tb_debug_create_func(TB_Module* m, TB_CallingConv cc, size_t param_count, size_t return_count, bool has_varargs); +TB_API TB_DebugType* tb_debug_field_type(TB_DebugType* type); + // you'll need to fill these if you make a function TB_API TB_DebugType** tb_debug_func_params(TB_DebugType* type); TB_API TB_DebugType** tb_debug_func_returns(TB_DebugType* type); @@ -839,12 +877,6 @@ TB_API TB_DebugType** tb_debug_func_returns(TB_DebugType* type); // it is an index to the input #define TB_FOR_INPUT_IN_NODE(it, parent) for (TB_Node **it = parent->inputs, **__end = it + (parent)->input_count; it != __end; it++) -//////////////////////////////// -// Compiled code introspection -//////////////////////////////// -// this is relative to the start of the function (the start of the prologue) -TB_API TB_Safepoint* tb_safepoint_get(TB_Function* f, uint32_t relative_ip); - //////////////////////////////// // Symbols //////////////////////////////// @@ -879,13 +911,6 @@ TB_API void tb_symbol_set_name(TB_Symbol* s, ptrdiff_t len, const char* name); TB_API void tb_symbol_bind_ptr(TB_Symbol* s, void* ptr); TB_API const char* tb_symbol_get_name(TB_Symbol* s); -// same as tb_function_set_prototype except it will handle lowering from types like the TB_DebugType -// into the correct ABI and exposing sane looking nodes to the parameters. -// -// returns the parameters -TB_API TB_Node** tb_function_set_prototype_from_dbg(TB_Function* f, TB_DebugType* dbg, TB_Arena* arena, size_t* out_param_count); -TB_API TB_FunctionPrototype* tb_prototype_from_dbg(TB_Module* m, TB_DebugType* dbg); - // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources TB_API void tb_function_set_prototype(TB_Function* f, TB_FunctionPrototype* p, TB_Arena* arena); TB_API TB_FunctionPrototype* tb_function_get_prototype(TB_Function* f); @@ -903,7 +928,6 @@ TB_API void tb_inst_set_region_name(TB_Node* n, ptrdiff_t len, const char* name) TB_API void tb_inst_unreachable(TB_Function* f); TB_API void tb_inst_debugbreak(TB_Function* f); TB_API void tb_inst_trap(TB_Function* f); -TB_API void tb_inst_keep_alive(TB_Function* f, TB_Node* src); TB_API TB_Node* tb_inst_poison(TB_Function* f); TB_API TB_Node* tb_inst_param(TB_Function* f, int param_id); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 5a1cd67dd..b9b9dbd44 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index e2764bc50..e7210382c 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -87,12 +87,11 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } if (p->symbol == nullptr) { - TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); + TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); p->param_nodes = {params, cast(isize)out_param_count}; p->proto = tb_function_get_prototype(p->func); @@ -141,12 +140,11 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li TB_Linkage linkage = TB_LINKAGE_PRIVATE; - TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, arena, &out_param_count); + TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); p->param_nodes = {params, cast(isize)out_param_count}; p->proto = tb_function_get_prototype(p->func); @@ -275,17 +273,32 @@ gb_internal void cg_procedure_end(cgProcedure *p) { if (tb_inst_get_control(p->func)) { tb_inst_ret(p->func, 0, nullptr); } + bool emit_asm = false; // if (p->name == "main") { - if (p->name == "bug" ABI_PKG_NAME_SEPARATOR "main") { + if ( + // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + p->name == "main" || + false + ) { TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); defer (tb_funcopt_exit(opt)); tb_funcopt_print(opt); + // emit_asm = true; + + // GraphViz printing // tb_function_print(p->func, tb_default_print_callback, stdout); } - tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); + TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); + if (emit_asm) { + TB_Assembly *assembly = tb_output_get_asm(output); + for (TB_Assembly *node = assembly; node != nullptr; node = node->next) { + gb_printf_err("%.*s", cast(int)node->length, node->data); + } + gb_printf_err("\n"); + } } gb_internal void cg_procedure_generate(cgProcedure *p) { @@ -332,7 +345,9 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { cgValue res = cg_build_call_expr_internal(p, expr); if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures - GB_PANIC("Handle optional_ok_one"); + GB_ASSERT(res.kind == cgValue_Multi); + GB_ASSERT(res.multi->values.count == 2); + return res.multi->values[0]; // GB_ASSERT(is_type_tuple(res.type)); // GB_ASSERT(res.type->Tuple.variables.count == 2); // return cg_emit_struct_ev(p, res, 0); @@ -345,18 +360,111 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); } GB_ASSERT(value.kind == cgValue_Value); + TEMPORARY_ALLOCATOR_GUARD(); + + TB_Module *m = p->module->mod; - // TODO(bill): abstract out the function prototype stuff so that you handle the ABI correctly (at least for win64 at the moment) - TB_FunctionPrototype *proto = cg_procedure_type_as_prototype(p->module, value.type); + + Type *type = base_type(value.type); + GB_ASSERT(type->kind == Type_Proc); + TypeProc *pt = &type->Proc; + gb_unused(pt); + + TB_FunctionPrototype *proto = cg_procedure_type_as_prototype(p->module, type); TB_Node *target = value.node; - auto params = slice_make(temporary_allocator(), 0 /*proto->param_count*/); - for_array(i, params) { - // params[i] = proto + auto params = slice_make(temporary_allocator(), proto->param_count); + + + GB_ASSERT(build_context.metrics.os == TargetOs_windows); + // TODO(bill): Support more than Win64 ABI + + bool is_odin_like_cc = is_calling_convention_odin(pt->calling_convention); + GB_ASSERT(is_odin_like_cc); + + bool return_is_indirect = false; + + isize param_index = 0; + if (pt->result_count != 0) { + Type *last_result = pt->results->Tuple.variables[pt->results->Tuple.variables.count-1]->type; + + TB_DebugType *dbg = cg_debug_type(p->module, last_result); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(m, dbg, true); + if (rule == TB_PASSING_INDIRECT) { + return_is_indirect = true; + TB_CharUnits size = cast(TB_CharUnits)type_size_of(last_result); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(last_result); + params[param_index++] = tb_inst_local(p->func, size, align); + } + } + for (cgValue arg : args) { + Type *param_type = pt->params->Tuple.variables[param_index]->type; + arg = cg_emit_conv(p, arg, param_type); + arg = cg_flatten_value(p, arg); + + TB_Node *param = nullptr; + + TB_DebugType *dbg = cg_debug_type(p->module, param_type); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(m, dbg, false); + switch (rule) { + case TB_PASSING_DIRECT: + GB_ASSERT(arg.kind == cgValue_Value); + param = arg.node; + break; + case TB_PASSING_INDIRECT: + { + // indirect + cgValue arg_ptr = cg_address_from_load_or_generate_local(p, arg); + GB_ASSERT(arg_ptr.kind == cgValue_Value); + param = arg_ptr.node; + } + break; + case TB_PASSING_IGNORE: + continue; + } + + params[param_index++] = param; + } + + // Split returns + for (isize i = 0; i < pt->result_count-1; i++) { + Type *result = pt->results->Tuple.variables[i]->type; + TB_CharUnits size = cast(TB_CharUnits)type_size_of(result); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(result); + params[param_index++] = tb_inst_local(p->func, size, align); + } + + if (pt->calling_convention == ProcCC_Odin) { + cgValue ctx_ptr = cg_find_or_generate_context_ptr(p).addr; + GB_ASSERT(ctx_ptr.kind == cgValue_Value); + params[param_index++] = ctx_ptr.node; + } + GB_ASSERT_MSG(param_index == params.count, "%td vs %td\n %s %u %u", + param_index, params.count, + type_to_string(type), + proto->return_count, + proto->param_count); + + for (TB_Node *param : params) { + GB_ASSERT(param != nullptr); } GB_ASSERT(target != nullptr); TB_MultiOutput multi_output = tb_inst_call(p->func, proto, target, params.count, params.data); gb_unused(multi_output); + + switch (pt->result_count) { + case 0: + return {}; + case 1: + if (return_is_indirect) { + return cg_lvalue_addr(params[0], pt->results->Tuple.variables[0]->type); + } + GB_ASSERT(multi_output.count == 1); + return cg_value(multi_output.single, pt->results->Tuple.variables[0]->type); + } + + + return {}; } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 6aa906288..2cdedbacf 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -252,7 +252,45 @@ gb_internal void cg_addr_store(cgProcedure *p, cgAddr addr, cgValue value) { } else if (addr.kind == cgAddr_Map) { GB_PANIC("TODO(bill): cgAddr_Map"); } else if (addr.kind == cgAddr_Context) { - GB_PANIC("TODO(bill): cgAddr_Context"); + cgAddr old_addr = cg_find_or_generate_context_ptr(p); + + bool create_new = true; + for_array(i, p->context_stack) { + cgContextData *ctx_data = &p->context_stack[i]; + if (ctx_data->ctx.addr.node == old_addr.addr.node) { + if (ctx_data->uses > 0) { + create_new = true; + } else if (p->scope_index > ctx_data->scope_index) { + create_new = true; + } else { + // gb_printf_err("%.*s (curr:%td) (ctx:%td) (uses:%td)\n", LIT(p->name), p->scope_index, ctx_data->scope_index, ctx_data->uses); + create_new = false; + } + break; + } + } + + cgValue next = {}; + if (create_new) { + cgValue old = cg_addr_load(p, old_addr); + cgAddr next_addr = cg_add_local(p, t_context, nullptr, true); + cg_addr_store(p, next_addr, old); + cg_push_context_onto_stack(p, next_addr); + next = next_addr.addr; + } else { + next = old_addr.addr; + } + + if (addr.ctx.sel.index.count > 0) { + cgValue lhs = cg_emit_deep_field_gep(p, next, addr.ctx.sel); + cgValue rhs = cg_emit_conv(p, value, type_deref(lhs.type)); + cg_emit_store(p, lhs, rhs); + } else { + cgValue lhs = next; + cgValue rhs = cg_emit_conv(p, value, cg_addr_type(addr)); + cg_emit_store(p, lhs, rhs); + } + return; } else if (addr.kind == cgAddr_SoaVariable) { GB_PANIC("TODO(bill): cgAddr_SoaVariable"); } else if (addr.kind == cgAddr_Swizzle) { -- cgit v1.2.3 From 99ebfc337e7dc3b103dcc77ce6609e4a1c44073f Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 08:33:30 +0100 Subject: Support multiple return values --- src/tilde/tb.h | 2 +- src/tilde_proc.cpp | 66 +++++++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 56 insertions(+), 12 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 048fce598..8e5bc5567 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -951,7 +951,7 @@ TB_API TB_Node* tb_inst_sint(TB_Function* f, TB_DataType dt, int64_t imm); TB_API TB_Node* tb_inst_uint(TB_Function* f, TB_DataType dt, uint64_t imm); TB_API TB_Node* tb_inst_float32(TB_Function* f, float imm); TB_API TB_Node* tb_inst_float64(TB_Function* f, double imm); -TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* str); +TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* srt); TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); // write 'val' over 'count' bytes on 'dst' diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index e7210382c..ec37617fd 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -276,8 +276,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { bool emit_asm = false; // if (p->name == "main") { if ( - // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || - p->name == "main" || + p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + // p->name == "main" || false ) { TB_Arena *arena = tb_default_arena(); @@ -379,25 +379,37 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice // TODO(bill): Support more than Win64 ABI bool is_odin_like_cc = is_calling_convention_odin(pt->calling_convention); - GB_ASSERT(is_odin_like_cc); + GB_ASSERT_MSG(is_odin_like_cc, "TODO(bill): non-odin like procedures"); bool return_is_indirect = false; + Slice result_entities = {}; + Slice param_entities = {}; + if (pt->results) { + result_entities = pt->results->Tuple.variables; + } + if (pt->params) { + param_entities = pt->params->Tuple.variables; + } + isize param_index = 0; if (pt->result_count != 0) { - Type *last_result = pt->results->Tuple.variables[pt->results->Tuple.variables.count-1]->type; + Type *last_result = result_entities[result_entities.count-1]->type; TB_DebugType *dbg = cg_debug_type(p->module, last_result); TB_PassingRule rule = tb_get_passing_rule_from_dbg(m, dbg, true); if (rule == TB_PASSING_INDIRECT) { return_is_indirect = true; TB_CharUnits size = cast(TB_CharUnits)type_size_of(last_result); - TB_CharUnits align = cast(TB_CharUnits)type_align_of(last_result); - params[param_index++] = tb_inst_local(p->func, size, align); + TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(last_result), 16); + TB_Node *local = tb_inst_local(p->func, size, align); + // TODO(bill): Should this need to be zeroed any way? + tb_inst_memzero(p->func, local, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); + params[param_index++] = local; } } for (cgValue arg : args) { - Type *param_type = pt->params->Tuple.variables[param_index]->type; + Type *param_type = param_entities[param_index]->type; arg = cg_emit_conv(p, arg, param_type); arg = cg_flatten_value(p, arg); @@ -426,11 +438,15 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice } // Split returns + isize split_offset = param_index; for (isize i = 0; i < pt->result_count-1; i++) { - Type *result = pt->results->Tuple.variables[i]->type; + Type *result = result_entities[i]->type; TB_CharUnits size = cast(TB_CharUnits)type_size_of(result); - TB_CharUnits align = cast(TB_CharUnits)type_align_of(result); - params[param_index++] = tb_inst_local(p->func, size, align); + TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(result), 16); + TB_Node *local = tb_inst_local(p->func, size, align); + // TODO(bill): Should this need to be zeroed any way? + tb_inst_memzero(p->func, local, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); + params[param_index++] = local; } if (pt->calling_convention == ProcCC_Odin) { @@ -463,9 +479,37 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice return cg_value(multi_output.single, pt->results->Tuple.variables[0]->type); } + cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); + multi->values = slice_make(permanent_allocator(), pt->result_count); + if (is_odin_like_cc) { + for (isize i = 0; i < pt->result_count-1; i++) { + multi->values[i] = cg_lvalue_addr(params[split_offset+i], result_entities[i]->type); + } - return {}; + Type *end_type = result_entities[pt->result_count-1]->type; + if (return_is_indirect) { + multi->values[pt->result_count-1] = cg_lvalue_addr(params[0], end_type); + } else { + GB_ASSERT(multi_output.count == 1); + TB_DataType dt = cg_data_type(end_type); + TB_Node *res = multi_output.single; + if (res->dt.raw != dt.raw) { + // struct-like returns passed in registers + TB_CharUnits size = cast(TB_CharUnits)type_size_of(end_type); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(end_type); + TB_Node *addr = tb_inst_local(p->func, size, align); + tb_inst_store(p->func, res->dt, addr, res, align, false); + multi->values[pt->result_count-1] = cg_lvalue_addr(addr, end_type); + } else { + multi->values[pt->result_count-1] = cg_value(res, end_type); + } + } + } else { + GB_PANIC("TODO non-odin like multiple return stuff"); + } + + return cg_value_multi(multi, pt->results); } gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { -- cgit v1.2.3 From b09ea17f0ecbfc30d9f41bd450fd2010820db28c Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 08:48:13 +0100 Subject: Support multiple return values for non-odin calling conventions --- src/tilde.hpp | 1 + src/tilde_proc.cpp | 64 +++++++++++++++++++++++++++++++++++++++--------------- src/tilde_stmt.cpp | 14 ++++++++++++ 3 files changed, 61 insertions(+), 18 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.hpp b/src/tilde.hpp index 633eb63db..d548de78e 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -282,6 +282,7 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &sr gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgValue value); +gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment); gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index ec37617fd..8f7b1972e 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -379,7 +379,6 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice // TODO(bill): Support more than Win64 ABI bool is_odin_like_cc = is_calling_convention_odin(pt->calling_convention); - GB_ASSERT_MSG(is_odin_like_cc, "TODO(bill): non-odin like procedures"); bool return_is_indirect = false; @@ -394,16 +393,19 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice isize param_index = 0; if (pt->result_count != 0) { - Type *last_result = result_entities[result_entities.count-1]->type; - - TB_DebugType *dbg = cg_debug_type(p->module, last_result); + Type *return_type = nullptr; + if (is_odin_like_cc) { + return_type = result_entities[result_entities.count-1]->type; + } else { + return_type = pt->results; + } + TB_DebugType *dbg = cg_debug_type(p->module, return_type); TB_PassingRule rule = tb_get_passing_rule_from_dbg(m, dbg, true); if (rule == TB_PASSING_INDIRECT) { return_is_indirect = true; - TB_CharUnits size = cast(TB_CharUnits)type_size_of(last_result); - TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(last_result), 16); + TB_CharUnits size = cast(TB_CharUnits)type_size_of(return_type); + TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(return_type), 16); TB_Node *local = tb_inst_local(p->func, size, align); - // TODO(bill): Should this need to be zeroed any way? tb_inst_memzero(p->func, local, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); params[param_index++] = local; } @@ -424,8 +426,13 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice break; case TB_PASSING_INDIRECT: { + cgValue arg_ptr = {}; // indirect - cgValue arg_ptr = cg_address_from_load_or_generate_local(p, arg); + if (is_odin_like_cc) { + arg_ptr = cg_address_from_load_or_generate_local(p, arg); + } else { + arg_ptr = cg_copy_value_to_ptr(p, arg, param_type, 16); + } GB_ASSERT(arg_ptr.kind == cgValue_Value); param = arg_ptr.node; } @@ -438,15 +445,18 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice } // Split returns - isize split_offset = param_index; - for (isize i = 0; i < pt->result_count-1; i++) { - Type *result = result_entities[i]->type; - TB_CharUnits size = cast(TB_CharUnits)type_size_of(result); - TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(result), 16); - TB_Node *local = tb_inst_local(p->func, size, align); - // TODO(bill): Should this need to be zeroed any way? - tb_inst_memzero(p->func, local, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); - params[param_index++] = local; + isize split_offset = -1; + if (is_odin_like_cc) { + split_offset = param_index; + for (isize i = 0; i < pt->result_count-1; i++) { + Type *result = result_entities[i]->type; + TB_CharUnits size = cast(TB_CharUnits)type_size_of(result); + TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(result), 16); + TB_Node *local = tb_inst_local(p->func, size, align); + // TODO(bill): Should this need to be zeroed any way? + tb_inst_memzero(p->func, local, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); + params[param_index++] = local; + } } if (pt->calling_convention == ProcCC_Odin) { @@ -483,6 +493,7 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice multi->values = slice_make(permanent_allocator(), pt->result_count); if (is_odin_like_cc) { + GB_ASSERT(split_offset >= 0); for (isize i = 0; i < pt->result_count-1; i++) { multi->values[i] = cg_lvalue_addr(params[split_offset+i], result_entities[i]->type); } @@ -506,7 +517,24 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice } } } else { - GB_PANIC("TODO non-odin like multiple return stuff"); + TB_Node *the_tuple = {}; + if (return_is_indirect) { + the_tuple = params[0]; + } else { + GB_ASSERT(multi_output.count == 1); + TB_Node *res = multi_output.single; + + // struct-like returns passed in registers + TB_CharUnits size = cast(TB_CharUnits)type_size_of(pt->results); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(pt->results); + the_tuple = tb_inst_local(p->func, size, align); + tb_inst_store(p->func, res->dt, the_tuple, res, align, false); + } + for (isize i = 0; i < pt->result_count; i++) { + i64 offset = type_offset_of(pt->results, i, nullptr); + TB_Node *ptr = tb_inst_member_access(p->func, the_tuple, offset); + multi->values[i] = cg_lvalue_addr(ptr, result_entities[i]->type); + } } return cg_value_multi(multi, pt->results); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 2cdedbacf..f0203e724 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -736,6 +736,20 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero return addr; } +gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment) { + TB_CharUnits size = cast(TB_CharUnits)type_size_of(original_type); + TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(original_type), min_alignment); + TB_Node *copy = tb_inst_local(p->func, size, align); + if (value.kind == cgValue_Value) { + tb_inst_store(p->func, cg_data_type(original_type), copy, value.node, align, false); + } else { + GB_ASSERT(value.kind == cgValue_Addr); + tb_inst_memcpy(p->func, copy, value.node, tb_inst_uint(p->func, TB_TYPE_INT, size), align, false); + } + + return cg_value(copy, alloc_type_pointer(original_type)); +} + gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgValue value) { switch (value.kind) { case cgValue_Value: -- cgit v1.2.3 From 4654b41c3e6a01118e28e6297b2de97bd0a8cd42 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 09:06:44 +0100 Subject: Implement call expressions --- src/array.cpp | 11 ++++ src/tilde.hpp | 9 ++- src/tilde_const.cpp | 2 +- src/tilde_proc.cpp | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 201 insertions(+), 6 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/array.cpp b/src/array.cpp index d8e25d25d..5d602cebc 100644 --- a/src/array.cpp +++ b/src/array.cpp @@ -168,6 +168,17 @@ gb_internal gb_inline Slice slice(Slice const &array, isize lo, isize hi) } return out; } +template +gb_internal gb_inline Slice slice(Array const &array, isize lo, isize hi) { + GB_ASSERT(0 <= lo && lo <= hi && hi <= array.count); + Slice out = {}; + isize len = hi-lo; + if (len > 0) { + out.data = array.data+lo; + out.count = len; + } + return out; +} template diff --git a/src/tilde.hpp b/src/tilde.hpp index d548de78e..45eceeb7b 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -42,8 +42,9 @@ struct cgValue { cgValueKind kind; Type * type; union { - TB_Symbol *symbol; - TB_Node * node; + // NOTE: any value in this union must be a pointer + TB_Symbol * symbol; + TB_Node * node; cgValueMulti *multi; }; }; @@ -308,4 +309,6 @@ gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgV gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); -gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); \ No newline at end of file +gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); + +gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 6e3979637..e066c72a3 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -126,7 +126,7 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty if (global == nullptr) { global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(type), type_align_of(type), 2); } tb_global_add_symbol_reloc(m->mod, global, offset+0, cast(TB_Symbol *)str_global); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8f7b1972e..0deb4af45 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -355,7 +355,7 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { return res; } -gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice args) { +gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice const &args) { if (value.kind == cgValue_Symbol) { value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); } @@ -540,6 +540,43 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice return cg_value_multi(multi, pt->results); } + +gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos) { + switch (param_value.kind) { + case ParameterValue_Constant: + if (is_type_constant_type(parameter_type)) { + auto res = cg_const_value(p, parameter_type, param_value.value); + return res; + } else { + ExactValue ev = param_value.value; + cgValue arg = {}; + Type *type = type_of_expr(param_value.original_ast_expr); + if (type != nullptr) { + arg = cg_const_value(p, type, ev); + } else { + arg = cg_const_value(p, parameter_type, param_value.value); + } + return cg_emit_conv(p, arg, parameter_type); + } + + case ParameterValue_Nil: + return cg_const_nil(p, parameter_type); + case ParameterValue_Location: + { + String proc_name = {}; + if (p->entity != nullptr) { + proc_name = p->entity->token.string; + } + GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); + // return cg_emit_source_code_location_as_global(p, proc_name, pos); + break; + } + case ParameterValue_Value: + return cg_build_expr(p, param_value.ast_value); + } + return cg_const_nil(p, parameter_type); +} + gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -611,7 +648,151 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { value = cg_emit_load(p, value); } GB_ASSERT(value.kind == cgValue_Value); + GB_ASSERT(value.node != nullptr); GB_ASSERT(is_type_proc(value.type)); - return cg_emit_call(p, value, {}); + TEMPORARY_ALLOCATOR_GUARD(); + + Type *proc_type_ = base_type(value.type); + GB_ASSERT(proc_type_->kind == Type_Proc); + TypeProc *pt = &proc_type_->Proc; + + GB_ASSERT(ce->split_args != nullptr); + + auto args = array_make(temporary_allocator(), 0, pt->param_count); + + bool vari_expand = (ce->ellipsis.pos.line != 0); + bool is_c_vararg = pt->c_vararg; + + for_array(i, ce->split_args->positional) { + Entity *e = pt->params->Tuple.variables[i]; + if (e->kind == Entity_TypeName) { + continue; + } else if (e->kind == Entity_Constant) { + continue; + } + + GB_ASSERT(e->kind == Entity_Variable); + + if (pt->variadic && pt->variadic_index == i) { + cgValue variadic_args = cg_const_nil(p, e->type); + auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count); + if (variadic.count != 0) { + // variadic call argument generation + Type *slice_type = e->type; + GB_ASSERT(slice_type->kind == Type_Slice); + + if (is_c_vararg) { + GB_ASSERT(!vari_expand); + + Type *elem_type = slice_type->Slice.elem; + + for (Ast *var_arg : variadic) { + cgValue arg = cg_build_expr(p, var_arg); + if (is_type_any(elem_type)) { + array_add(&args, cg_emit_conv(p, arg, default_type(arg.type))); + } else { + array_add(&args, cg_emit_conv(p, arg, elem_type)); + } + } + break; + } else if (vari_expand) { + GB_ASSERT(variadic.count == 1); + variadic_args = cg_build_expr(p, variadic[0]); + variadic_args = cg_emit_conv(p, variadic_args, slice_type); + } else { + Type *elem_type = slice_type->Slice.elem; + + auto var_args = array_make(temporary_allocator(), 0, variadic.count); + for (Ast *var_arg : variadic) { + cgValue v = cg_build_expr(p, var_arg); + cg_append_tuple_values(p, &var_args, v); + } + isize slice_len = var_args.count; + if (slice_len > 0) { + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cgAddr base_array = cg_add_local(p, alloc_type_array(elem_type, slice_len), nullptr, true); + + for (isize i = 0; i < var_args.count; i++) { + cgValue addr = cg_emit_array_epi(p, base_array.addr, cast(i32)i); + cgValue var_arg = var_args[i]; + var_arg = cg_emit_conv(p, var_arg, elem_type); + cg_emit_store(p, addr, var_arg); + } + + cgValue base_elem = cg_emit_array_epi(p, base_array.addr, 0); + cgValue len = cg_const_int(p, t_int, slice_len); + GB_PANIC("TODO(bill): cg_fill_slice"); + // cg_fill_slice(p, slice, base_elem, len); + + variadic_args = cg_addr_load(p, slice); + } + } + } + array_add(&args, variadic_args); + + break; + } else { + cgValue value = cg_build_expr(p, ce->split_args->positional[i]); + cg_append_tuple_values(p, &args, value); + } + } + + if (!is_c_vararg) { + array_resize(&args, pt->param_count); + } + + for (Ast *arg : ce->split_args->named) { + ast_node(fv, FieldValue, arg); + GB_ASSERT(fv->field->kind == Ast_Ident); + String name = fv->field->Ident.token.string; + gb_unused(name); + isize param_index = lookup_procedure_parameter(pt, name); + GB_ASSERT(param_index >= 0); + + cgValue value = cg_build_expr(p, fv->value); + GB_ASSERT(!is_type_tuple(value.type)); + args[param_index] = value; + } + + TokenPos pos = ast_token(ce->proc).pos; + + + if (pt->params != nullptr) { + isize min_count = pt->params->Tuple.variables.count; + if (is_c_vararg) { + min_count -= 1; + } + GB_ASSERT(args.count >= min_count); + for_array(arg_index, pt->params->Tuple.variables) { + Entity *e = pt->params->Tuple.variables[arg_index]; + if (pt->variadic && arg_index == pt->variadic_index) { + if (!is_c_vararg && args[arg_index].node == nullptr) { + args[arg_index] = cg_const_nil(p, e->type); + } + continue; + } + + cgValue arg = args[arg_index]; + if (arg.node == nullptr) { + switch (e->kind) { + case Entity_TypeName: + case Entity_Constant: + break; + case Entity_Variable: + args[arg_index] = cg_handle_param_value(p, e->type, e->Variable.param_value, pos); + break; + default: + GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind])); + } + } else { + args[arg_index] = cg_emit_conv(p, arg, e->type); + } + } + } + + isize final_count = is_c_vararg ? args.count : pt->param_count; + auto call_args = slice(args, 0, final_count); + + return cg_emit_call(p, value, call_args); } -- cgit v1.2.3 From eec3b3009f0005090ddd5a7901e5f3c38cf31ce1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 10:16:28 +0100 Subject: Begin work on builtin procedures --- src/checker.cpp | 1 + src/tilde.cpp | 1 + src/tilde.hpp | 7 +- src/tilde_builtin.cpp | 147 +++++++++++++++ src/tilde_expr.cpp | 486 +++++++++++++++++++++++++++++++++++++++++++++++++- src/tilde_proc.cpp | 3 +- src/types.cpp | 1 + 7 files changed, 637 insertions(+), 9 deletions(-) create mode 100644 src/tilde_builtin.cpp (limited to 'src/tilde_proc.cpp') diff --git a/src/checker.cpp b/src/checker.cpp index 2a2cb5c42..01b8b6b2a 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1114,6 +1114,7 @@ gb_internal void init_universal(void) { t_u8_ptr = alloc_type_pointer(t_u8); + t_u8_multi_ptr = alloc_type_multi_pointer(t_u8); t_int_ptr = alloc_type_pointer(t_int); t_i64_ptr = alloc_type_pointer(t_i64); t_f64_ptr = alloc_type_pointer(t_f64); diff --git a/src/tilde.cpp b/src/tilde.cpp index 78aa3640d..1969deaec 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -669,6 +669,7 @@ gb_internal String cg_get_entity_name(cgModule *m, Entity *e) { #include "tilde_const.cpp" #include "tilde_debug.cpp" #include "tilde_expr.cpp" +#include "tilde_builtin.cpp" #include "tilde_proc.cpp" #include "tilde_stmt.cpp" diff --git a/src/tilde.hpp b/src/tilde.hpp index 45eceeb7b..f0e45bb97 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -272,6 +272,7 @@ gb_internal void cg_build_when_stmt(cgProcedure *p, AstWhenStmt *ws); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr); gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr); +gb_internal cgValue cg_build_addr_ptr(cgProcedure *p, Ast *expr); gb_internal Type * cg_addr_type(cgAddr const &addr); gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr); @@ -311,4 +312,8 @@ gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); -gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); \ No newline at end of file +gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); + + +gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value); +gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); \ No newline at end of file diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp new file mode 100644 index 000000000..08c3f7bdd --- /dev/null +++ b/src/tilde_builtin.cpp @@ -0,0 +1,147 @@ +gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value) { + Type *t = base_type(value.type); + + switch (t->kind) { + case Type_Basic: + switch (t->Basic.kind) { + case Basic_string: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue len_ptr = cg_emit_struct_ep(p, ptr, 1); + return cg_emit_load(p, len_ptr); + } + case Basic_cstring: + break; + } + break; + case Type_Array: + return cg_const_int(p, t_int, t->Array.count); + case Type_EnumeratedArray: + return cg_const_int(p, t_int, t->EnumeratedArray.count); + case Type_Slice: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue len_ptr = cg_emit_struct_ep(p, ptr, 1); + return cg_emit_load(p, len_ptr); + } + case Type_DynamicArray: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue len_ptr = cg_emit_struct_ep(p, ptr, 1); + return cg_emit_load(p, len_ptr); + } + case Type_Map: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue len_ptr = cg_emit_struct_ep(p, ptr, 1); + return cg_emit_conv(p, cg_emit_load(p, len_ptr), t_int); + } + case Type_Struct: + GB_ASSERT(is_type_soa_struct(t)); + break; + case Type_RelativeSlice: + break; + } + + GB_PANIC("TODO(bill): cg_builtin_len %s", type_to_string(t)); + return {}; +} + +gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { + Type *t = base_type(value.type); + cgValue res = {}; + switch (t->kind) { + case Type_Slice: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue data_ptr = cg_emit_struct_ep(p, ptr, 0); + res = cg_emit_load(p, data_ptr); + } + break; + case Type_DynamicArray: + { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue data_ptr = cg_emit_struct_ep(p, ptr, 0); + res = cg_emit_load(p, data_ptr); + } + break; + case Type_Basic: + if (t->Basic.kind == Basic_string) { + GB_ASSERT(value.kind == cgValue_Addr); + cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); + cgValue data_ptr = cg_emit_struct_ep(p, ptr, 0); + res = cg_emit_load(p, data_ptr); + } else if (t->Basic.kind == Basic_cstring) { + res = cg_emit_conv(p, value, t_u8_multi_ptr); + } + break; + case Type_Pointer: + case Type_MultiPointer: + GB_PANIC("TODO(bill) %s", type_to_string(value.type)); + // res = cg_emit_conv(p, value, tv.type); + break; + } + GB_ASSERT(res.node != nullptr); + return res; +} + +gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr) { + ast_node(ce, CallExpr, expr); + + if (BuiltinProc__simd_begin < id && id < BuiltinProc__simd_end) { + GB_PANIC("TODO(bill): cg_build_builtin_simd_proc"); + // return cg_build_builtin_simd_proc(p, expr, tv, id); + } + + String builtin_name = builtin_procs[id].name; + + switch (id) { + case BuiltinProc_DIRECTIVE: { + ast_node(bd, BasicDirective, ce->proc); + String name = bd->name.string; + GB_ASSERT(name == "location"); + String procedure = p->entity->token.string; + TokenPos pos = ast_token(ce->proc).pos; + if (ce->args.count > 0) { + Ast *ident = unselector_expr(ce->args[0]); + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_node(ident); + GB_ASSERT(e != nullptr); + + if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) { + procedure = e->parent_proc_decl->entity->token.string; + } else { + procedure = str_lit(""); + } + pos = e->token.pos; + + } + GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); + // return cg_emit_source_code_location_as_global(p, procedure, pos); + } break; + + case BuiltinProc_len: { + cgValue v = cg_build_expr(p, ce->args[0]); + Type *t = base_type(v.type); + if (is_type_pointer(t)) { + // IMPORTANT TODO(bill): Should there be a nil pointer check? + v = cg_emit_load(p, v); + t = type_deref(t); + } + return cg_builtin_len(p, v); + } + + + } + + + GB_PANIC("TODO(bill): builtin procs %d %.*s", id, LIT(builtin_name)); + return {}; +} + diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 2d4b11336..c0ddc4e70 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -179,7 +179,7 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) TB_DataType dt = cg_data_type(type); switch (value.kind) { case cgValue_Value: - GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%s", type_to_string(type)); value.type = type; if (value.node->dt.raw != dt.raw) { value.node = tb_inst_bitcast(p->func, value.node, dt); @@ -1959,6 +1959,255 @@ gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { } +gb_internal cgValue cg_find_ident(cgProcedure *p, Entity *e, Ast *expr) { + cgAddr *found_addr = map_get(&p->variable_map, e); + if (found_addr) { + return cg_addr_load(p, *found_addr); + } + + cgValue *found = nullptr; + rw_mutex_shared_lock(&p->module->values_mutex); + found = map_get(&p->module->values, e); + rw_mutex_shared_unlock(&p->module->values_mutex); + + if (found) { + + auto v = *found; + // NOTE(bill): This is because pointers are already pointers in LLVM + if (is_type_proc(v.type)) { + return v; + } + return cg_emit_load(p, v); + } else if (e != nullptr && e->kind == Entity_Variable) { + return cg_addr_load(p, cg_build_addr(p, expr)); + } + + if (e->kind == Entity_Procedure) { + return cg_find_procedure_value_from_entity(p->module, e); + } + + String pkg = {}; + if (e->pkg) { + pkg = e->pkg->name; + } + gb_printf_err("Error in: %s\n", token_pos_to_string(ast_token(expr).pos)); + GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(pkg), LIT(e->token.string), e, type_to_string(e->type), expr); + return {}; +} + +gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { + ast_node(ue, UnaryExpr, expr); + auto tv = type_and_value_of_expr(expr); + + + Ast *ue_expr = unparen_expr(ue->expr); + if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) { + GB_PANIC("TODO(bill): &m[k]"); + // Type *tuple = tv.type; + + // Type *map_type = type_of_expr(ue_expr->IndexExpr.expr); + // Type *ot = base_type(map_type); + // Type *t = base_type(type_deref(ot)); + // bool deref = t != ot; + // GB_ASSERT(t->kind == Type_Map); + // ast_node(ie, IndexExpr, ue_expr); + + // lbValue map_val = lb_build_addr_ptr(p, ie->expr); + // if (deref) { + // map_val = lb_emit_load(p, map_val); + // } + + // lbValue key = lb_build_expr(p, ie->index); + // key = lb_emit_conv(p, key, t->Map.key); + + // lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value)); + // lbValue ptr = lb_addr_get_ptr(p, addr); + + // lbValue ok = lb_emit_comp_against_nil(p, Token_NotEq, ptr); + // ok = lb_emit_conv(p, ok, tuple->Tuple.variables[1]->type); + + // lbAddr res = lb_add_local_generated(p, tuple, false); + // lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0); + // lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1); + // lb_emit_store(p, gep0, ptr); + // lb_emit_store(p, gep1, ok); + // return lb_addr_load(p, res); + + } else if (is_type_soa_pointer(tv.type)) { + GB_PANIC("TODO(bill): &soa[i]"); + // ast_node(ie, IndexExpr, ue_expr); + // lbValue addr = lb_build_addr_ptr(p, ie->expr); + // lbValue index = lb_build_expr(p, ie->index); + + // if (!build_context.no_bounds_check) { + // // TODO(bill): soa bounds checking + // } + + // return lb_make_soa_pointer(p, tv.type, addr, index); + } else if (ue_expr->kind == Ast_CompoundLit) { + cgValue v = cg_build_expr(p, ue->expr); + + Type *type = v.type; + cgAddr addr = {}; + // if (p->is_startup) { + // addr = cg_add_global_generated(p->module, type, v); + // } else { + addr = cg_add_local(p, type, nullptr, false); + // } + cg_addr_store(p, addr, v); + return addr.addr; + + } else if (ue_expr->kind == Ast_TypeAssertion) { + GB_PANIC("TODO(bill): &v.(T)"); + // if (is_type_tuple(tv.type)) { + // Type *tuple = tv.type; + // Type *ptr_type = tuple->Tuple.variables[0]->type; + // Type *ok_type = tuple->Tuple.variables[1]->type; + + // ast_node(ta, TypeAssertion, ue_expr); + // TokenPos pos = ast_token(expr).pos; + // Type *type = type_of_expr(ue_expr); + // GB_ASSERT(!is_type_tuple(type)); + + // lbValue e = lb_build_expr(p, ta->expr); + // Type *t = type_deref(e.type); + // if (is_type_union(t)) { + // lbValue v = e; + // if (!is_type_pointer(v.type)) { + // v = lb_address_from_load_or_generate_local(p, v); + // } + // Type *src_type = type_deref(v.type); + // Type *dst_type = type; + + // lbValue src_tag = {}; + // lbValue dst_tag = {}; + // if (is_type_union_maybe_pointer(src_type)) { + // src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v); + // dst_tag = lb_const_bool(p->module, t_bool, true); + // } else { + // src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); + // dst_tag = lb_const_union_tag(p->module, src_type, dst_type); + // } + + // lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); + + // lbValue data_ptr = lb_emit_conv(p, v, ptr_type); + // lbAddr res = lb_add_local_generated(p, tuple, true); + // lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0); + // lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1); + // lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type))); + // lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type)); + // return lb_addr_load(p, res); + // } else if (is_type_any(t)) { + // lbValue v = e; + // if (is_type_pointer(v.type)) { + // v = lb_emit_load(p, v); + // } + + // lbValue data_ptr = lb_emit_conv(p, lb_emit_struct_ev(p, v, 0), ptr_type); + // lbValue any_id = lb_emit_struct_ev(p, v, 1); + // lbValue id = lb_typeid(p->module, type); + + // lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); + + // lbAddr res = lb_add_local_generated(p, tuple, false); + // lbValue gep0 = lb_emit_struct_ep(p, res.addr, 0); + // lbValue gep1 = lb_emit_struct_ep(p, res.addr, 1); + // lb_emit_store(p, gep0, lb_emit_select(p, ok, data_ptr, lb_const_nil(p->module, ptr_type))); + // lb_emit_store(p, gep1, lb_emit_conv(p, ok, ok_type)); + // return lb_addr_load(p, res); + // } else { + // GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); + // } + + // } else { + // GB_ASSERT(is_type_pointer(tv.type)); + + // ast_node(ta, TypeAssertion, ue_expr); + // TokenPos pos = ast_token(expr).pos; + // Type *type = type_of_expr(ue_expr); + // GB_ASSERT(!is_type_tuple(type)); + + // lbValue e = lb_build_expr(p, ta->expr); + // Type *t = type_deref(e.type); + // if (is_type_union(t)) { + // lbValue v = e; + // if (!is_type_pointer(v.type)) { + // v = lb_address_from_load_or_generate_local(p, v); + // } + // Type *src_type = type_deref(v.type); + // Type *dst_type = type; + + + // if ((p->state_flags & StateFlag_no_type_assert) == 0) { + // lbValue src_tag = {}; + // lbValue dst_tag = {}; + // if (is_type_union_maybe_pointer(src_type)) { + // src_tag = lb_emit_comp_against_nil(p, Token_NotEq, v); + // dst_tag = lb_const_bool(p->module, t_bool, true); + // } else { + // src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); + // dst_tag = lb_const_union_tag(p->module, src_type, dst_type); + // } + + + // isize arg_count = 6; + // if (build_context.no_rtti) { + // arg_count = 4; + // } + + // lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); + // auto args = array_make(permanent_allocator(), arg_count); + // args[0] = ok; + + // args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)); + // args[2] = lb_const_int(p->module, t_i32, pos.line); + // args[3] = lb_const_int(p->module, t_i32, pos.column); + + // if (!build_context.no_rtti) { + // args[4] = lb_typeid(p->module, src_type); + // args[5] = lb_typeid(p->module, dst_type); + // } + // lb_emit_runtime_call(p, "type_assertion_check", args); + // } + + // lbValue data_ptr = v; + // return lb_emit_conv(p, data_ptr, tv.type); + // } else if (is_type_any(t)) { + // lbValue v = e; + // if (is_type_pointer(v.type)) { + // v = lb_emit_load(p, v); + // } + // lbValue data_ptr = lb_emit_struct_ev(p, v, 0); + // if ((p->state_flags & StateFlag_no_type_assert) == 0) { + // GB_ASSERT(!build_context.no_rtti); + + // lbValue any_id = lb_emit_struct_ev(p, v, 1); + + // lbValue id = lb_typeid(p->module, type); + // lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); + // auto args = array_make(permanent_allocator(), 6); + // args[0] = ok; + + // args[1] = lb_find_or_add_entity_string(p->module, get_file_path_string(pos.file_id)); + // args[2] = lb_const_int(p->module, t_i32, pos.line); + // args[3] = lb_const_int(p->module, t_i32, pos.column); + + // args[4] = any_id; + // args[5] = id; + // lb_emit_runtime_call(p, "type_assertion_check", args); + // } + + // return lb_emit_conv(p, data_ptr, tv.type); + // } else { + // GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); + // } + // } + } + + return cg_build_addr_ptr(p, ue->expr); +} + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { expr = unparen_expr(expr); @@ -2016,9 +2265,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { if (addr) { return cg_addr_load(p, *addr); } - // return cg_find_ident(p, m, e, expr); - GB_PANIC("TODO: cg_find_ident"); - return {}; + return cg_find_ident(p, e, expr); case_end; case_ast_node(i, Implicit, expr); @@ -2151,8 +2398,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(ue, UnaryExpr, expr); if (ue->op.kind == Token_And) { - GB_PANIC("TODO(bill): cg_build_unary_and"); - // return cg_build_unary_and(p, expr); + return cg_build_unary_and(p, expr); } cgValue v = cg_build_expr(p, ue->expr); return cg_emit_unary_arith(p, ue->op.kind, v, type); @@ -2166,6 +2412,10 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { } +gb_internal cgValue cg_build_addr_ptr(cgProcedure *p, Ast *expr) { + cgAddr addr = cg_build_addr(p, expr); + return cg_addr_get_ptr(p, addr); +} gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr); gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr) { @@ -2193,6 +2443,225 @@ gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr) { return addr; } +gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { + ast_node(ie, IndexExpr, expr); + + Type *t = base_type(type_of_expr(ie->expr)); + + bool deref = is_type_pointer(t); + t = base_type(type_deref(t)); + if (is_type_soa_struct(t)) { + GB_PANIC("TODO(bill): #soa"); + // // SOA STRUCTURES!!!! + // lbValue val = cg_build_addr_ptr(p, ie->expr); + // if (deref) { + // val = cg_emit_load(p, val); + // } + + // cgValue index = cg_build_expr(p, ie->index); + // return cg_addr_soa_variable(val, index, ie->index); + } + + if (ie->expr->tav.mode == Addressing_SoaVariable) { + GB_PANIC("TODO(bill): #soa"); + // // SOA Structures for slices/dynamic arrays + // GB_ASSERT(is_type_pointer(type_of_expr(ie->expr))); + + // lbValue field = lb_build_expr(p, ie->expr); + // lbValue index = lb_build_expr(p, ie->index); + + + // if (!build_context.no_bounds_check) { + // // TODO HACK(bill): Clean up this hack to get the length for bounds checking + // // GB_ASSERT(LLVMIsALoadInst(field.value)); + + // // lbValue a = {}; + // // a.value = LLVMGetOperand(field.value, 0); + // // a.type = alloc_type_pointer(field.type); + + // // irInstr *b = &a->Instr; + // // GB_ASSERT(b->kind == irInstr_StructElementPtr); + // // lbValue base_struct = b->StructElementPtr.address; + + // // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct)))); + // // lbValue len = ir_soa_struct_len(p, base_struct); + // // lb_emit_bounds_check(p, ast_token(ie->index), index, len); + // } + // lbValue val = lb_emit_ptr_offset(p, field, index); + // return lb_addr(val); + } + + GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr)); + + if (is_type_map(t)) { + GB_PANIC("TODO(bill): map indexing"); + // lbAddr map_addr = lb_build_addr(p, ie->expr); + // lbValue key = lb_build_expr(p, ie->index); + // key = lb_emit_conv(p, key, t->Map.key); + + // Type *result_type = type_of_expr(expr); + // lbValue map_ptr = lb_addr_get_ptr(p, map_addr); + // if (is_type_pointer(type_deref(map_ptr.type))) { + // map_ptr = lb_emit_load(p, map_ptr); + // } + // return lb_addr_map(map_ptr, key, t, result_type); + } + + switch (t->kind) { + case Type_Array: { + cgValue array = {}; + array = cg_build_addr_ptr(p, ie->expr); + if (deref) { + array = cg_emit_load(p, array); + } + cgValue index = cg_build_expr(p, ie->index); + index = cg_emit_conv(p, index, t_int); + cgValue elem = cg_emit_array_ep(p, array, index); + + auto index_tv = type_and_value_of_expr(ie->index); + if (index_tv.mode != Addressing_Constant) { + // cgValue len = cg_const_int(p->module, t_int, t->Array.count); + // cg_emit_bounds_check(p, ast_token(ie->index), index, len); + } + return cg_addr(elem); + } + + case Type_EnumeratedArray: { + cgValue array = {}; + array = cg_build_addr_ptr(p, ie->expr); + if (deref) { + array = cg_emit_load(p, array); + } + + Type *index_type = t->EnumeratedArray.index; + + auto index_tv = type_and_value_of_expr(ie->index); + + cgValue index = {}; + if (compare_exact_values(Token_NotEq, *t->EnumeratedArray.min_value, exact_value_i64(0))) { + if (index_tv.mode == Addressing_Constant) { + ExactValue idx = exact_value_sub(index_tv.value, *t->EnumeratedArray.min_value); + index = cg_const_value(p, index_type, idx); + } else { + index = cg_emit_arith(p, Token_Sub, + cg_build_expr(p, ie->index), + cg_const_value(p, index_type, *t->EnumeratedArray.min_value), + index_type); + index = cg_emit_conv(p, index, t_int); + } + } else { + index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); + } + + cgValue elem = cg_emit_array_ep(p, array, index); + + if (index_tv.mode != Addressing_Constant) { + // cgValue len = cg_const_int(p->module, t_int, t->EnumeratedArray.count); + // cg_emit_bounds_check(p, ast_token(ie->index), index, len); + } + return cg_addr(elem); + } + + case Type_Slice: { + cgValue slice = {}; + slice = cg_build_expr(p, ie->expr); + if (deref) { + slice = cg_emit_load(p, slice); + } + cgValue elem = cg_builtin_raw_data(p, slice); + cgValue index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); + // cgValue len = cg_builtin_len(p, slice); + // cg_emit_bounds_check(p, ast_token(ie->index), index, len); + cgValue v = cg_emit_ptr_offset(p, elem, index); + return cg_addr(v); + } + + case Type_MultiPointer: { + cgValue multi_ptr = {}; + multi_ptr = cg_build_expr(p, ie->expr); + if (deref) { + multi_ptr = cg_emit_load(p, multi_ptr); + } + cgValue index = cg_build_expr(p, ie->index); + index = cg_emit_conv(p, index, t_int); + + return cg_addr(cg_emit_ptr_offset(p, multi_ptr, index)); + } + + case Type_RelativeSlice: { + GB_PANIC("TODO(bill): relative slice"); + // lbAddr slice_addr = {}; + // if (deref) { + // slice_addr = lb_addr(lb_build_expr(p, ie->expr)); + // } else { + // slice_addr = lb_build_addr(p, ie->expr); + // } + // lbValue slice = lb_addr_load(p, slice_addr); + + // lbValue elem = lb_slice_elem(p, slice); + // lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); + // lbValue len = lb_slice_len(p, slice); + // lb_emit_bounds_check(p, ast_token(ie->index), index, len); + // lbValue v = lb_emit_ptr_offset(p, elem, index); + // return lb_addr(v); + } + + case Type_DynamicArray: { + cgValue dynamic_array = {}; + dynamic_array = cg_build_expr(p, ie->expr); + if (deref) { + dynamic_array = cg_emit_load(p, dynamic_array); + } + cgValue elem = cg_builtin_raw_data(p, dynamic_array); + cgValue index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); + // cgValue len = cg_dynamic_array_len(p, dynamic_array); + // cg_emit_bounds_check(p, ast_token(ie->index), index, len); + cgValue v = cg_emit_ptr_offset(p, elem, index); + return cg_addr(v); + } + + case Type_Matrix: { + GB_PANIC("TODO(bill): 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 + cgValue str; + cgValue elem; + cgValue len; + cgValue index; + + str = cg_build_expr(p, ie->expr); + if (deref) { + str = cg_emit_load(p, str); + } + elem = cg_builtin_raw_data(p, str); + len = cg_builtin_len(p, str); + + index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); + // cg_emit_bounds_check(p, ast_token(ie->index), index, len); + + return cg_addr(cg_emit_ptr_offset(p, elem, index)); + } + } + return {}; +} gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { switch (expr->kind) { @@ -2218,6 +2687,10 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { return cg_build_addr_from_entity(p, e, expr); case_end; + case_ast_node(ie, IndexExpr, expr); + return cg_build_addr_index_expr(p, expr); + case_end; + case_ast_node(se, SliceExpr, expr); return cg_build_addr_slice_expr(p, expr); case_end; @@ -2350,6 +2823,5 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { LIT(ast_strings[expr->kind]), token_pos_to_string(token_pos)); - return {}; } \ No newline at end of file diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 0deb4af45..8016e4dba 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -607,7 +607,8 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { } return {}; } - GB_PANIC("TODO(bill): builtin procs %d %.*s", id, LIT(builtin_procs[id].name)); + + return cg_build_builtin(p, id, expr); } // NOTE(bill): Regular call diff --git a/src/types.cpp b/src/types.cpp index f513f23d9..17945b109 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -594,6 +594,7 @@ gb_global Type *t_untyped_uninit = &basic_types[Basic_UntypedUninit]; gb_global Type *t_u8_ptr = nullptr; +gb_global Type *t_u8_multi_ptr = nullptr; gb_global Type *t_int_ptr = nullptr; gb_global Type *t_i64_ptr = nullptr; gb_global Type *t_f64_ptr = nullptr; -- cgit v1.2.3 From 6c12156b1a47cb3c39e5c12d443e482af2a218bb Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 11:16:29 +0100 Subject: Simplify procedure argument handling --- src/tilde.cpp | 1 + src/tilde.hpp | 5 +-- src/tilde/tb.h | 3 +- src/tilde/tb.lib | Bin 4162738 -> 4157412 bytes src/tilde_const.cpp | 2 +- src/tilde_expr.cpp | 2 +- src/tilde_proc.cpp | 113 +++++++++++++++++++++++++++++++++++++++------------- src/tilde_stmt.cpp | 5 ++- 8 files changed, 95 insertions(+), 36 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 1969deaec..26bd69f4f 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -75,6 +75,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_f32be: return TB_TYPE_F32; case Basic_f64be: return TB_TYPE_F64; } + break; case Type_Pointer: case Type_MultiPointer: diff --git a/src/tilde.hpp b/src/tilde.hpp index f0e45bb97..0e5b3b551 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -166,9 +166,6 @@ struct cgProcedure { TB_FunctionPrototype *proto; TB_Symbol *symbol; - // includes parameters, pointers to return values, and context ptr - Slice param_nodes; - Entity * entity; cgModule *module; String name; @@ -309,11 +306,11 @@ gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgV gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); - gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); +gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos); gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value); gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); \ No newline at end of file diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 8e5bc5567..abe3c5a1a 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -83,7 +83,6 @@ typedef enum TB_ABI { typedef enum TB_OutputFlavor { TB_FLAVOR_OBJECT, // .o .obj - TB_FLAVOR_ASSEMBLY, // .s .asm TB_FLAVOR_SHARED, // .so .dll TB_FLAVOR_STATIC, // .a .lib TB_FLAVOR_EXECUTABLE, // .exe @@ -951,7 +950,7 @@ TB_API TB_Node* tb_inst_sint(TB_Function* f, TB_DataType dt, int64_t imm); TB_API TB_Node* tb_inst_uint(TB_Function* f, TB_DataType dt, uint64_t imm); TB_API TB_Node* tb_inst_float32(TB_Function* f, float imm); TB_API TB_Node* tb_inst_float64(TB_Function* f, double imm); -TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* srt); +TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* str); TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); // write 'val' over 'count' bytes on 'dst' diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index b9b9dbd44..a3c6ba044 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index e066c72a3..6b1fb5c92 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -851,7 +851,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); } else { - return cg_value(symbol, type); + return cg_value(symbol, alloc_type_pointer(type)); } } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index c0ddc4e70..3d9054803 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -179,7 +179,7 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) TB_DataType dt = cg_data_type(type); switch (value.kind) { case cgValue_Value: - GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%s", type_to_string(type)); + GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%d %s -> %s", dt.type, type_to_string(value.type), type_to_string(type)); value.type = type; if (value.node->dt.raw != dt.raw) { value.node = tb_inst_bitcast(p->func, value.node, dt); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8016e4dba..7c7bda197 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -89,11 +89,9 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i if (p->symbol == nullptr) { p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); - p->param_nodes = {params, cast(isize)out_param_count}; - p->proto = tb_function_get_prototype(p->func); + p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); + tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; } @@ -142,12 +140,9 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); - p->param_nodes = {params, cast(isize)out_param_count}; - p->proto = tb_function_get_prototype(p->func); - + p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); + tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; @@ -179,25 +174,59 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; + bool is_odin_like_cc = is_calling_convention_odin(pt->calling_convention); int param_index = 0; + int param_count = p->proto->param_count; + + if (pt->results) { + Type *result_type = nullptr; + if (is_odin_like_cc) { + result_type = pt->results->Tuple.variables[pt->results->Tuple.variables.count-1]->type; + } else { + result_type = pt->results; + } + TB_DebugType *debug_type = cg_debug_type(p->module, result_type); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(p->module->mod, debug_type, true); + if (rule == TB_PASSING_INDIRECT) { + param_index++; + } + } + if (pt->params != nullptr) for (Entity *e : pt->params->Tuple.variables) { if (e->kind != Entity_Variable) { continue; } - if (param_index >= p->param_nodes.count) { + GB_ASSERT_MSG(param_index < param_count, "%d < %d %.*s :: %s", param_index, param_count, LIT(p->name), type_to_string(p->type)); + + TB_Node *param_ptr = nullptr; + + TB_CharUnits size = cast(TB_CharUnits)type_size_of(e->type); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(e->type); + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(p->module->mod, debug_type, false); + switch (rule) { + case TB_PASSING_DIRECT: { + TB_Node *param = tb_inst_param(p->func, param_index++); + param_ptr = tb_inst_local(p->func, size, align); + tb_inst_store(p->func, param->dt, param_ptr, param, align, false); + } break; + case TB_PASSING_INDIRECT: + // TODO(bill): does this need a copy? for non-odin calling convention stuff? + param_ptr = tb_inst_param(p->func, param_index++); break; + case TB_PASSING_IGNORE: + continue; } - TB_Node *param = p->param_nodes[param_index++]; - cgValue local = cg_value(param, alloc_type_pointer(e->type)); + GB_ASSERT(param_ptr->dt.type == TB_PTR); + + cgValue local = cg_value(param_ptr, alloc_type_pointer(e->type)); if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only String name = e->token.string; - TB_DebugType *debug_type = cg_debug_type(p->module, e->type); - tb_node_append_attrib(param, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); - + tb_node_append_attrib(param_ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); } cgAddr addr = cg_addr(local); if (e) { @@ -243,7 +272,9 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } } - if (p->type->Proc.calling_convention == ProcCC_Odin) { + // isize split_offset = param_index; + + if (pt->calling_convention == ProcCC_Odin) { // NOTE(bill): Push context on to stack from implicit parameter String name = str_lit("__.context_ptr"); @@ -251,10 +282,8 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false); e->flags |= EntityFlag_NoAlias; - TB_Node *param = p->param_nodes[p->param_nodes.count-1]; - param = tb_inst_load(p->func, TB_TYPE_PTR, param, cast(TB_CharUnits)build_context.ptr_size, false); - - cgValue local = cg_value(param, t_context_ptr); + TB_Node *param_ptr = tb_inst_param(p->func, param_count-1); + cgValue local = cg_value(param_ptr, t_context_ptr); cgAddr addr = cg_addr(local); map_set(&p->variable_map, e, addr); @@ -264,6 +293,26 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { cd->scope_index = -1; cd->uses = +1; // make sure it has been used already } + + if (pt->has_named_results) { + auto const &results = pt->results->Tuple.variables; + for_array(i, results) { + Entity *e = results[i]; + GB_ASSERT(e->kind == Entity_Variable); + + if (e->token.string == "") { + continue; + } + GB_ASSERT(!is_blank_ident(e->token)); + + cgAddr res = cg_add_local(p, e->type, e, true); + + if (e->Variable.param_value.kind != ParameterValue_Invalid) { + cgValue c = cg_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos); + cg_addr_store(p, res, c); + } + } + } } gb_internal void cg_procedure_end(cgProcedure *p) { @@ -276,7 +325,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { bool emit_asm = false; // if (p->name == "main") { if ( - p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || + // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || // p->name == "main" || false ) { @@ -301,18 +351,27 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } } +gb_global String procedures_to_generate_list[] = { + str_lit("bug" ABI_PKG_NAME_SEPARATOR "main"), + str_lit("main"), +}; + gb_internal void cg_procedure_generate(cgProcedure *p) { if (p->body == nullptr) { return; } - cg_procedure_begin(p); - defer (cg_procedure_end(p)); - if (p->name != "bug" ABI_PKG_NAME_SEPARATOR "main" && - p->name != "main") { - return; + if ( + p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || + // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + // p->name == "main" || + false + ) { + cg_procedure_begin(p); + cg_build_stmt(p, p->body); } - cg_build_stmt(p, p->body); + + cg_procedure_end(p); } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index f0203e724..4fc00dd28 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -914,7 +914,10 @@ gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, } Type *type = cg_addr_type(lval); - GB_ASSERT(are_types_identical(type, init.type)); + if (!cg_addr_is_empty(lval)) { + GB_ASSERT_MSG(are_types_identical(init.type, type), "%s = %s", type_to_string(init.type), type_to_string(type)); + } + if (init.kind == cgValue_Addr && !cg_addr_is_empty(lval)) { // NOTE(bill): This is needed for certain constructs such as this: -- cgit v1.2.3 From d82c2ce50ff37ca624d32208f2e0249966b5542d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 12:21:29 +0100 Subject: Update Tilde; Add `min` and `max` --- src/tilde.hpp | 2 ++ src/tilde/tb.lib | Bin 4157412 -> 4162054 bytes src/tilde_builtin.cpp | 38 +++++++++++++++++++++ src/tilde_debug.cpp | 5 ++- src/tilde_expr.cpp | 69 ++++++++++++++++++++----------------- src/tilde_proc.cpp | 49 ++++++++++++++------------- src/tilde_stmt.cpp | 92 +++++++++++++++++++++++++++++++++++++++++--------- 7 files changed, 184 insertions(+), 71 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.hpp b/src/tilde.hpp index 0e5b3b551..b8434ce4b 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -196,6 +196,8 @@ struct cgProcedure { Scope *curr_scope; i32 scope_index; bool in_multi_assignment; + isize split_returns_index; + bool return_by_ptr; PtrMap variable_map; diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index a3c6ba044..f50666cff 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index 08c3f7bdd..d6e161ec3 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -91,6 +91,18 @@ gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { return res; } +gb_internal cgValue cg_builtin_min(cgProcedure *p, Type *t, cgValue x, cgValue y) { + x = cg_emit_conv(p, x, t); + y = cg_emit_conv(p, y, t); + return cg_emit_select(p, cg_emit_comp(p, Token_Lt, x, y), x, y); +} +gb_internal cgValue cg_builtin_max(cgProcedure *p, Type *t, cgValue x, cgValue y) { + x = cg_emit_conv(p, x, t); + y = cg_emit_conv(p, y, t); + return cg_emit_select(p, cg_emit_comp(p, Token_Gt, x, y), x, y); +} + + gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -137,6 +149,32 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr return cg_builtin_len(p, v); } + case BuiltinProc_min: + if (ce->args.count == 2) { + Type *t = type_of_expr(expr); + return cg_builtin_min(p, t, cg_build_expr(p, ce->args[0]), cg_build_expr(p, ce->args[1])); + } else { + Type *t = type_of_expr(expr); + cgValue x = cg_build_expr(p, ce->args[0]); + for (isize i = 1; i < ce->args.count; i++) { + x = cg_builtin_min(p, t, x, cg_build_expr(p, ce->args[i])); + } + return x; + } + break; + case BuiltinProc_max: + if (ce->args.count == 2) { + Type *t = type_of_expr(expr); + return cg_builtin_max(p, t, cg_build_expr(p, ce->args[0]), cg_build_expr(p, ce->args[1])); + } else { + Type *t = type_of_expr(expr); + cgValue x = cg_build_expr(p, ce->args[0]); + for (isize i = 1; i < ce->args.count; i++) { + x = cg_builtin_max(p, t, x, cg_build_expr(p, ce->args[i])); + } + return x; + } + break; } diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index e3b45ff1b..21594ef07 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -1,5 +1,7 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type); gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type) { + type = reduce_tuple_to_single_type(type); + mutex_lock(&m->debug_type_mutex); defer (mutex_unlock(&m->debug_type_mutex)); TB_DebugType **found = map_get(&m->debug_type_map, type); @@ -235,7 +237,8 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { case Basic_uint: return tb_debug_get_integer(m->mod, is_signed, bits); case Basic_uintptr: return tb_debug_get_integer(m->mod, is_signed, bits); - case Basic_rawptr: return tb_debug_create_ptr(m->mod, tb_debug_get_void(m->mod)); + case Basic_rawptr: + return tb_debug_create_ptr(m->mod, tb_debug_get_void(m->mod)); case Basic_string: { String name = basic_types[type->Basic.kind].Basic.name; diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 3d9054803..b6dbce181 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -15,6 +15,15 @@ gb_internal cgValue cg_flatten_value(cgProcedure *p, cgValue value) { return value; } +gb_internal cgValue cg_emit_select(cgProcedure *p, cgValue const &cond, cgValue const &x, cgValue const &y) { + GB_ASSERT(x.kind == y.kind); + GB_ASSERT(cond.kind == cgValue_Value); + cgValue res = x; + res.node = tb_inst_select(p->func, cond.node, x.node, y.node); + return res; +} + + gb_internal bool cg_is_expr_untyped_const(Ast *expr) { auto const &tv = type_and_value_of_expr(expr); if (is_type_untyped(tv.type)) { @@ -1724,36 +1733,35 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { case Token_CmpEq: case Token_NotEq: - GB_PANIC("TODO(bill): comparisons"); - // if (is_type_untyped_nil(be->right->tav.type)) { - // // `x == nil` or `x != nil` - // cgValue left = cg_build_expr(p, be->left); - // cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, left); - // Type *type = default_type(tv.type); - // return cg_emit_conv(p, cmp, type); - // } else if (is_type_untyped_nil(be->left->tav.type)) { - // // `nil == x` or `nil != x` - // cgValue right = cg_build_expr(p, be->right); - // cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, right); - // Type *type = default_type(tv.type); - // return cg_emit_conv(p, cmp, type); - // } else if (cg_is_empty_string_constant(be->right)) { - // // `x == ""` or `x != ""` - // cgValue s = cg_build_expr(p, be->left); - // s = cg_emit_conv(p, s, t_string); - // cgValue len = cg_string_len(p, s); - // cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); - // Type *type = default_type(tv.type); - // return cg_emit_conv(p, cmp, type); - // } else if (cg_is_empty_string_constant(be->left)) { - // // `"" == x` or `"" != x` - // cgValue s = cg_build_expr(p, be->right); - // s = cg_emit_conv(p, s, t_string); - // cgValue len = cg_string_len(p, s); - // cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); - // Type *type = default_type(tv.type); - // return cg_emit_conv(p, cmp, type); - // } + if (is_type_untyped_nil(be->right->tav.type)) { + // `x == nil` or `x != nil` + cgValue left = cg_build_expr(p, be->left); + cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, left); + Type *type = default_type(tv.type); + return cg_emit_conv(p, cmp, type); + } else if (is_type_untyped_nil(be->left->tav.type)) { + // `nil == x` or `nil != x` + cgValue right = cg_build_expr(p, be->right); + cgValue cmp = cg_emit_comp_against_nil(p, be->op.kind, right); + Type *type = default_type(tv.type); + return cg_emit_conv(p, cmp, type); + }/* else if (cg_is_empty_string_constant(be->right)) { + // `x == ""` or `x != ""` + cgValue s = cg_build_expr(p, be->left); + s = cg_emit_conv(p, s, t_string); + cgValue len = cg_string_len(p, s); + cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); + Type *type = default_type(tv.type); + return cg_emit_conv(p, cmp, type); + } else if (cg_is_empty_string_constant(be->left)) { + // `"" == x` or `"" != x` + cgValue s = cg_build_expr(p, be->right); + s = cg_emit_conv(p, s, t_string); + cgValue len = cg_string_len(p, s); + cgValue cmp = cg_emit_comp(p, be->op.kind, len, cg_const_int(p->module, t_int, 0)); + Type *type = default_type(tv.type); + return cg_emit_conv(p, cmp, type); + }*/ /*fallthrough*/ case Token_Lt: case Token_LtEq: @@ -2255,7 +2263,6 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { token_pos_to_string(token.pos)); return {}; } else if (e->kind == Entity_Nil) { - GB_PANIC("TODO: cg_find_ident nil"); // TODO(bill): is this correct? return cg_value(cast(TB_Node *)nullptr, e->type); } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 7c7bda197..41c185dc6 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -63,6 +63,7 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i p->is_foreign = entity->Procedure.is_foreign; p->is_export = entity->Procedure.is_export; p->is_entry_point = false; + p->split_returns_index = -1; gbAllocator a = heap_allocator(); p->children.allocator = a; @@ -122,6 +123,7 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li p->is_foreign = false; p->is_export = false; p->is_entry_point = false; + p->split_returns_index = -1; gbAllocator a = heap_allocator(); p->children.allocator = a; @@ -188,6 +190,7 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { TB_DebugType *debug_type = cg_debug_type(p->module, result_type); TB_PassingRule rule = tb_get_passing_rule_from_dbg(p->module->mod, debug_type, true); if (rule == TB_PASSING_INDIRECT) { + p->return_by_ptr = true; param_index++; } } @@ -272,7 +275,7 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } } - // isize split_offset = param_index; + p->split_returns_index = param_index; if (pt->calling_convention == ProcCC_Odin) { // NOTE(bill): Push context on to stack from implicit parameter @@ -323,24 +326,6 @@ gb_internal void cg_procedure_end(cgProcedure *p) { tb_inst_ret(p->func, 0, nullptr); } bool emit_asm = false; - // if (p->name == "main") { - if ( - p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || - // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || - // p->name == "main" || - false - ) { - TB_Arena *arena = tb_default_arena(); - defer (arena->free(arena)); - TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - defer (tb_funcopt_exit(opt)); - tb_funcopt_print(opt); - - // emit_asm = true; - - // GraphViz printing - // tb_function_print(p->func, tb_default_print_callback, stdout); - } TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); if (emit_asm) { TB_Assembly *assembly = tb_output_get_asm(output); @@ -361,17 +346,33 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { return; } + bool build_body = false; + if ( - p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || + string_starts_with(p->name, str_lit("runtime" ABI_PKG_NAME_SEPARATOR "_os_write")) || // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || // p->name == "main" || false ) { + build_body = true; + } + + if (build_body) { cg_procedure_begin(p); cg_build_stmt(p, p->body); } - cg_procedure_end(p); + + if (build_body) { + TB_Arena *arena = tb_default_arena(); + defer (arena->free(arena)); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + tb_funcopt_print(opt); + + // GraphViz printing + // tb_function_print(p->func, tb_default_print_callback, stdout); + } } @@ -543,9 +544,11 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice case 1: if (return_is_indirect) { return cg_lvalue_addr(params[0], pt->results->Tuple.variables[0]->type); + } else { + GB_ASSERT(multi_output.count == 1); + TB_Node *node = multi_output.single; + return cg_value(node, pt->results->Tuple.variables[0]->type); } - GB_ASSERT(multi_output.count == 1); - return cg_value(multi_output.single, pt->results->Tuple.variables[0]->type); } cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 4fc00dd28..074d2674c 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1011,31 +1011,91 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { TypeTuple *tuple = &p->type->Proc.results->Tuple; isize return_count = p->type->Proc.result_count; - gb_unused(tuple); - isize res_count = return_results.count; - gb_unused(res_count); if (return_count == 0) { tb_inst_ret(p->func, 0, nullptr); return; - } else if (return_count == 1) { - Entity *e = tuple->variables[0]; - if (res_count == 0) { - cgValue zero = cg_const_nil(p, tuple->variables[0]->type); - if (zero.kind == cgValue_Value) { - tb_inst_ret(p->func, 1, &zero.node); + } + TEMPORARY_ALLOCATOR_GUARD(); + + auto results = array_make(temporary_allocator(), 0, return_count); + + if (return_results.count != 0) { + for (isize i = 0; i < return_results.count; i++) { + cgValue res = cg_build_expr(p, return_results[i]); + cg_append_tuple_values(p, &results, res); + } + } else { + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cgValue res = cg_addr_load(p, addr); + array_add(&results, res); + } + } + GB_ASSERT(results.count == return_count); + + if (return_results.count != 0 && p->type->Proc.has_named_results) { + // NOTE(bill): store the named values before returning + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cg_addr_store(p, addr, results[i]); + } + } + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + results[i] = cg_emit_conv(p, results[i], e->type); + } + + + if (p->split_returns_index >= 0) { + GB_ASSERT(is_calling_convention_odin(p->type->Proc.calling_convention)); + + for (isize i = 0; i < return_count-1; i++) { + Entity *e = tuple->variables[i]; + TB_Node *ret_ptr = tb_inst_param(p->func, cast(int)(p->split_returns_index+i)); + cgValue ptr = cg_value(ret_ptr, alloc_type_pointer(e->type)); + cg_emit_store(p, ptr, results[i]); + } + + if (p->return_by_ptr) { + Entity *e = tuple->variables[return_count-1]; + TB_Node *ret_ptr = tb_inst_param(p->func, 0); + cgValue ptr = cg_value(ret_ptr, alloc_type_pointer(e->type)); + cg_emit_store(p, ptr, results[return_count-1]); + + tb_inst_ret(p->func, 0, nullptr); + return; + } else { + GB_ASSERT(p->proto->return_count == 1); + TB_DataType dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; + + cgValue result = cg_flatten_value(p, results[0]); + TB_Node *final_res = nullptr; + if (result.kind == cgValue_Addr) { + TB_CharUnits align = cast(TB_CharUnits)type_align_of(result.type); + final_res = tb_inst_load(p->func, dt, result.node, align, false); + } else { + GB_ASSERT(result.kind == cgValue_Value); + if (result.node->dt.raw == dt.raw) { + final_res = result.node; + } else { + final_res = tb_inst_bitcast(p->func, result.node, dt); + } } + GB_ASSERT(final_res != nullptr); + + tb_inst_ret(p->func, 1, &final_res); return; } - cgValue res = cg_build_expr(p, return_results[0]); - res = cg_emit_conv(p, res, e->type); - if (res.kind == cgValue_Value) { - tb_inst_ret(p->func, 1, &res.node); - } - return; + } else { - GB_PANIC("TODO(bill): MUTLIPLE RETURN VALUES"); + GB_ASSERT(!is_calling_convention_odin(p->type->Proc.calling_convention)); } + + + GB_PANIC("TODO(bill): %.*s MUTLIPLE RETURN VALUES %td %td", LIT(p->name), results.count, return_results.count); } gb_internal void cg_build_if_stmt(cgProcedure *p, Ast *node) { -- cgit v1.2.3 From 99c812b02d31d8f827e299ff7bb4a5d0c59bed4b Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 23 Jul 2023 12:21:27 +0100 Subject: Begin working on a minimum build --- src/checker.cpp | 3 + src/tilde.cpp | 44 ++- src/tilde.hpp | 9 +- src/tilde/tb.lib | Bin 4162054 -> 4163308 bytes src/tilde_builtin.cpp | 133 +++++++ src/tilde_const.cpp | 109 ++++-- src/tilde_debug.cpp | 6 +- src/tilde_expr.cpp | 932 +++++++++++++++++++++++++++++++++++++++++++------- src/tilde_proc.cpp | 102 ++++-- src/tilde_stmt.cpp | 273 ++++++++++++--- 10 files changed, 1355 insertions(+), 256 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/checker.cpp b/src/checker.cpp index 01b8b6b2a..21fa80d9f 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1046,6 +1046,7 @@ gb_internal void init_universal(void) { add_global_bool_constant("ODIN_NO_RTTI", bc->no_rtti); add_global_bool_constant("ODIN_VALGRIND_SUPPORT", bc->ODIN_VALGRIND_SUPPORT); + add_global_bool_constant("ODIN_TILDE", bc->tilde_backend); add_global_constant("ODIN_COMPILE_TIMESTAMP", t_untyped_integer, exact_value_i64(odin_compile_timestamp())); @@ -2311,7 +2312,9 @@ gb_internal void generate_minimum_dependency_set(Checker *c, Entity *start) { str_lit("memory_equal"), str_lit("memory_compare"), str_lit("memory_compare_zero"), + ); + FORCE_ADD_RUNTIME_ENTITIES(!build_context.tilde_backend, // Extended data type internal procedures str_lit("umodti3"), str_lit("udivti3"), diff --git a/src/tilde.cpp b/src/tilde.cpp index 26bd69f4f..ff2a540f5 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -126,6 +126,19 @@ gb_internal cgValue cg_lvalue_addr(TB_Node *node, Type *type) { return v; } +gb_internal cgValue cg_lvalue_addr_to_value(cgValue v) { + if (v.kind == cgValue_Value) { + GB_ASSERT(is_type_pointer(v.type)); + GB_ASSERT(v.node->dt.type == TB_PTR); + } else { + GB_ASSERT(v.kind == cgValue_Addr); + GB_ASSERT(v.node->dt.type == TB_PTR); + v.kind = cgValue_Value; + v.type = alloc_type_pointer(v.type); + } + return v; +} + gb_internal cgValue cg_value_multi(cgValueMulti *multi, Type *type) { GB_ASSERT(type->kind == Type_Tuple); GB_ASSERT(multi != nullptr); @@ -138,6 +151,24 @@ gb_internal cgValue cg_value_multi(cgValueMulti *multi, Type *type) { return v; } +gb_internal cgValue cg_value_multi(Slice const &values, Type *type) { + cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); + multi->values = values; + return cg_value_multi(multi, type); +} + + +gb_internal cgValue cg_value_multi2(cgValue const &x, cgValue const &y, Type *type) { + GB_ASSERT(type->kind == Type_Tuple); + GB_ASSERT(type->Tuple.variables.count == 2); + cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); + multi->values = slice_make(permanent_allocator(), 2); + multi->values[0] = x; + multi->values[1] = y; + return cg_value_multi(multi, type); +} + + gb_internal cgAddr cg_addr(cgValue const &value) { GB_ASSERT(value.kind != cgValue_Multi); cgAddr addr = {}; @@ -151,10 +182,21 @@ gb_internal cgAddr cg_addr(cgValue const &value) { return addr; } +gb_internal void cg_set_debug_pos_from_node(cgProcedure *p, Ast *node) { + if (node) { + TokenPos pos = ast_token(node).pos; + TB_FileID *file_id = map_get(&p->module->file_id_map, cast(uintptr)pos.file_id); + if (file_id) { + tb_inst_set_location(p->func, *file_id, pos.line); + } + } +} + gb_internal void cg_add_entity(cgModule *m, Entity *e, cgValue const &val) { if (e) { rw_mutex_lock(&m->values_mutex); + GB_ASSERT(val.node != nullptr); map_set(&m->values, e, val); rw_mutex_unlock(&m->values_mutex); } @@ -744,7 +786,7 @@ gb_internal bool cg_generate_code(Checker *c) { } TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; - if (build_context.ODIN_DEBUG) { + if (build_context.ODIN_DEBUG || true) { switch (build_context.metrics.os) { case TargetOs_windows: debug_format = TB_DEBUGFMT_CODEVIEW; diff --git a/src/tilde.hpp b/src/tilde.hpp index b8434ce4b..8a29d4c90 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -272,6 +272,7 @@ gb_internal void cg_build_when_stmt(cgProcedure *p, AstWhenStmt *ws); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr); gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_addr_ptr(cgProcedure *p, Ast *expr); +gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block, TB_Node *false_block); gb_internal Type * cg_addr_type(cgAddr const &addr); gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr); @@ -279,13 +280,15 @@ gb_internal void cg_addr_store(cgProcedure *p, cgAddr addr, cgValue value); gb_internal cgValue cg_addr_get_ptr(cgProcedure *p, cgAddr const &addr); gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false); -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false); +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue src, bool is_volatile=false); gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgValue value); gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment); gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); +gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results); +gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results); gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); @@ -300,6 +303,7 @@ gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index); gb_internal cgValue cg_emit_array_epi(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection const &sel); +gb_internal cgValue cg_emit_struct_ev(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t); gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, cgValue x); @@ -315,4 +319,5 @@ gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_val gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos); gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value); -gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); \ No newline at end of file +gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); + diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index f50666cff..936675fda 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index d6e161ec3..c55cfbb75 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -61,6 +61,7 @@ gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); cgValue data_ptr = cg_emit_struct_ep(p, ptr, 0); res = cg_emit_load(p, data_ptr); + GB_ASSERT(is_type_multi_pointer(res.type)); } break; case Type_DynamicArray: @@ -82,7 +83,12 @@ gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { } break; case Type_Pointer: + GB_ASSERT(is_type_array_like(t->Pointer.elem)); + GB_ASSERT(value.kind == cgValue_Value); + res = cg_value(value.node, alloc_type_multi_pointer(base_array_type(t->Pointer.elem))); + break; case Type_MultiPointer: + GB_PANIC("TODO(bill) %s", type_to_string(value.type)); // res = cg_emit_conv(p, value, tv.type); break; @@ -102,6 +108,37 @@ gb_internal cgValue cg_builtin_max(cgProcedure *p, Type *t, cgValue x, cgValue y return cg_emit_select(p, cg_emit_comp(p, Token_Gt, x, y), x, y); } +gb_internal cgValue cg_builtin_abs(cgProcedure *p, cgValue x) { + if (is_type_unsigned(x.type)) { + return x; + } + + if (is_type_quaternion(x.type)) { + GB_PANIC("TODO(bill): abs quaternion"); + } else if (is_type_complex(x.type)) { + GB_PANIC("TODO(bill): abs complex"); + } + + TB_DataType dt = cg_data_type(x.type); + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + TB_Node *zero = nullptr; + if (dt.type == TB_FLOAT) { + if (dt.data == 32) { + zero = tb_inst_float32(p->func, 0); + } else if (dt.data == 64) { + zero = tb_inst_float64(p->func, 0); + } + } else { + zero = tb_inst_uint(p->func, dt, 0); + } + GB_ASSERT(zero != nullptr); + + cgValue cond = cg_emit_comp(p, Token_Lt, x, cg_value(zero, x.type)); + cgValue neg = cg_emit_unary_arith(p, Token_Sub, x, x.type); + return cg_emit_select(p, cond, neg, x); +} + + gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -149,6 +186,12 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr return cg_builtin_len(p, v); } + case BuiltinProc_raw_data: + { + cgValue v = cg_build_expr(p, ce->args[0]); + return cg_builtin_raw_data(p, v); + } + case BuiltinProc_min: if (ce->args.count == 2) { Type *t = type_of_expr(expr); @@ -176,6 +219,96 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr } break; + case BuiltinProc_abs: + { + cgValue x = cg_build_expr(p, ce->args[0]); + return cg_builtin_abs(p, x); + } + + case BuiltinProc_debug_trap: + tb_inst_debugbreak(p->func); + return {}; + case BuiltinProc_trap: + tb_inst_trap(p->func); + return {}; + + case BuiltinProc_mem_zero: + { + cgValue ptr = cg_build_expr(p, ce->args[0]); + cgValue len = cg_build_expr(p, ce->args[1]); + GB_ASSERT(ptr.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + tb_inst_memzero(p->func, ptr.node, len.node, 1, false); + return {}; + } + + case BuiltinProc_mem_copy: + { + cgValue dst = cg_build_expr(p, ce->args[0]); + cgValue src = cg_build_expr(p, ce->args[1]); + cgValue len = cg_build_expr(p, ce->args[2]); + GB_ASSERT(dst.kind == cgValue_Value); + GB_ASSERT(src.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + // TODO(bill): This needs to be memmove + tb_inst_memcpy(p->func, dst.node, src.node, len.node, 1, false); + return {}; + } + + case BuiltinProc_mem_copy_non_overlapping: + { + cgValue dst = cg_build_expr(p, ce->args[0]); + cgValue src = cg_build_expr(p, ce->args[1]); + cgValue len = cg_build_expr(p, ce->args[2]); + GB_ASSERT(dst.kind == cgValue_Value); + GB_ASSERT(src.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + tb_inst_memcpy(p->func, dst.node, src.node, len.node, 1, false); + return {}; + } + + + case BuiltinProc_overflow_add: + { + Type *res_type = type_of_expr(expr); + GB_ASSERT(res_type->kind == Type_Tuple); + GB_ASSERT(res_type->Tuple.variables.count == 2); + // TODO(bill): do a proper overflow add + Type *type = res_type->Tuple.variables[0]->type; + Type *ok_type = res_type->Tuple.variables[1]->type; + cgValue x = cg_build_expr(p, ce->args[0]); + cgValue y = cg_build_expr(p, ce->args[1]); + x = cg_emit_conv(p, x, type); + y = cg_emit_conv(p, y, type); + cgValue res = cg_emit_arith(p, Token_Add, x, y, type); + cgValue ok = cg_const_int(p, ok_type, false); + + return cg_value_multi2(res, ok, res_type); + } + + + case BuiltinProc_ptr_offset: + { + cgValue ptr = cg_build_expr(p, ce->args[0]); + cgValue len = cg_build_expr(p, ce->args[1]); + len = cg_emit_conv(p, len, t_int); + return cg_emit_ptr_offset(p, ptr, len); + } + case BuiltinProc_ptr_sub: + { + Type *elem0 = type_deref(type_of_expr(ce->args[0])); + Type *elem1 = type_deref(type_of_expr(ce->args[1])); + GB_ASSERT(are_types_identical(elem0, elem1)); + Type *elem = elem0; + + cgValue ptr0 = cg_emit_conv(p, cg_build_expr(p, ce->args[0]), t_uintptr); + cgValue ptr1 = cg_emit_conv(p, cg_build_expr(p, ce->args[1]), t_uintptr); + + cgValue diff = cg_emit_arith(p, Token_Sub, ptr0, ptr1, t_uintptr); + diff = cg_emit_conv(p, diff, t_int); + return cg_emit_arith(p, Token_Quo, diff, cg_const_int(p, t_int, type_size_of(elem)), t_int); + } + } diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 6b1fb5c92..bb4a294a5 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -52,6 +52,13 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { } +gb_internal cgValue cg_emit_source_code_location_as_global(cgProcedure *p, String const &proc_name, TokenPos pos) { + // TODO(bill): cg_emit_source_code_location_as_global + return cg_const_nil(p, t_source_code_location); +} + + + gb_internal void cg_write_big_int_at_ptr(void *dst, BigInt const *a, Type *original_type) { GB_ASSERT(build_context.endian_kind == TargetEndian_Little); size_t sz = cast(size_t)type_size_of(original_type); @@ -109,7 +116,6 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty char name[32] = {}; gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *str_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); i64 size = str.len+1; tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, size, 1, 1); @@ -125,6 +131,7 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty } if (global == nullptr) { + gb_snprintf(name, 31, "cstr$%u", 1+m->const_nil_guid.fetch_add(1)); global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(type), type_align_of(type), 2); } @@ -778,18 +785,47 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ } -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { +gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { + GB_ASSERT(p != nullptr); TB_Node *node = nullptr; + if (is_type_untyped(type)) { + // TODO(bill): THIS IS A COMPLETE HACK, WHY DOES THIS NOT A TYPE? + GB_ASSERT(type->kind == Type_Basic); + switch (type->Basic.kind) { + case Basic_UntypedBool: + type = t_bool; + break; + case Basic_UntypedInteger: + type = t_i64; + break; + case Basic_UntypedFloat: + type = t_f64; + break; + case Basic_UntypedComplex: + type = t_complex128; + break; + case Basic_UntypedQuaternion: + type = t_quaternion256; + break; + case Basic_UntypedString: + type = t_string; + break; + case Basic_UntypedRune: + type = t_rune; + break; + case Basic_UntypedNil: + case Basic_UntypedUninit: + return cg_value(cast(TB_Node *)nullptr, type); + } + } TB_DataType dt = cg_data_type(type); switch (value.kind) { case ExactValue_Invalid: - GB_ASSERT(p != nullptr); return cg_const_nil(p, type); case ExactValue_Typeid: - GB_ASSERT(p != nullptr); return cg_typeid(p, value.value_typeid); case ExactValue_Procedure: @@ -797,13 +833,13 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac Ast *expr = unparen_expr(value.value_procedure); Entity *e = entity_of_node(expr); if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(m, e); - GB_ASSERT(are_types_identical(type, found.type)); + cgValue found = cg_find_procedure_value_from_entity(p->module, e); + GB_ASSERT_MSG(are_types_identical(type, found.type), + "%.*s %s == %s", + LIT(p->name), + type_to_string(type), type_to_string(found.type)); GB_ASSERT(found.kind == cgValue_Symbol); - if (p) { - return cg_flatten_value(p, found); - } - return found; + return cg_flatten_value(p, found); } GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); } @@ -812,12 +848,10 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac switch (value.kind) { case ExactValue_Bool: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { @@ -830,7 +864,6 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; case ExactValue_Float: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); GB_ASSERT(dt.raw != TB_TYPE_F16.raw); GB_ASSERT(!is_type_different_to_arch_endianness(type)); @@ -846,13 +879,36 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_String: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type, nullptr, 0); - if (p) { - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); - } else { - return cg_value(symbol, alloc_type_pointer(type)); + GB_ASSERT(is_type_string(type)); + cgModule *m = p->module; + + String str = value.value_string; + + char name[32] = {}; + gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *cstr_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + i64 size = str.len+1; + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), cstr_global, size, 1, 1); + u8 *data = cast(u8 *)tb_global_add_region(m->mod, cstr_global, 0, size); + gb_memcopy(data, str.text, str.len); + data[str.len] = 0; + + if (is_type_cstring(type)) { + cgValue s = cg_value(cstr_global, type); + return cg_flatten_value(p, s); } + + gb_snprintf(name, 31, "str$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *str_global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); + + tb_global_add_symbol_reloc(m->mod, str_global, 0, cast(TB_Symbol *)cstr_global); + void *len_ptr = tb_global_add_region(m->mod, str_global, build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, str.len, t_int); + + TB_Node *s = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)str_global); + return cg_lvalue_addr(s, type); + } case ExactValue_Pointer: @@ -860,13 +916,9 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_Compound: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(m, type, value, nullptr, 0); - if (p) { - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); - } else { - return cg_value(symbol, type); - } + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(p->module, type, value, nullptr, 0); + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); } break; } @@ -876,11 +928,6 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_value(node, type); } -gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { - GB_ASSERT(p != nullptr); - return cg_const_value(p->module, p, type, value); -} - gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { return cg_const_value(p, type, exact_value_i64(i)); } diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index 21594ef07..e6e60be96 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -368,7 +368,11 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { param_count += 1; } - TB_DebugType *func = tb_debug_create_func(m->mod, TB_CDECL, param_count, return_count, pt->c_vararg); + TB_CallingConv tb_cc = TB_CDECL; + if (pt->calling_convention == ProcCC_StdCall) { + tb_cc = TB_STDCALL; + } + TB_DebugType *func = tb_debug_create_func(m->mod, tb_cc, param_count, return_count, pt->c_vararg); map_set(&m->proc_debug_type_map, original_type, func); map_set(&m->proc_debug_type_map, type, func); diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index b6dbce181..822c637ca 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -648,21 +648,22 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, break; case Basic_any: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); + GB_ASSERT(x.kind == cgValue_Addr); // // TODO(bill): is this correct behaviour for nil comparison for any? - // cgValue data = cg_emit_struct_ev(p, x, 0); - // cgValue ti = cg_emit_struct_ev(p, x, 1); - // if (op_kind == Token_CmpEq) { - // LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, ""); - // LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, ""); - // res.value = LLVMBuildOr(p->builder, a, b, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, ""); - // LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, ""); - // res.value = LLVMBuildAnd(p->builder, a, b, ""); - // return res; - // } + cgValue data = cg_emit_struct_ev(p, x, 0); + cgValue id = cg_emit_struct_ev(p, x, 1); + + if (op_kind == Token_CmpEq) { + TB_Node *a = tb_inst_cmp_eq(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + TB_Node *b = tb_inst_cmp_eq(p->func, id.node, tb_inst_uint(p->func, id.node->dt, 0)); + TB_Node *c = tb_inst_or(p->func, a, b); + return cg_value(c, t_bool); + } else if (op_kind == Token_NotEq) { + TB_Node *a = tb_inst_cmp_ne(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + TB_Node *b = tb_inst_cmp_ne(p->func, id.node, tb_inst_uint(p->func, id.node->dt, 0)); + TB_Node *c = tb_inst_and(p->func, a, b); + return cg_value(c, t_bool); + } } break; case Basic_typeid: @@ -685,64 +686,33 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, break; case Type_Slice: - { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data = cg_emit_struct_ev(p, x, 0); - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data.value, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // res.value = LLVMBuildIsNotNull(p->builder, data.value, ""); - // return res; - // } - } - break; - case Type_DynamicArray: - { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data = cg_emit_struct_ev(p, x, 0); - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data.value, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // res.value = LLVMBuildIsNotNull(p->builder, data.value, ""); - // return res; - // } - } - break; - case Type_Map: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data_ptr = cg_emit_struct_ev(p, x, 0); - - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data_ptr.value, ""); - // return res; - // } else { - // res.value = LLVMBuildIsNotNull(p->builder, data_ptr.value, ""); - // return res; - // } + // NOTE(bill): all of their data "pointer-like" fields are at the 0-index + cgValue data = cg_emit_struct_ev(p, x, 0); + if (op_kind == Token_CmpEq) { + TB_Node *a = tb_inst_cmp_eq(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + return cg_value(a, t_bool); + } else if (op_kind == Token_NotEq) { + TB_Node *a = tb_inst_cmp_ne(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + return cg_value(a, t_bool); + } } break; case Type_Union: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // if (type_size_of(t) == 0) { - // if (op_kind == Token_CmpEq) { - // return cg_const_bool(p->module, t_bool, true); - // } else if (op_kind == Token_NotEq) { - // return cg_const_bool(p->module, t_bool, false); - // } - // } else if (is_type_union_maybe_pointer(t)) { - // cgValue tag = cg_emit_transmute(p, x, t_rawptr); - // return cg_emit_comp_against_nil(p, op_kind, tag); - // } else { - // cgValue tag = cg_emit_union_tag_value(p, x); - // return cg_emit_comp(p, op_kind, tag, cg_zero(p->module, tag.type)); - // } + if (type_size_of(t) == 0) { + return cg_const_bool(p, t_bool, op_kind == Token_CmpEq); + } else if (is_type_union_maybe_pointer(t)) { + cgValue tag = cg_emit_transmute(p, x, t_rawptr); + return cg_emit_comp_against_nil(p, op_kind, tag); + } else { + GB_ASSERT("TODO(bill): cg_emit_union_tag_value"); + // cgValue tag = cg_emit_union_tag_value(p, x); + // return cg_emit_comp(p, op_kind, tag, cg_zero(p->module, tag.type)); + } } break; case Type_Struct: @@ -1311,6 +1281,17 @@ handle_op:; } +gb_internal void cg_fill_slice(cgProcedure *p, cgAddr const &slice, cgValue data, cgValue len) { + cgValue slice_ptr = cg_addr_get_ptr(p, slice); + cgValue data_ptr = cg_emit_struct_ep(p, slice_ptr, 0); + cgValue len_ptr = cg_emit_struct_ep(p, slice_ptr, 1); + + data = cg_emit_conv(p, data, type_deref(data_ptr.type)); + len = cg_emit_conv(p, len, t_int); + cg_emit_store(p, data_ptr, data); + cg_emit_store(p, len_ptr, len); +} + gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { ast_node(se, SliceExpr, expr); @@ -1338,23 +1319,28 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { } switch (type->kind) { + case Type_Basic: case Type_Slice: { - // Type *slice_type = type; - // cgValue len = cg_slice_len(p, base); - // if (high.value == nullptr) high = len; + if (type->kind == Type_Basic) { + GB_ASSERT(type->Basic.kind == Basic_string); + } - // if (!no_indices) { - // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); - // } + Type *slice_type = type; + if (high.node == nullptr) { + cgValue len = cg_builtin_len(p, base); + high = len; + } - // cgValue elem = cg_emit_ptr_offset(p, cg_slice_elem(p, base), low); - // cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + if (!no_indices) { + // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + } - // cgAddr slice = cg_add_local_generated(p, slice_type, false); - // cg_fill_slice(p, slice, elem, new_len); - // return slice; - GB_PANIC("cg_build_addr_slice_expr Type_Slice"); - break; + cgValue elem = cg_emit_ptr_offset(p, cg_builtin_raw_data(p, base), low); + cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cg_fill_slice(p, slice, elem, new_len); + return slice; } case Type_RelativeSlice: @@ -1414,46 +1400,24 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { } case Type_Array: { - // Type *slice_type = alloc_type_slice(type->Array.elem); - // lbValue len = lb_const_int(p->module, t_int, type->Array.count); - - // if (high.value == nullptr) high = len; + Type *slice_type = type_of_expr(expr); + GB_ASSERT(is_type_slice(slice_type)); + cgValue len = cg_const_int(p, t_int, type->Array.count); + if (high.node == nullptr) high = len; // bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant; // bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant; - // if (!low_const || !high_const) { // if (!no_indices) { // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); // } // } - // lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low); - // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + cgValue elem = cg_emit_ptr_offset(p, cg_builtin_raw_data(p, cg_addr_get_ptr(p, addr)), low); + cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); - // lbAddr slice = lb_add_local_generated(p, slice_type, false); - // lb_fill_slice(p, slice, elem, new_len); - // return slice; - GB_PANIC("cg_build_addr_slice_expr Type_Array"); - break; - } - - case Type_Basic: { - // GB_ASSERT(type == t_string); - // lbValue len = lb_string_len(p, base); - // if (high.value == nullptr) high = len; - - // if (!no_indices) { - // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); - // } - - // lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low); - // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); - - // lbAddr str = lb_add_local_generated(p, t_string, false); - // lb_fill_string(p, str, elem, new_len); - // return str; - GB_PANIC("cg_build_addr_slice_expr Type_Basic"); - break; + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cg_fill_slice(p, slice, elem, new_len); + return slice; } @@ -1685,6 +1649,207 @@ gb_internal cgValue cg_emit_unary_arith(cgProcedure *p, TokenKind op, cgValue x, return res; } +gb_internal void cg_emit_if(cgProcedure *p, cgValue const &cond, TB_Node *true_region, TB_Node *false_region) { + GB_ASSERT(cond.kind == cgValue_Value); + tb_inst_if(p->func, cond.node, true_region, false_region); +} + +gb_internal void cg_build_try_lhs_rhs(cgProcedure *p, Ast *arg, Type *final_type, cgValue *lhs_, cgValue *rhs_) { + cgValue lhs = {}; + cgValue rhs = {}; + + cgValue value = cg_build_expr(p, arg); + if (value.kind == cgValue_Multi) { + auto const &values = value.multi->values; + if (values.count == 2) { + lhs = values[0]; + rhs = values[1]; + } else { + rhs = values[values.count-1]; + if (values.count > 1) { + lhs = cg_value_multi(slice(values, 0, values.count-1), final_type); + } + } + } else { + rhs = value; + } + + GB_ASSERT(rhs.node != nullptr); + + if (lhs_) *lhs_ = lhs; + if (rhs_) *rhs_ = rhs; +} + +gb_internal cgValue cg_emit_try_has_value(cgProcedure *p, cgValue rhs) { + cgValue has_value = {}; + if (is_type_boolean(rhs.type)) { + has_value = rhs; + } else { + GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type)); + has_value = cg_emit_comp_against_nil(p, Token_CmpEq, rhs); + } + GB_ASSERT(has_value.node != nullptr); + return has_value; +} + +gb_internal cgValue cg_build_or_return(cgProcedure *p, Ast *arg, Type *final_type) { + cgValue lhs = {}; + cgValue rhs = {}; + cg_build_try_lhs_rhs(p, arg, final_type, &lhs, &rhs); + + TB_Node *return_region = cg_control_region(p, "or_return_return"); + TB_Node *continue_region = cg_control_region(p, "or_return_continue"); + + cgValue cond = cg_emit_try_has_value(p, rhs); + cg_emit_if(p, cond, continue_region, return_region); + tb_inst_set_control(p->func, return_region); + { + Type *proc_type = base_type(p->type); + Type *results = proc_type->Proc.results; + GB_ASSERT(results != nullptr && results->kind == Type_Tuple); + TypeTuple *tuple = &results->Tuple; + + GB_ASSERT(tuple->variables.count != 0); + + Entity *end_entity = tuple->variables[tuple->variables.count-1]; + rhs = cg_emit_conv(p, rhs, end_entity->type); + if (p->type->Proc.has_named_results) { + GB_ASSERT(end_entity->token.string.len != 0); + + // NOTE(bill): store the named values before returning + cgAddr found = map_must_get(&p->variable_map, end_entity); + cg_addr_store(p, found, rhs); + + cg_build_return_stmt(p, {}); + } else { + GB_ASSERT(tuple->variables.count == 1); + Slice results = {}; + results.data = &rhs; + results.count = 1;; + cg_build_return_stmt_internal(p, results); + } + } + tb_inst_set_control(p->func, continue_region); + if (final_type != nullptr && !is_type_tuple(final_type)) { + return cg_emit_conv(p, lhs, final_type); + } + return {}; +} + +gb_internal cgValue cg_build_or_else(cgProcedure *p, Ast *arg, Ast *else_expr, Type *final_type) { + if (arg->state_flags & StateFlag_DirectiveWasFalse) { + return cg_build_expr(p, else_expr); + } + + cgValue lhs = {}; + cgValue rhs = {}; + cg_build_try_lhs_rhs(p, arg, final_type, &lhs, &rhs); + + GB_ASSERT(else_expr != nullptr); + + if (is_diverging_expr(else_expr)) { + TB_Node *then = cg_control_region(p, "or_else_then"); + TB_Node *else_ = cg_control_region(p, "or_else_else"); + + cg_emit_if(p, cg_emit_try_has_value(p, rhs), then, else_); + // NOTE(bill): else block needs to be straight afterwards to make sure that the actual value is used + // from the then block + tb_inst_set_control(p->func, else_); + + cg_build_expr(p, else_expr); + + tb_inst_set_control(p->func, then); + return cg_emit_conv(p, lhs, final_type); + } else { + TB_Node *incoming_values[2] = {}; + TB_Node *incoming_regions[2] = {}; + + TB_Node *then = cg_control_region(p, "or_else_then"); + TB_Node *done = cg_control_region(p, "or_else_done"); // NOTE(bill): Append later + TB_Node *else_ = cg_control_region(p, "or_else_else"); + + cg_emit_if(p, cg_emit_try_has_value(p, rhs), then, else_); + tb_inst_set_control(p->func, then); + + cgValue x = cg_emit_conv(p, lhs, final_type); + incoming_values[0] = x.node; + incoming_regions[0] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, else_); + + cgValue y = cg_emit_conv(p, cg_build_expr(p, else_expr), final_type); + incoming_values[1] = y.node; + incoming_regions[1] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + GB_ASSERT(x.kind == y.kind); + GB_ASSERT(incoming_values[0]->dt.raw == incoming_values[1]->dt.raw); + cgValue res = {}; + res.kind = x.kind; + res.type = final_type; + + res.node = tb_inst_incomplete_phi(p->func, incoming_values[0]->dt, done, 2); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[0], incoming_values[0]); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[1], incoming_values[1]); + return res; + } +} + + +gb_internal isize cg_control_region_pred_count(TB_Node *region) { + GB_ASSERT(region->type == TB_REGION); + GB_ASSERT(region->input_count > 0); + return region->input_count; +} + +gb_internal cgValue cg_build_logical_binary_expr(cgProcedure *p, TokenKind op, Ast *left, Ast *right, Type *final_type) { + TB_Node *rhs = cg_control_region(p, "logical_cmp_rhs"); + TB_Node *done = cg_control_region(p, "logical_cmp_done"); + + cgValue short_circuit = {}; + if (op == Token_CmpAnd) { + cg_build_cond(p, left, rhs, done); + short_circuit = cg_const_bool(p, t_bool, false); + } else if (op == Token_CmpOr) { + cg_build_cond(p, left, done, rhs); + short_circuit = cg_const_bool(p, t_bool, true); + } + + if (rhs->input_count == 0) { + tb_inst_set_control(p->func, done); + return cg_emit_conv(p, short_circuit, final_type); + } + + if (done->input_count == 0) { + tb_inst_set_control(p->func, rhs); + return cg_build_expr(p, right); + } + + tb_inst_set_control(p->func, rhs); + cgValue edge = cg_build_expr(p, right); + TB_Node *edge_region = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + TB_DataType dt = edge.node->dt; + TB_Node *phi = tb_inst_incomplete_phi(p->func, dt, done, done->input_count); + for (size_t i = 0; i < done->input_count; i++) { + TB_Node *val = short_circuit.node; + TB_Node *region = done->inputs[i]; + if (region == edge_region) { + val = edge.node; + } + tb_inst_add_phi_operand(p->func, phi, region, val); + } + return cg_emit_conv(p, cg_value(phi, t_bool), final_type); +} + + + gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { ast_node(be, BinaryExpr, expr); @@ -1786,8 +1951,7 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { case Token_CmpAnd: case Token_CmpOr: - GB_PANIC("TODO(bill): cg_emit_logical_binary_expr"); - // return cg_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); + return cg_build_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); case Token_in: case Token_not_in: @@ -1896,15 +2060,14 @@ gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block } else { v = cg_build_expr(p, cond); } - - GB_ASSERT(v.kind == cgValue_Value); - tb_inst_if(p->func, v.node, true_block, false_block); - + cg_emit_if(p, v, true_block, false_block); return v; } gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { + cg_set_debug_pos_from_node(p, expr); + u16 prev_state_flags = p->state_flags; defer (p->state_flags = prev_state_flags); @@ -2003,6 +2166,468 @@ gb_internal cgValue cg_find_ident(cgProcedure *p, Entity *e, Ast *expr) { return {}; } +cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { + struct cgCompoundLitElemTempData { + Ast * expr; + cgValue value; + i64 elem_index; + i64 elem_length; + cgValue gep; + }; + + + auto const &populate = [](cgProcedure *p, Slice const &elems, Array *temp_data, Type *compound_type) { + Type *bt = base_type(compound_type); + Type *et = nullptr; + switch (bt->kind) { + case Type_Array: et = bt->Array.elem; break; + case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break; + case Type_Slice: et = bt->Slice.elem; break; + case Type_BitSet: et = bt->BitSet.elem; break; + case Type_DynamicArray: et = bt->DynamicArray.elem; break; + case Type_SimdVector: et = bt->SimdVector.elem; break; + case Type_Matrix: et = bt->Matrix.elem; break; + } + GB_ASSERT(et != nullptr); + + + // NOTE(bill): Separate value, gep, store into their own chunks + for_array(i, elems) { + Ast *elem = elems[i]; + if (elem->kind == Ast_FieldValue) { + 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; + } + + cgValue value = cg_emit_conv(p, cg_build_expr(p, fv->value), et); + + GB_ASSERT((hi-lo) > 0); + + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // for (i64 k = lo; k < hi; k++) { + // cgCompoundLitElemTempData data = {}; + // data.value = value; + + // data.elem_index = matrix_row_major_index_to_offset(bt, k); + // array_add(temp_data, data); + // } + } else { + enum {MAX_ELEMENT_AMOUNT = 32}; + if ((hi-lo) <= MAX_ELEMENT_AMOUNT) { + for (i64 k = lo; k < hi; k++) { + cgCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = k; + array_add(temp_data, data); + } + } else { + cgCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = lo; + data.elem_length = hi-lo; + 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); + + cgValue value = cg_emit_conv(p, cg_build_expr(p, fv->value), et); + GB_ASSERT(!is_type_tuple(value.type)); + + cgCompoundLitElemTempData data = {}; + data.value = value; + data.expr = fv->value; + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // data.elem_index = matrix_row_major_index_to_offset(bt, index); + } else { + data.elem_index = index; + } + array_add(temp_data, data); + } + + } else { + // if (bt->kind != Type_DynamicArray && lb_is_elem_const(elem, et)) { + // continue; + // } + + cgValue field_expr = cg_build_expr(p, elem); + GB_ASSERT(!is_type_tuple(field_expr.type)); + + cgValue ev = cg_emit_conv(p, field_expr, et); + + cgCompoundLitElemTempData data = {}; + data.value = ev; + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // data.elem_index = matrix_row_major_index_to_offset(bt, i); + } else { + data.elem_index = i; + } + array_add(temp_data, data); + } + } + }; + + auto const &assign_array = [](cgProcedure *p, Array const &temp_data) { + for (auto const &td : temp_data) if (td.value.node != nullptr) { + if (td.elem_length > 0) { + GB_PANIC("TODO(bill): range"); + // auto loop_data = cg_loop_start(p, cast(isize)td.elem_length, t_i32); + // { + // cgValue dst = td.gep; + // dst = cg_emit_ptr_offset(p, dst, loop_data.idx); + // cg_emit_store(p, dst, td.value); + // } + // cg_loop_end(p, loop_data); + } else { + cg_emit_store(p, td.gep, td.value); + } + } + }; + + + + ast_node(cl, CompoundLit, expr); + + Type *type = type_of_expr(expr); + Type *bt = base_type(type); + + cgAddr v = cg_add_local(p, type, nullptr, true); + + if (cl->elems.count == 0) { + // No need to create it + return v; + } + + TEMPORARY_ALLOCATOR_GUARD(); + + Type *et = nullptr; + switch (bt->kind) { + case Type_Array: et = bt->Array.elem; break; + case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break; + 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 = {}; + if (p->entity) { + proc_name = p->entity->token.string; + } + TokenPos pos = ast_token(expr).pos; + + if (cl->elems.count == 0) { + } + + switch (bt->kind) { + default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break; + + case Type_Struct: { + TypeStruct *st = &bt->Struct; + cgValue comp_lit_ptr = cg_addr_get_ptr(p, v); + + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + + cgValue field_expr = {}; + Entity *field = nullptr; + isize index = field_index; + + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + String name = fv->field->Ident.token.string; + Selection sel = lookup_field(bt, name, false); + GB_ASSERT(!sel.indirect); + + elem = fv->value; + if (sel.index.count > 1) { + cgValue dst = cg_emit_deep_field_gep(p, comp_lit_ptr, sel); + field_expr = cg_build_expr(p, elem); + field_expr = cg_emit_conv(p, field_expr, sel.entity->type); + cg_emit_store(p, dst, field_expr); + continue; + } + + index = sel.index[0]; + } else { + Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_index); + GB_ASSERT(sel.index.count == 1); + GB_ASSERT(!sel.indirect); + index = sel.index[0]; + } + + field = st->fields[index]; + Type *ft = field->type; + + field_expr = cg_build_expr(p, elem); + + cgValue gep = {}; + if (st->is_raw_union) { + gep = cg_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft)); + } else { + gep = cg_emit_struct_ep(p, comp_lit_ptr, cast(i32)index); + } + + Type *fet = field_expr.type; + GB_ASSERT(fet->kind != Type_Tuple); + + // HACK TODO(bill): THIS IS A MASSIVE HACK!!!! + if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) { + GB_ASSERT_MSG(union_variant_index(ft, fet) >= 0, "%s", type_to_string(fet)); + + GB_PANIC("TODO(bill): cg_emit_store_union_variant"); + // cg_emit_store_union_variant(p, gep, field_expr, fet); + } else { + cgValue fv = cg_emit_conv(p, field_expr, ft); + cg_emit_store(p, gep, fv); + } + } + return v; + } + + // case Type_Map: { + // GB_ASSERT(!build_context.no_dynamic_literals); + + // cgValue err = cg_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos); + // gb_unused(err); + + // for (Ast *elem : cl->elems) { + // ast_node(fv, FieldValue, elem); + + // cgValue key = cg_build_expr(p, fv->field); + // cgValue value = cg_build_expr(p, fv->value); + // cg_internal_dynamic_map_set(p, v.addr, type, key, value, elem); + // } + // break; + // } + + // case Type_Array: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // for_array(i, temp_data) { + // i32 index = cast(i32)(temp_data[i].elem_index); + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + // } + + // assign_array(p, temp_data); + // break; + // } + // case Type_EnumeratedArray: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value); + // for_array(i, temp_data) { + // i32 index = cast(i32)(temp_data[i].elem_index - index_offset); + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + // } + + // assign_array(p, temp_data); + // break; + // } + case Type_Slice: { + isize count = gb_max(cl->elems.count, cl->max_count); + + TB_CharUnits backing_size = cast(TB_CharUnits)(type_size_of(bt->Slice.elem) * count); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(bt->Slice.elem); + TB_Node *backing = tb_inst_local(p->func, backing_size, align); + + cgValue data = cg_value(backing, alloc_type_multi_pointer(bt->Slice.elem)); + + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + populate(p, cl->elems, &temp_data, type); + + + for_array(i, temp_data) { + temp_data[i].gep = cg_emit_ptr_offset(p, data, cg_const_int(p, t_int, temp_data[i].elem_index)); + } + + assign_array(p, temp_data); + cg_fill_slice(p, v, data, cg_const_int(p, t_int, cl->max_count)); + return v; + } + + // case Type_DynamicArray: { + // GB_ASSERT(!build_context.no_dynamic_literals); + + // Type *et = bt->DynamicArray.elem; + // cgValue size = cg_const_int(p->module, t_int, type_size_of(et)); + // cgValue align = cg_const_int(p->module, t_int, type_align_of(et)); + + // i64 item_count = gb_max(cl->max_count, cl->elems.count); + // { + + // auto args = array_make(temporary_allocator(), 5); + // args[0] = cg_emit_conv(p, cg_addr_get_ptr(p, v), t_rawptr); + // args[1] = size; + // args[2] = align; + // args[3] = cg_const_int(p->module, t_int, item_count); + // args[4] = cg_emit_source_code_location_as_global(p, proc_name, pos); + // cg_emit_runtime_call(p, "__dynamic_array_reserve", args); + // } + + // cgValue items = cg_generate_local_array(p, et, item_count); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + // populate(p, cl->elems, &temp_data, type); + + // for_array(i, temp_data) { + // temp_data[i].gep = cg_emit_array_epi(p, items, temp_data[i].elem_index); + // } + // assign_array(p, temp_data); + + // { + // auto args = array_make(temporary_allocator(), 6); + // args[0] = cg_emit_conv(p, v.addr, t_rawptr); + // args[1] = size; + // args[2] = align; + // args[3] = cg_emit_conv(p, items, t_rawptr); + // args[4] = cg_const_int(p->module, t_int, item_count); + // args[5] = cg_emit_source_code_location_as_global(p, proc_name, pos); + // cg_emit_runtime_call(p, "__dynamic_array_append", args); + // } + // break; + // } + + // case Type_Basic: { + // GB_ASSERT(is_type_any(bt)); + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + // String field_names[2] = { + // str_lit("data"), + // str_lit("id"), + // }; + // Type *field_types[2] = { + // t_rawptr, + // t_typeid, + // }; + + // for_array(field_index, cl->elems) { + // Ast *elem = cl->elems[field_index]; + + // cgValue field_expr = {}; + // isize index = field_index; + + // if (elem->kind == Ast_FieldValue) { + // ast_node(fv, FieldValue, elem); + // Selection sel = lookup_field(bt, fv->field->Ident.token.string, false); + // index = sel.index[0]; + // elem = fv->value; + // } else { + // TypeAndValue tav = type_and_value_of_expr(elem); + // Selection sel = lookup_field(bt, field_names[field_index], false); + // index = sel.index[0]; + // } + + // field_expr = cg_build_expr(p, elem); + + // GB_ASSERT(field_expr.type->kind != Type_Tuple); + + // Type *ft = field_types[index]; + // cgValue fv = cg_emit_conv(p, field_expr, ft); + // cgValue gep = cg_emit_struct_ep(p, cg_addr_get_ptr(p, v), cast(i32)index); + // cg_emit_store(p, gep, fv); + // } + // break; + // } + + case Type_BitSet: { + i64 sz = type_size_of(type); + if (sz == 0) { + return v; + } + cgValue lower = cg_const_value(p, t_int, exact_value_i64(bt->BitSet.lower)); + Type *it = bit_set_to_int(bt); + cgValue one = cg_const_value(p, it, exact_value_i64(1)); + for (Ast *elem : cl->elems) { + GB_ASSERT(elem->kind != Ast_FieldValue); + + cgValue expr = cg_build_expr(p, elem); + GB_ASSERT(expr.type->kind != Type_Tuple); + + cgValue e = cg_emit_conv(p, expr, it); + e = cg_emit_arith(p, Token_Sub, e, lower, it); + e = cg_emit_arith(p, Token_Shl, one, e, it); + + cgValue old_value = cg_emit_transmute(p, cg_addr_load(p, v), it); + cgValue new_value = cg_emit_arith(p, Token_Or, old_value, e, it); + new_value = cg_emit_transmute(p, new_value, type); + cg_addr_store(p, v, new_value); + } + return v; + } + + // case Type_Matrix: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // for_array(i, temp_data) { + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, temp_data[i].elem_index); + // } + + // assign_array(p, temp_data); + // break; + // } + + // case Type_SimdVector: { + // cgValue vector_value = cg_const_value(p->module, type, exact_value_compound(expr)); + // defer (cg_addr_store(p, v, vector_value)); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector` + // // might be a better option + // for (auto const &td : temp_data) { + // if (td.value.value != nullptr) { + // if (td.elem_length > 0) { + // for (i64 k = 0; k < td.elem_length; k++) { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index + k).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + // } + // } else { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + + // } + // } + // } + // break; + // } + } + + return v; +} + gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { ast_node(ue, UnaryExpr, expr); auto tv = type_and_value_of_expr(expr); @@ -2020,12 +2645,12 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { // GB_ASSERT(t->kind == Type_Map); // ast_node(ie, IndexExpr, ue_expr); - // lbValue map_val = lb_build_addr_ptr(p, ie->expr); + // cgValue map_val = cg_build_addr_ptr(p, ie->expr); // if (deref) { - // map_val = lb_emit_load(p, map_val); + // map_val = cg_emit_load(p, map_val); // } - // lbValue key = lb_build_expr(p, ie->index); + // cgValue key = lb_build_expr(p, ie->index); // key = lb_emit_conv(p, key, t->Map.key); // lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value)); @@ -2053,18 +2678,8 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { // return lb_make_soa_pointer(p, tv.type, addr, index); } else if (ue_expr->kind == Ast_CompoundLit) { - cgValue v = cg_build_expr(p, ue->expr); - - Type *type = v.type; - cgAddr addr = {}; - // if (p->is_startup) { - // addr = cg_add_global_generated(p->module, type, v); - // } else { - addr = cg_add_local(p, type, nullptr, false); - // } - cg_addr_store(p, addr, v); + cgAddr addr = cg_build_addr_compound_lit(p, expr); return addr.addr; - } else if (ue_expr->kind == Ast_TypeAssertion) { GB_PANIC("TODO(bill): &v.(T)"); // if (is_type_tuple(tv.type)) { @@ -2225,7 +2840,8 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { Type *type = type_of_expr(expr); GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type)); - if (tv.value.kind != ExactValue_Invalid) { + if (tv.value.kind != ExactValue_Invalid && + expr->kind != Ast_CompoundLit) { // NOTE(bill): The commented out code below is just for debug purposes only // if (is_type_untyped(type)) { // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr); @@ -2314,6 +2930,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_build_call_expr(p, expr); case_end; + case_ast_node(cl, CompoundLit, expr); + cgAddr addr = cg_build_addr_compound_lit(p, expr); + return cg_addr_load(p, addr); + case_end; + case_ast_node(te, TernaryIfExpr, expr); cgValue incoming_values[2] = {}; @@ -2413,6 +3034,14 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(be, BinaryExpr, expr); return cg_build_binary_expr(p, expr); case_end; + + case_ast_node(oe, OrReturnExpr, expr); + return cg_build_or_return(p, oe->expr, tv.type); + case_end; + + case_ast_node(oe, OrElseExpr, expr); + return cg_build_or_else(p, oe->x, oe->y, tv.type); + case_end; } GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; @@ -2580,6 +3209,7 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { // cgValue len = cg_builtin_len(p, slice); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); return cg_addr(v); } @@ -2592,7 +3222,9 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { cgValue index = cg_build_expr(p, ie->index); index = cg_emit_conv(p, index, t_int); - return cg_addr(cg_emit_ptr_offset(p, multi_ptr, index)); + cgValue v = cg_emit_ptr_offset(p, multi_ptr, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); + return cg_addr(v); } case Type_RelativeSlice: { @@ -2624,6 +3256,7 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { // cgValue len = cg_dynamic_array_len(p, dynamic_array); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); return cg_addr(v); } @@ -2664,7 +3297,9 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); - return cg_addr(cg_emit_ptr_offset(p, elem, index)); + cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); + return cg_addr(v); } } return {}; @@ -2694,6 +3329,23 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { return cg_build_addr_from_entity(p, e, expr); case_end; + case_ast_node(de, DerefExpr, expr); + Type *t = type_of_expr(de->expr); + if (is_type_relative_pointer(t)) { + cgAddr addr = cg_build_addr(p, de->expr); + addr.relative.deref = true; + return addr; + } else if (is_type_soa_pointer(t)) { + cgValue value = cg_build_expr(p, de->expr); + cgValue ptr = cg_emit_struct_ev(p, value, 0); + cgValue idx = cg_emit_struct_ev(p, value, 1); + GB_PANIC("TODO(bill): cg_addr_soa_variable"); + // return cg_addr_soa_variable(ptr, idx, nullptr); + } + cgValue addr = cg_build_expr(p, de->expr); + return cg_addr(addr); + case_end; + case_ast_node(ie, IndexExpr, expr); return cg_build_addr_index_expr(p, expr); case_end; @@ -2804,6 +3456,7 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { if (sub_sel.index.count > 0) { item = cg_emit_deep_field_gep(p, item, sub_sel); } + item.type = alloc_type_pointer(type_deref(item.type, true)); return cg_addr(item); } else if (addr.kind == cgAddr_Swizzle) { GB_ASSERT(sel.index.count > 0); @@ -2821,6 +3474,23 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { } case_end; + case_ast_node(ce, CallExpr, expr); + cgValue res = cg_build_expr(p, expr); + switch (res.kind) { + case cgValue_Value: + return cg_addr(cg_address_from_load_or_generate_local(p, res)); + case cgValue_Addr: + return cg_addr(res); + case cgValue_Multi: + GB_PANIC("cannot address a multi-valued expression"); + break; + } + case_end; + + case_ast_node(cl, CompoundLit, expr); + return cg_build_addr_compound_lit(p, expr); + case_end; + } TokenPos token_pos = ast_token(expr).pos; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 41c185dc6..610d715ae 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -86,6 +86,10 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); } + if (p->name == "main") { + // TODO(bill): figure out when this should be public or not + linkage = TB_LINKAGE_PUBLIC; + } if (p->symbol == nullptr) { p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); @@ -97,9 +101,9 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i p->symbol = cast(TB_Symbol *)p->func; } - cgValue proc_value = cg_value(p->symbol, p->type); - cg_add_entity(m, entity, proc_value); - cg_add_member(m, p->name, proc_value); + p->value = cg_value(p->symbol, p->type); + cg_add_entity(m, entity, p->value); + cg_add_member(m, p->name, p->value); cg_add_procedure_value(m, p); @@ -275,7 +279,9 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } } - p->split_returns_index = param_index; + if (is_odin_like_cc) { + p->split_returns_index = param_index; + } if (pt->calling_convention == ProcCC_Odin) { // NOTE(bill): Push context on to stack from implicit parameter @@ -323,9 +329,15 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } if (tb_inst_get_control(p->func)) { + GB_ASSERT(p->type->Proc.result_count == 0); tb_inst_ret(p->func, 0, nullptr); } bool emit_asm = false; + + if (string_starts_with(p->name, str_lit("bug@main"))) { + // emit_asm = true; + } + TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); if (emit_asm) { TB_Assembly *assembly = tb_output_get_asm(output); @@ -336,47 +348,70 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } } -gb_global String procedures_to_generate_list[] = { - str_lit("bug" ABI_PKG_NAME_SEPARATOR "main"), - str_lit("main"), -}; - gb_internal void cg_procedure_generate(cgProcedure *p) { if (p->body == nullptr) { return; } - bool build_body = false; - - if ( - string_starts_with(p->name, str_lit("runtime" ABI_PKG_NAME_SEPARATOR "_os_write")) || - // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || - // p->name == "main" || - false - ) { - build_body = true; - } - - if (build_body) { - cg_procedure_begin(p); - cg_build_stmt(p, p->body); - } + cg_procedure_begin(p); + cg_build_stmt(p, p->body); cg_procedure_end(p); - if (build_body) { + if (string_starts_with(p->name, str_lit("bug@main"))) { // IR Printing TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); defer (tb_funcopt_exit(opt)); tb_funcopt_print(opt); + fprintf(stdout, "\n"); + } + if (false) { // GraphViz printing + tb_function_print(p->func, tb_default_print_callback, stdout); + } +} + +gb_internal void cg_build_nested_proc(cgProcedure *p, AstProcLit *pd, Entity *e) { + GB_ASSERT(pd->body != nullptr); + cgModule *m = p->module; + auto *min_dep_set = &m->info->minimum_dependency_set; + + if (ptr_set_exists(min_dep_set, e) == false) { + // NOTE(bill): Nothing depends upon it so doesn't need to be built + return; + } - // GraphViz printing - // tb_function_print(p->func, tb_default_print_callback, stdout); + // NOTE(bill): Generate a new name + // parent.name-guid + String original_name = e->token.string; + String pd_name = original_name; + if (e->Procedure.link_name.len > 0) { + pd_name = e->Procedure.link_name; } + + + isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1; + char *name_text = gb_alloc_array(permanent_allocator(), char, name_len); + + i32 guid = cast(i32)p->children.count; + name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid); + String name = make_string(cast(u8 *)name_text, name_len-1); + + e->Procedure.link_name = name; + + cgProcedure *nested_proc = cg_procedure_create(p->module, e); + e->cg_procedure = nested_proc; + + cgValue value = nested_proc->value; + + cg_add_entity(m, e, value); + array_add(&p->children, nested_proc); + array_add(&m->procedures_to_generate, nested_proc); } + + gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) { GB_ASSERT(is_type_proc(e->type)); e = strip_entity_wrapping(e); @@ -388,6 +423,7 @@ gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) found = map_get(&m->values, e); rw_mutex_shared_unlock(&m->values_mutex); if (found) { + GB_ASSERT(found->node != nullptr); return *found; } @@ -408,9 +444,6 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { GB_ASSERT(res.kind == cgValue_Multi); GB_ASSERT(res.multi->values.count == 2); return res.multi->values[0]; - // GB_ASSERT(is_type_tuple(res.type)); - // GB_ASSERT(res.type->Tuple.variables.count == 2); - // return cg_emit_struct_ev(p, res, 0); } return res; } @@ -470,8 +503,9 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice params[param_index++] = local; } } - for (cgValue arg : args) { - Type *param_type = param_entities[param_index]->type; + for_array(i, args) { + Type *param_type = param_entities[i]->type; + cgValue arg = args[i]; arg = cg_emit_conv(p, arg, param_type); arg = cg_flatten_value(p, arg); @@ -629,9 +663,7 @@ gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, if (p->entity != nullptr) { proc_name = p->entity->token.string; } - GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); - // return cg_emit_source_code_location_as_global(p, proc_name, pos); - break; + return cg_emit_source_code_location_as_global(p, proc_name, pos); } case ParameterValue_Value: return cg_build_expr(p, param_value.ast_value); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 074d2674c..b25be089d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -65,7 +65,7 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol return cg_value(tb_inst_load(p->func, dt, the_ptr, alignment, is_volatile), type); } -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile) { +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue src, bool is_volatile) { GB_ASSERT_MSG(dst.kind != cgValue_Multi, "cannot store to multiple values at once"); if (dst.kind == cgValue_Addr) { @@ -122,10 +122,14 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, return; } + switch (dst.kind) { case cgValue_Value: - switch (dst.kind) { + switch (src.kind) { case cgValue_Value: + if (src.node->dt.type == TB_INT && src.node->dt.data == 1) { + src.node = tb_inst_zxt(p->func, src.node, dt); + } tb_inst_store(p->func, dt, dst.node, src.node, alignment, is_volatile); return; case cgValue_Addr: @@ -367,8 +371,7 @@ gb_internal cgValue cg_emit_ptr_offset(cgProcedure *p, cgValue ptr, cgValue inde Type *elem = type_deref(ptr.type, true); i64 stride = type_size_of(elem); - ptr.node = tb_inst_array_access(p->func, ptr.node, index.node, stride); - return ptr; + return cg_value(tb_inst_array_access(p->func, ptr.node, index.node, stride), alloc_type_pointer(elem)); } gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index) { GB_ASSERT(s.kind == cgValue_Value); @@ -383,8 +386,7 @@ gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index) { Type *elem = base_array_type(st); i64 stride = type_size_of(elem); - s.node = tb_inst_array_access(p->func, s.node, index.node, stride); - return s; + return cg_value(tb_inst_array_access(p->func, s.node, index.node, stride), alloc_type_pointer(elem)); } gb_internal cgValue cg_emit_array_epi(cgProcedure *p, cgValue s, i64 index) { return cg_emit_array_ep(p, s, cg_const_int(p, t_int, index)); @@ -425,7 +427,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Type_Slice: switch (index) { case 0: - result_type = alloc_type_pointer(t->Slice.elem); + result_type = alloc_type_multi_pointer(t->Slice.elem); offset = 0; break; case 1: @@ -439,7 +441,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Basic_string: switch (index) { case 0: - result_type = t_u8_ptr; + result_type = t_u8_multi_ptr; offset = 0; break; case 1: @@ -494,7 +496,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Type_DynamicArray: switch (index) { case 0: - result_type = alloc_type_pointer(t->DynamicArray.elem); + result_type = alloc_type_multi_pointer(t->DynamicArray.elem); offset = index*int_size; break; case 1: case 2: @@ -564,6 +566,14 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { ); } + +gb_internal cgValue cg_emit_struct_ev(cgProcedure *p, cgValue s, i64 index) { + s = cg_address_from_load_or_generate_local(p, s); + cgValue ptr = cg_emit_struct_ep(p, s, index); + return cg_flatten_value(p, cg_emit_load(p, ptr)); +} + + gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection const &sel) { GB_ASSERT(sel.index.count > 0); Type *type = type_deref(e.type); @@ -1008,7 +1018,7 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { } } -gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { +gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results) { TypeTuple *tuple = &p->type->Proc.results->Tuple; isize return_count = p->type->Proc.result_count; @@ -1016,38 +1026,6 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return tb_inst_ret(p->func, 0, nullptr); return; } - TEMPORARY_ALLOCATOR_GUARD(); - - auto results = array_make(temporary_allocator(), 0, return_count); - - if (return_results.count != 0) { - for (isize i = 0; i < return_results.count; i++) { - cgValue res = cg_build_expr(p, return_results[i]); - cg_append_tuple_values(p, &results, res); - } - } else { - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - cgAddr addr = map_must_get(&p->variable_map, e); - cgValue res = cg_addr_load(p, addr); - array_add(&results, res); - } - } - GB_ASSERT(results.count == return_count); - - if (return_results.count != 0 && p->type->Proc.has_named_results) { - // NOTE(bill): store the named values before returning - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - cgAddr addr = map_must_get(&p->variable_map, e); - cg_addr_store(p, addr, results[i]); - } - } - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - results[i] = cg_emit_conv(p, results[i], e->type); - } - if (p->split_returns_index >= 0) { GB_ASSERT(is_calling_convention_odin(p->type->Proc.calling_convention)); @@ -1071,15 +1049,20 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return GB_ASSERT(p->proto->return_count == 1); TB_DataType dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; - cgValue result = cg_flatten_value(p, results[0]); + cgValue result = results[return_count-1]; + result = cg_flatten_value(p, result); TB_Node *final_res = nullptr; if (result.kind == cgValue_Addr) { TB_CharUnits align = cast(TB_CharUnits)type_align_of(result.type); final_res = tb_inst_load(p->func, dt, result.node, align, false); } else { GB_ASSERT(result.kind == cgValue_Value); - if (result.node->dt.raw == dt.raw) { + TB_DataType st = result.node->dt; + GB_ASSERT(st.type == dt.type); + if (st.raw == dt.raw) { final_res = result.node; + } else if (st.type == TB_INT && st.data == 1) { + final_res = tb_inst_zxt(p->func, result.node, dt); } else { final_res = tb_inst_bitcast(p->func, result.node, dt); } @@ -1092,10 +1075,94 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return } else { GB_ASSERT(!is_calling_convention_odin(p->type->Proc.calling_convention)); + + if (p->return_by_ptr) { + Entity *e = tuple->variables[return_count-1]; + TB_Node *ret_ptr = tb_inst_param(p->func, 0); + cgValue ptr = cg_value(ret_ptr, alloc_type_pointer(e->type)); + cg_emit_store(p, ptr, results[return_count-1]); + + tb_inst_ret(p->func, 0, nullptr); + return; + } else { + GB_ASSERT(p->proto->return_count == 1); + TB_DataType dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; + if (results.count == 1) { + cgValue result = results[0]; + result = cg_flatten_value(p, result); + + TB_Node *final_res = nullptr; + if (result.kind == cgValue_Addr) { + TB_CharUnits align = cast(TB_CharUnits)type_align_of(result.type); + final_res = tb_inst_load(p->func, dt, result.node, align, false); + } else { + GB_ASSERT(result.kind == cgValue_Value); + TB_DataType st = result.node->dt; + GB_ASSERT(st.type == dt.type); + if (st.raw == dt.raw) { + final_res = result.node; + } else if (st.type == TB_INT && st.data == 1) { + final_res = tb_inst_zxt(p->func, result.node, dt); + } else { + final_res = tb_inst_bitcast(p->func, result.node, dt); + } + } + + GB_ASSERT(final_res != nullptr); + + tb_inst_ret(p->func, 1, &final_res); + return; + } else { + GB_ASSERT_MSG(results.count == 1, "TODO(bill): multi-return values for the return"); + return; + } + } + } +} + + +gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { + TypeTuple *tuple = &p->type->Proc.results->Tuple; + isize return_count = p->type->Proc.result_count; + if (return_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + return; + } + TEMPORARY_ALLOCATOR_GUARD(); - GB_PANIC("TODO(bill): %.*s MUTLIPLE RETURN VALUES %td %td", LIT(p->name), results.count, return_results.count); + auto results = array_make(temporary_allocator(), 0, return_count); + + if (return_results.count != 0) { + for (isize i = 0; i < return_results.count; i++) { + cgValue res = cg_build_expr(p, return_results[i]); + cg_append_tuple_values(p, &results, res); + } + } else { + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cgValue res = cg_addr_load(p, addr); + array_add(&results, res); + } + } + GB_ASSERT(results.count == return_count); + + if (return_results.count != 0 && p->type->Proc.has_named_results) { + // NOTE(bill): store the named values before returning + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cg_addr_store(p, addr, results[i]); + } + } + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + results[i] = cg_emit_conv(p, results[i], e->type); + } + + cg_build_return_stmt_internal(p, slice_from_array(results)); } gb_internal void cg_build_if_stmt(cgProcedure *p, Ast *node) { @@ -1673,13 +1740,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { // TODO(bill): check if last instruction was a terminating one or not - { - TokenPos pos = ast_token(node).pos; - TB_FileID *file_id = map_get(&p->module->file_id_map, cast(uintptr)pos.file_id); - if (file_id) { - tb_inst_set_location(p->func, *file_id, pos.line); - } - } + cg_set_debug_pos_from_node(p, node); u16 prev_state_flags = p->state_flags; defer (p->state_flags = prev_state_flags); @@ -1838,7 +1899,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_end; case_ast_node(rs, RangeStmt, node); - GB_PANIC("TODO(bill): cg_build_range_stmt"); + GB_PANIC("TODO(bill): cg_build_range_stmt %.*s", LIT(p->name)); // cg_build_range_stmt(p, rs, rs->scope); case_end; @@ -1879,13 +1940,115 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { } } +gb_internal void cg_build_constant_value_decl(cgProcedure *p, AstValueDecl *vd) { + if (vd == nullptr || vd->is_mutable) { + return; + } + + auto *min_dep_set = &p->module->info->minimum_dependency_set; + + static i32 global_guid = 0; + + for (Ast *ident : vd->names) { + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_node(ident); + GB_ASSERT(e != nullptr); + if (e->kind != Entity_TypeName) { + continue; + } + + bool polymorphic_struct = false; + if (e->type != nullptr && e->kind == Entity_TypeName) { + Type *bt = base_type(e->type); + if (bt->kind == Type_Struct) { + polymorphic_struct = bt->Struct.is_polymorphic; + } + } + + if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) { + continue; + } + + if (e->TypeName.ir_mangled_name.len != 0) { + // NOTE(bill): Already set + continue; + } + + cg_set_nested_type_name_ir_mangled_name(e, p); + } + + for_array(i, vd->names) { + Ast *ident = vd->names[i]; + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_node(ident); + GB_ASSERT(e != nullptr); + if (e->kind != Entity_Procedure) { + continue; + } + GB_ASSERT (vd->values[i] != nullptr); + + Ast *value = unparen_expr(vd->values[i]); + if (value->kind != Ast_ProcLit) { + continue; // It's an alias + } + + DeclInfo *decl = decl_info_of_entity(e); + ast_node(pl, ProcLit, decl->proc_lit); + if (pl->body != nullptr) { + GenProcsData *gpd = e->Procedure.gen_procs; + if (gpd) { + rw_mutex_shared_lock(&gpd->mutex); + for (Entity *e : gpd->procs) { + if (!ptr_set_exists(min_dep_set, e)) { + continue; + } + DeclInfo *d = decl_info_of_entity(e); + cg_build_nested_proc(p, &d->proc_lit->ProcLit, e); + } + rw_mutex_shared_unlock(&gpd->mutex); + } else { + cg_build_nested_proc(p, pl, e); + } + } else { + + // FFI - Foreign function interace + String original_name = e->token.string; + String name = original_name; + + if (e->Procedure.is_foreign) { + GB_PANIC("cg_add_foreign_library_path"); + // cg_add_foreign_library_path(p->module, e->Procedure.foreign_library); + } + + if (e->Procedure.link_name.len > 0) { + name = e->Procedure.link_name; + } + + cgValue *prev_value = string_map_get(&p->module->members, name); + if (prev_value != nullptr) { + // NOTE(bill): Don't do mutliple declarations in the IR + return; + } + + e->Procedure.link_name = name; + + cgProcedure *nested_proc = cg_procedure_create(p->module, e); + + cgValue value = p->value; + + array_add(&p->module->procedures_to_generate, nested_proc); + array_add(&p->children, nested_proc); + string_map_set(&p->module->members, name, value); + } + } +} + gb_internal void cg_build_stmt_list(cgProcedure *p, Slice const &stmts) { for (Ast *stmt : stmts) { switch (stmt->kind) { case_ast_node(vd, ValueDecl, stmt); - // TODO(bill) - // cg_build_constant_value_decl(p, vd); + cg_build_constant_value_decl(p, vd); case_end; case_ast_node(fb, ForeignBlockDecl, stmt); ast_node(block, BlockStmt, fb->body); -- cgit v1.2.3 From 241a939c2985b0d9ad65dd305af6e84c82554e39 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 10:27:55 +0100 Subject: Update Tilde --- core/runtime/error_checks.odin | 18 +++++++++--------- core/runtime/internal.odin | 13 +++++++++++-- core/runtime/print.odin | 12 ++++++------ core/runtime/procs.odin | 4 ++-- src/tilde/tb.h | 1 - src/tilde/tb.lib | Bin 4163308 -> 4161458 bytes src/tilde_const.cpp | 1 + src/tilde_proc.cpp | 9 ++++++--- 8 files changed, 35 insertions(+), 23 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/core/runtime/error_checks.odin b/core/runtime/error_checks.odin index c189642af..9d484979a 100644 --- a/core/runtime/error_checks.odin +++ b/core/runtime/error_checks.odin @@ -235,7 +235,7 @@ make_slice_error_loc :: #force_inline proc "contextless" (loc := #caller_locatio handle_error(loc, len) } -make_dynamic_array_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, len, cap: int) { +make_dynamic_array_error_loc :: #force_inline proc "contextless" (loc := #caller_location, len, cap: int) { if 0 <= len && len <= cap { return } @@ -271,18 +271,18 @@ make_map_expr_error_loc :: #force_inline proc "contextless" (loc := #caller_loca -bounds_check_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, index, count: int) { - bounds_check_error(file_path, line, column, index, count) +bounds_check_error_loc :: #force_inline proc "contextless" (loc := #caller_location, index, count: int) { + bounds_check_error(loc.file_path, loc.line, loc.column, index, count) } -slice_expr_error_hi_loc :: #force_inline proc "contextless" (using loc := #caller_location, hi: int, len: int) { - slice_expr_error_hi(file_path, line, column, hi, len) +slice_expr_error_hi_loc :: #force_inline proc "contextless" (loc := #caller_location, hi: int, len: int) { + slice_expr_error_hi(loc.file_path, loc.line, loc.column, hi, len) } -slice_expr_error_lo_hi_loc :: #force_inline proc "contextless" (using loc := #caller_location, lo, hi: int, len: int) { - slice_expr_error_lo_hi(file_path, line, column, lo, hi, len) +slice_expr_error_lo_hi_loc :: #force_inline proc "contextless" (loc := #caller_location, lo, hi: int, len: int) { + slice_expr_error_lo_hi(loc.file_path, loc.line, loc.column, lo, hi, len) } -dynamic_array_expr_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, low, high, max: int) { - dynamic_array_expr_error(file_path, line, column, low, high, max) +dynamic_array_expr_error_loc :: #force_inline proc "contextless" (loc := #caller_location, low, high, max: int) { + dynamic_array_expr_error(loc.file_path, loc.line, loc.column, low, high, max) } diff --git a/core/runtime/internal.odin b/core/runtime/internal.odin index ad8a40acf..4d166bef0 100644 --- a/core/runtime/internal.odin +++ b/core/runtime/internal.odin @@ -11,7 +11,7 @@ RUNTIME_LINKAGE :: "strong" when ( ODIN_BUILD_MODE == .Dynamic || !ODIN_NO_CRT) && !IS_WASM) else "internal" -RUNTIME_REQUIRE :: true +RUNTIME_REQUIRE :: !ODIN_TILDE @(private) @@ -218,10 +218,18 @@ memory_equal :: proc "contextless" (x, y: rawptr, n: int) -> bool { case n == 0: return true case x == y: return true } - a, b := ([^]byte)(x), ([^]byte)(y) length := uint(n) + + for i := uint(0); i < length; i += 1 { + if a[i] != b[i] { + return false + } + } + return true +/* + when size_of(uint) == 8 { if word_length := length >> 3; word_length != 0 { for _ in 0.. bool { return true } +*/ } memory_compare :: proc "contextless" (a, b: rawptr, n: int) -> int #no_bounds_check { diff --git a/core/runtime/print.odin b/core/runtime/print.odin index 732ed9c12..20788b66f 100644 --- a/core/runtime/print.odin +++ b/core/runtime/print.odin @@ -215,19 +215,19 @@ print_uint :: proc "contextless" (x: uint) { print_u64(u64(x)) } print_uintptr :: proc "contextless" (x: uintptr) { print_u64(u64(x)) } print_int :: proc "contextless" (x: int) { print_i64(i64(x)) } -print_caller_location :: proc "contextless" (using loc: Source_Code_Location) { - print_string(file_path) +print_caller_location :: proc "contextless" (loc: Source_Code_Location) { + print_string(loc.file_path) when ODIN_ERROR_POS_STYLE == .Default { print_byte('(') - print_u64(u64(line)) + print_u64(u64(loc.line)) print_byte(':') - print_u64(u64(column)) + print_u64(u64(loc.column)) print_byte(')') } else when ODIN_ERROR_POS_STYLE == .Unix { print_byte(':') - print_u64(u64(line)) + print_u64(u64(loc.line)) print_byte(':') - print_u64(u64(column)) + print_u64(u64(loc.column)) print_byte(':') } else { #panic("unhandled ODIN_ERROR_POS_STYLE") diff --git a/core/runtime/procs.odin b/core/runtime/procs.odin index 3a433c3bf..1592c608b 100644 --- a/core/runtime/procs.odin +++ b/core/runtime/procs.odin @@ -31,7 +31,7 @@ when ODIN_NO_CRT && ODIN_OS == .Windows { if ptr != nil && len != 0 { b := byte(val) p := ([^]byte)(ptr) - for i in 0..const_nil_guid.fetch_add(1)); TB_Global *cstr_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + i64 size = str.len+1; tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), cstr_global, size, 1, 1); u8 *data = cast(u8 *)tb_global_add_region(m->mod, cstr_global, 0, size); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 610d715ae..e75c621ee 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -334,8 +334,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } bool emit_asm = false; - if (string_starts_with(p->name, str_lit("bug@main"))) { - // emit_asm = true; + if (string_starts_with(p->name, str_lit("bug@"))) { + emit_asm = true; } TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); @@ -357,7 +357,10 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { cg_build_stmt(p, p->body); cg_procedure_end(p); - if (string_starts_with(p->name, str_lit("bug@main"))) { // IR Printing + if ( + // string_starts_with(p->name, str_lit("bug@")) || + false + ) { // IR Printing TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); -- cgit v1.2.3 From 4051dd95223f9662c78c05d09e01b925d2d99ac0 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 11:30:07 +0100 Subject: Update Tilde to get basic "Hello World" working with `runtime.print_string` --- src/tilde/tb.lib | Bin 4161458 -> 4161494 bytes src/tilde_builtin.cpp | 14 ++++++++++---- src/tilde_proc.cpp | 6 +++--- 3 files changed, 13 insertions(+), 7 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 64b6f492d..b35b28fc0 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index 6deaf0e9b..b40eacc7f 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -303,12 +303,15 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr case BuiltinProc_min: if (ce->args.count == 2) { Type *t = type_of_expr(expr); - return cg_builtin_min(p, t, cg_build_expr(p, ce->args[0]), cg_build_expr(p, ce->args[1])); + cgValue x = cg_build_expr(p, ce->args[0]); + cgValue y = cg_build_expr(p, ce->args[1]); + return cg_builtin_min(p, t, x, y); } else { Type *t = type_of_expr(expr); cgValue x = cg_build_expr(p, ce->args[0]); for (isize i = 1; i < ce->args.count; i++) { - x = cg_builtin_min(p, t, x, cg_build_expr(p, ce->args[i])); + cgValue y = cg_build_expr(p, ce->args[i]); + x = cg_builtin_min(p, t, x, y); } return x; } @@ -316,12 +319,15 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr case BuiltinProc_max: if (ce->args.count == 2) { Type *t = type_of_expr(expr); - return cg_builtin_max(p, t, cg_build_expr(p, ce->args[0]), cg_build_expr(p, ce->args[1])); + cgValue x = cg_build_expr(p, ce->args[0]); + cgValue y = cg_build_expr(p, ce->args[1]); + return cg_builtin_max(p, t, x, y); } else { Type *t = type_of_expr(expr); cgValue x = cg_build_expr(p, ce->args[0]); for (isize i = 1; i < ce->args.count; i++) { - x = cg_builtin_max(p, t, x, cg_build_expr(p, ce->args[i])); + cgValue y = cg_build_expr(p, ce->args[i]); + x = cg_builtin_max(p, t, x, y); } return x; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index e75c621ee..8143c9a6e 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -334,8 +334,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } bool emit_asm = false; - if (string_starts_with(p->name, str_lit("bug@"))) { - emit_asm = true; + if (string_starts_with(p->name, str_lit("runtime@_os_write"))) { + // emit_asm = true; } TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); @@ -358,7 +358,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { cg_procedure_end(p); if ( - // string_starts_with(p->name, str_lit("bug@")) || + string_starts_with(p->name, str_lit("runtime@_os_write")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); -- cgit v1.2.3 From bd81c6f5b4bbcdb0c65cda5bedf1f3c5e0c0371e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 11:53:18 +0100 Subject: Move linker code into separate file --- src/linker.cpp | 427 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/llvm_backend.hpp | 10 +- src/main.cpp | 425 ++------------------------------------------------ src/tilde/tb.lib | Bin 4161494 -> 4393788 bytes src/tilde_proc.cpp | 2 +- 5 files changed, 438 insertions(+), 426 deletions(-) create mode 100644 src/linker.cpp (limited to 'src/tilde_proc.cpp') diff --git a/src/linker.cpp b/src/linker.cpp new file mode 100644 index 000000000..dc6e072d1 --- /dev/null +++ b/src/linker.cpp @@ -0,0 +1,427 @@ +struct LinkerData { + BlockingMutex foreign_mutex; + PtrSet foreign_libraries_set; + Array foreign_libraries; + + Array output_object_paths; + Array output_temp_paths; + String output_base; + String output_name; +}; + +gb_internal i32 system_exec_command_line_app(char const *name, char const *fmt, ...); + +gb_internal i32 linker_stage(LinkerData *gen) { + i32 result = 0; + Timings *timings = &global_timings; + + String output_filename = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_Output]); + debugf("Linking %.*s\n", LIT(output_filename)); + + // TOOD(Jeroen): Make a `build_paths[BuildPath_Object] to avoid `%.*s.o`. + + if (is_arch_wasm()) { + timings_start_section(timings, str_lit("wasm-ld")); + + #if defined(GB_SYSTEM_WINDOWS) + result = system_exec_command_line_app("wasm-ld", + "\"%.*s\\bin\\wasm-ld\" \"%.*s.o\" -o \"%.*s\" %.*s %.*s", + LIT(build_context.ODIN_ROOT), + LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); + #else + result = system_exec_command_line_app("wasm-ld", + "wasm-ld \"%.*s.o\" -o \"%.*s\" %.*s %.*s", + LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); + #endif + return result; + } + + if (build_context.cross_compiling && selected_target_metrics->metrics == &target_essence_amd64) { +#if defined(GB_SYSTEM_UNIX) + result = system_exec_command_line_app("linker", "x86_64-essence-gcc \"%.*s.o\" -o \"%.*s\" %.*s %.*s", + LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); +#else + gb_printf_err("Linking for cross compilation for this platform is not yet supported (%.*s %.*s)\n", + LIT(target_os_names[build_context.metrics.os]), + LIT(target_arch_names[build_context.metrics.arch]) + ); +#endif + } else if (build_context.cross_compiling && build_context.different_os) { + gb_printf_err("Linking for cross compilation for this platform is not yet supported (%.*s %.*s)\n", + LIT(target_os_names[build_context.metrics.os]), + LIT(target_arch_names[build_context.metrics.arch]) + ); + build_context.keep_object_files = true; + } else { + #if defined(GB_SYSTEM_WINDOWS) + bool is_windows = true; + #else + bool is_windows = false; + #endif + #if defined(GB_SYSTEM_OSX) + bool is_osx = true; + #else + bool is_osx = false; + #endif + + + if (is_windows) { + String section_name = str_lit("msvc-link"); + if (build_context.use_lld) { + section_name = str_lit("lld-link"); + } + timings_start_section(timings, section_name); + + gbString lib_str = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(lib_str)); + + gbString link_settings = gb_string_make_reserve(heap_allocator(), 256); + defer (gb_string_free(link_settings)); + + // Add library search paths. + if (build_context.build_paths[BuildPath_VS_LIB].basename.len > 0) { + String path = {}; + auto add_path = [&](String path) { + if (path[path.len-1] == '\\') { + path.len -= 1; + } + link_settings = gb_string_append_fmt(link_settings, " /LIBPATH:\"%.*s\"", LIT(path)); + }; + add_path(build_context.build_paths[BuildPath_Win_SDK_UM_Lib].basename); + add_path(build_context.build_paths[BuildPath_Win_SDK_UCRT_Lib].basename); + add_path(build_context.build_paths[BuildPath_VS_LIB].basename); + } + + + StringSet libs = {}; + string_set_init(&libs, 64); + defer (string_set_destroy(&libs)); + + StringSet asm_files = {}; + string_set_init(&asm_files, 64); + defer (string_set_destroy(&asm_files)); + + for (Entity *e : gen->foreign_libraries) { + GB_ASSERT(e->kind == Entity_LibraryName); + for_array(i, e->LibraryName.paths) { + String lib = string_trim_whitespace(e->LibraryName.paths[i]); + // IMPORTANT NOTE(bill): calling `string_to_lower` here is not an issue because + // we will never uses these strings afterwards + string_to_lower(&lib); + if (lib.len == 0) { + continue; + } + + if (has_asm_extension(lib)) { + if (!string_set_update(&asm_files, lib)) { + String asm_file = asm_files.entries[i].value; + String obj_file = concatenate_strings(permanent_allocator(), asm_file, str_lit(".obj")); + + result = system_exec_command_line_app("nasm", + "\"%.*s\\bin\\nasm\\windows\\nasm.exe\" \"%.*s\" " + "-f win64 " + "-o \"%.*s\" " + "%.*s " + "", + LIT(build_context.ODIN_ROOT), LIT(asm_file), + LIT(obj_file), + LIT(build_context.extra_assembler_flags) + ); + + if (result) { + return result; + } + array_add(&gen->output_object_paths, obj_file); + } + } else { + if (!string_set_update(&libs, lib)) { + lib_str = gb_string_append_fmt(lib_str, " \"%.*s\"", LIT(lib)); + } + } + } + } + + for (Entity *e : gen->foreign_libraries) { + GB_ASSERT(e->kind == Entity_LibraryName); + if (e->LibraryName.extra_linker_flags.len != 0) { + lib_str = gb_string_append_fmt(lib_str, " %.*s", LIT(e->LibraryName.extra_linker_flags)); + } + } + + if (build_context.build_mode == BuildMode_DynamicLibrary) { + link_settings = gb_string_append_fmt(link_settings, " /DLL"); + } else { + link_settings = gb_string_append_fmt(link_settings, " /ENTRY:mainCRTStartup"); + } + + if (build_context.pdb_filepath != "") { + String pdb_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_PDB]); + link_settings = gb_string_append_fmt(link_settings, " /PDB:%.*s", LIT(pdb_path)); + } + + if (build_context.no_crt) { + link_settings = gb_string_append_fmt(link_settings, " /nodefaultlib"); + } else { + link_settings = gb_string_append_fmt(link_settings, " /defaultlib:libcmt"); + } + + if (build_context.ODIN_DEBUG) { + link_settings = gb_string_append_fmt(link_settings, " /DEBUG"); + } + + gbString object_files = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(object_files)); + for (String const &object_path : gen->output_object_paths) { + object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); + } + + String vs_exe_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_VS_EXE]); + defer (gb_free(heap_allocator(), vs_exe_path.text)); + + String windows_sdk_bin_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_Win_SDK_Bin_Path]); + defer (gb_free(heap_allocator(), windows_sdk_bin_path.text)); + + char const *subsystem_str = build_context.use_subsystem_windows ? "WINDOWS" : "CONSOLE"; + if (!build_context.use_lld) { // msvc + String res_path = {}; + defer (gb_free(heap_allocator(), res_path.text)); + if (build_context.has_resource) { + String temp_res_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_RES]); + res_path = concatenate3_strings(heap_allocator(), str_lit("\""), temp_res_path, str_lit("\"")); + gb_free(heap_allocator(), temp_res_path.text); + + String rc_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_RC]); + defer (gb_free(heap_allocator(), rc_path.text)); + + result = system_exec_command_line_app("msvc-link", + "\"%.*src.exe\" /nologo /fo \"%.*s\" \"%.*s\"", + LIT(windows_sdk_bin_path), + LIT(res_path), + LIT(rc_path) + ); + + if (result) { + return result; + } + } + + switch (build_context.build_mode) { + case BuildMode_Executable: + link_settings = gb_string_append_fmt(link_settings, " /NOIMPLIB /NOEXP"); + break; + } + + result = system_exec_command_line_app("msvc-link", + "\"%.*slink.exe\" %s %.*s -OUT:\"%.*s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + "%.*s " + "%.*s " + "%s " + "", + LIT(vs_exe_path), object_files, LIT(res_path), LIT(output_filename), + link_settings, + subsystem_str, + LIT(build_context.link_flags), + LIT(build_context.extra_linker_flags), + lib_str + ); + if (result) { + return result; + } + } else { // lld + result = system_exec_command_line_app("msvc-lld-link", + "\"%.*s\\bin\\lld-link\" %s -OUT:\"%.*s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + "%.*s " + "%.*s " + "%s " + "", + LIT(build_context.ODIN_ROOT), object_files, LIT(output_filename), + link_settings, + subsystem_str, + LIT(build_context.link_flags), + LIT(build_context.extra_linker_flags), + lib_str + ); + + if (result) { + return result; + } + } + } else { + timings_start_section(timings, str_lit("ld-link")); + + // NOTE(vassvik): get cwd, for used for local shared libs linking, since those have to be relative to the exe + char cwd[256]; + #if !defined(GB_SYSTEM_WINDOWS) + getcwd(&cwd[0], 256); + #endif + //printf("%s\n", cwd); + + // NOTE(vassvik): needs to add the root to the library search paths, so that the full filenames of the library + // files can be passed with -l: + gbString lib_str = gb_string_make(heap_allocator(), "-L/"); + defer (gb_string_free(lib_str)); + + StringSet libs = {}; + string_set_init(&libs, 64); + defer (string_set_destroy(&libs)); + + for (Entity *e : gen->foreign_libraries) { + GB_ASSERT(e->kind == Entity_LibraryName); + for (String lib : e->LibraryName.paths) { + lib = string_trim_whitespace(lib); + if (lib.len == 0) { + continue; + } + if (string_set_update(&libs, lib)) { + continue; + } + + // NOTE(zangent): Sometimes, you have to use -framework on MacOS. + // This allows you to specify '-f' in a #foreign_system_library, + // without having to implement any new syntax specifically for MacOS. + if (build_context.metrics.os == TargetOs_darwin) { + if (string_ends_with(lib, str_lit(".framework"))) { + // framework thingie + String lib_name = lib; + lib_name = remove_extension_from_path(lib_name); + lib_str = gb_string_append_fmt(lib_str, " -framework %.*s ", LIT(lib_name)); + } else if (string_ends_with(lib, str_lit(".a")) || string_ends_with(lib, str_lit(".o")) || string_ends_with(lib, str_lit(".dylib"))) { + // For: + // object + // dynamic lib + // static libs, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + } else { + // NOTE(vassvik): static libraries (.a files) in linux can be linked to directly using the full path, + // since those are statically linked to at link time. shared libraries (.so) has to be + // available at runtime wherever the executable is run, so we make require those to be + // local to the executable (unless the system collection is used, in which case we search + // the system library paths for the library file). + if (string_ends_with(lib, str_lit(".a")) || string_ends_with(lib, str_lit(".o"))) { + // static libs and object files, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " -l:\"%.*s\" ", LIT(lib)); + } else if (string_ends_with(lib, str_lit(".so"))) { + // dynamic lib, relative path to executable + // NOTE(vassvik): it is the user's responsibility to make sure the shared library files are visible + // at runtime to the executable + lib_str = gb_string_append_fmt(lib_str, " -l:\"%s/%.*s\" ", cwd, LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + } + } + } + + for (Entity *e : gen->foreign_libraries) { + GB_ASSERT(e->kind == Entity_LibraryName); + if (e->LibraryName.extra_linker_flags.len != 0) { + lib_str = gb_string_append_fmt(lib_str, " %.*s", LIT(e->LibraryName.extra_linker_flags)); + } + } + + gbString object_files = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(object_files)); + for (String object_path : gen->output_object_paths) { + object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); + } + + gbString link_settings = gb_string_make_reserve(heap_allocator(), 32); + + if (build_context.no_crt) { + link_settings = gb_string_append_fmt(link_settings, "-nostdlib "); + } + + // NOTE(dweiler): We use clang as a frontend for the linker as there are + // other runtime and compiler support libraries that need to be linked in + // very specific orders such as libgcc_s, ld-linux-so, unwind, etc. + // These are not always typically inside /lib, /lib64, or /usr versions + // of that, e.g libgcc.a is in /usr/lib/gcc/{version}, and can vary on + // the distribution of Linux even. The gcc or clang specs is the only + // reliable way to query this information to call ld directly. + if (build_context.build_mode == BuildMode_DynamicLibrary) { + // NOTE(dweiler): Let the frontend know we're building a shared library + // so it doesn't generate symbols which cannot be relocated. + link_settings = gb_string_appendc(link_settings, "-shared "); + + // NOTE(dweiler): _odin_entry_point must be called at initialization + // time of the shared object, similarly, _odin_exit_point must be called + // at deinitialization. We can pass both -init and -fini to the linker by + // using a comma separated list of arguments to -Wl. + // + // This previously used ld but ld cannot actually build a shared library + // correctly this way since all the other dependencies provided implicitly + // by the compiler frontend are still needed and most of the command + // line arguments prepared previously are incompatible with ld. + if (build_context.metrics.os == TargetOs_darwin) { + link_settings = gb_string_appendc(link_settings, "-Wl,-init,'__odin_entry_point' "); + // NOTE(weshardee): __odin_exit_point should also be added, but -fini + // does not exist on MacOS + } else { + link_settings = gb_string_appendc(link_settings, "-Wl,-init,'_odin_entry_point' "); + link_settings = gb_string_appendc(link_settings, "-Wl,-fini,'_odin_exit_point' "); + } + + } else if (build_context.metrics.os != TargetOs_openbsd) { + // OpenBSD defaults to PIE executable. do not pass -no-pie for it. + link_settings = gb_string_appendc(link_settings, "-no-pie "); + } + + gbString platform_lib_str = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(platform_lib_str)); + if (build_context.metrics.os == TargetOs_darwin) { + platform_lib_str = gb_string_appendc(platform_lib_str, "-lSystem -lm -Wl,-syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -L/usr/local/lib"); + } else { + platform_lib_str = gb_string_appendc(platform_lib_str, "-lc -lm"); + } + + if (build_context.metrics.os == TargetOs_darwin) { + // This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit. + if (build_context.minimum_os_version_string.len) { + link_settings = gb_string_append_fmt(link_settings, " -mmacosx-version-min=%.*s ", LIT(build_context.minimum_os_version_string)); + } else if (build_context.metrics.arch == TargetArch_arm64) { + link_settings = gb_string_appendc(link_settings, " -mmacosx-version-min=12.0.0 "); + } else { + link_settings = gb_string_appendc(link_settings, " -mmacosx-version-min=10.12.0 "); + } + // This points the linker to where the entry point is + link_settings = gb_string_appendc(link_settings, " -e _main "); + } + + gbString link_command_line = gb_string_make(heap_allocator(), "clang -Wno-unused-command-line-argument "); + defer (gb_string_free(link_command_line)); + + link_command_line = gb_string_appendc(link_command_line, object_files); + link_command_line = gb_string_append_fmt(link_command_line, " -o \"%.*s\" ", LIT(output_filename)); + link_command_line = gb_string_append_fmt(link_command_line, " %s ", platform_lib_str); + link_command_line = gb_string_append_fmt(link_command_line, " %s ", lib_str); + link_command_line = gb_string_append_fmt(link_command_line, " %.*s ", LIT(build_context.link_flags)); + link_command_line = gb_string_append_fmt(link_command_line, " %.*s ", LIT(build_context.extra_linker_flags)); + link_command_line = gb_string_append_fmt(link_command_line, " %s ", link_settings); + + result = system_exec_command_line_app("ld-link", link_command_line); + + if (result) { + return result; + } + + if (is_osx && build_context.ODIN_DEBUG) { + // NOTE: macOS links DWARF symbols dynamically. Dsymutil will map the stubs in the exe + // to the symbols in the object file + result = system_exec_command_line_app("dsymutil", "dsymutil %.*s", LIT(output_filename)); + + if (result) { + return result; + } + } + } + } + + return result; +} diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 15833c63a..e05bf8025 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -190,13 +190,9 @@ struct lbModule { LLVMPassManagerRef function_pass_managers[lbFunctionPassManager_COUNT]; }; -struct lbGenerator { +struct lbGenerator : LinkerData { CheckerInfo *info; - Array output_object_paths; - Array output_temp_paths; - String output_base; - String output_name; PtrMap modules; // key is `AstPackage *` (`void *` is used for future use) PtrMap modules_through_ctx; lbModule default_module; @@ -204,10 +200,6 @@ struct lbGenerator { RecursiveMutex anonymous_proc_lits_mutex; PtrMap anonymous_proc_lits; - BlockingMutex foreign_mutex; - PtrSet foreign_libraries_set; - Array foreign_libraries; - std::atomic global_array_index; std::atomic global_generated_index; diff --git a/src/main.cpp b/src/main.cpp index a59f452d8..70e887b9f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -71,6 +71,8 @@ gb_global Timings global_timings = {0}; #include "checker.cpp" #include "docs.cpp" +#include "linker.cpp" + #if defined(GB_SYSTEM_WINDOWS) #include "tilde.cpp" #endif @@ -151,422 +153,6 @@ gb_internal i32 system_exec_command_line_app(char const *name, char const *fmt, return exit_code; } - -gb_internal i32 linker_stage(lbGenerator *gen) { - i32 result = 0; - Timings *timings = &global_timings; - - String output_filename = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_Output]); - debugf("Linking %.*s\n", LIT(output_filename)); - - // TOOD(Jeroen): Make a `build_paths[BuildPath_Object] to avoid `%.*s.o`. - - if (is_arch_wasm()) { - timings_start_section(timings, str_lit("wasm-ld")); - - #if defined(GB_SYSTEM_WINDOWS) - result = system_exec_command_line_app("wasm-ld", - "\"%.*s\\bin\\wasm-ld\" \"%.*s.o\" -o \"%.*s\" %.*s %.*s", - LIT(build_context.ODIN_ROOT), - LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); - #else - result = system_exec_command_line_app("wasm-ld", - "wasm-ld \"%.*s.o\" -o \"%.*s\" %.*s %.*s", - LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); - #endif - return result; - } - - if (build_context.cross_compiling && selected_target_metrics->metrics == &target_essence_amd64) { -#if defined(GB_SYSTEM_UNIX) - result = system_exec_command_line_app("linker", "x86_64-essence-gcc \"%.*s.o\" -o \"%.*s\" %.*s %.*s", - LIT(output_filename), LIT(output_filename), LIT(build_context.link_flags), LIT(build_context.extra_linker_flags)); -#else - gb_printf_err("Linking for cross compilation for this platform is not yet supported (%.*s %.*s)\n", - LIT(target_os_names[build_context.metrics.os]), - LIT(target_arch_names[build_context.metrics.arch]) - ); -#endif - } else if (build_context.cross_compiling && build_context.different_os) { - gb_printf_err("Linking for cross compilation for this platform is not yet supported (%.*s %.*s)\n", - LIT(target_os_names[build_context.metrics.os]), - LIT(target_arch_names[build_context.metrics.arch]) - ); - build_context.keep_object_files = true; - } else { - #if defined(GB_SYSTEM_WINDOWS) - bool is_windows = true; - #else - bool is_windows = false; - #endif - #if defined(GB_SYSTEM_OSX) - bool is_osx = true; - #else - bool is_osx = false; - #endif - - - if (is_windows) { - String section_name = str_lit("msvc-link"); - if (build_context.use_lld) { - section_name = str_lit("lld-link"); - } - timings_start_section(timings, section_name); - - gbString lib_str = gb_string_make(heap_allocator(), ""); - defer (gb_string_free(lib_str)); - - gbString link_settings = gb_string_make_reserve(heap_allocator(), 256); - defer (gb_string_free(link_settings)); - - // Add library search paths. - if (build_context.build_paths[BuildPath_VS_LIB].basename.len > 0) { - String path = {}; - auto add_path = [&](String path) { - if (path[path.len-1] == '\\') { - path.len -= 1; - } - link_settings = gb_string_append_fmt(link_settings, " /LIBPATH:\"%.*s\"", LIT(path)); - }; - add_path(build_context.build_paths[BuildPath_Win_SDK_UM_Lib].basename); - add_path(build_context.build_paths[BuildPath_Win_SDK_UCRT_Lib].basename); - add_path(build_context.build_paths[BuildPath_VS_LIB].basename); - } - - - StringSet libs = {}; - string_set_init(&libs, 64); - defer (string_set_destroy(&libs)); - - StringSet asm_files = {}; - string_set_init(&asm_files, 64); - defer (string_set_destroy(&asm_files)); - - for (Entity *e : gen->foreign_libraries) { - GB_ASSERT(e->kind == Entity_LibraryName); - for_array(i, e->LibraryName.paths) { - String lib = string_trim_whitespace(e->LibraryName.paths[i]); - // IMPORTANT NOTE(bill): calling `string_to_lower` here is not an issue because - // we will never uses these strings afterwards - string_to_lower(&lib); - if (lib.len == 0) { - continue; - } - - if (has_asm_extension(lib)) { - if (!string_set_update(&asm_files, lib)) { - String asm_file = asm_files.entries[i].value; - String obj_file = concatenate_strings(permanent_allocator(), asm_file, str_lit(".obj")); - - result = system_exec_command_line_app("nasm", - "\"%.*s\\bin\\nasm\\windows\\nasm.exe\" \"%.*s\" " - "-f win64 " - "-o \"%.*s\" " - "%.*s " - "", - LIT(build_context.ODIN_ROOT), LIT(asm_file), - LIT(obj_file), - LIT(build_context.extra_assembler_flags) - ); - - if (result) { - return result; - } - array_add(&gen->output_object_paths, obj_file); - } - } else { - if (!string_set_update(&libs, lib)) { - lib_str = gb_string_append_fmt(lib_str, " \"%.*s\"", LIT(lib)); - } - } - } - } - - for (Entity *e : gen->foreign_libraries) { - GB_ASSERT(e->kind == Entity_LibraryName); - if (e->LibraryName.extra_linker_flags.len != 0) { - lib_str = gb_string_append_fmt(lib_str, " %.*s", LIT(e->LibraryName.extra_linker_flags)); - } - } - - if (build_context.build_mode == BuildMode_DynamicLibrary) { - link_settings = gb_string_append_fmt(link_settings, " /DLL"); - } else { - link_settings = gb_string_append_fmt(link_settings, " /ENTRY:mainCRTStartup"); - } - - if (build_context.pdb_filepath != "") { - String pdb_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_PDB]); - link_settings = gb_string_append_fmt(link_settings, " /PDB:%.*s", LIT(pdb_path)); - } - - if (build_context.no_crt) { - link_settings = gb_string_append_fmt(link_settings, " /nodefaultlib"); - } else { - link_settings = gb_string_append_fmt(link_settings, " /defaultlib:libcmt"); - } - - if (build_context.ODIN_DEBUG) { - link_settings = gb_string_append_fmt(link_settings, " /DEBUG"); - } - - gbString object_files = gb_string_make(heap_allocator(), ""); - defer (gb_string_free(object_files)); - for (String const &object_path : gen->output_object_paths) { - object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); - } - - String vs_exe_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_VS_EXE]); - defer (gb_free(heap_allocator(), vs_exe_path.text)); - - String windows_sdk_bin_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_Win_SDK_Bin_Path]); - defer (gb_free(heap_allocator(), windows_sdk_bin_path.text)); - - char const *subsystem_str = build_context.use_subsystem_windows ? "WINDOWS" : "CONSOLE"; - if (!build_context.use_lld) { // msvc - String res_path = {}; - defer (gb_free(heap_allocator(), res_path.text)); - if (build_context.has_resource) { - String temp_res_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_RES]); - res_path = concatenate3_strings(heap_allocator(), str_lit("\""), temp_res_path, str_lit("\"")); - gb_free(heap_allocator(), temp_res_path.text); - - String rc_path = path_to_string(heap_allocator(), build_context.build_paths[BuildPath_RC]); - defer (gb_free(heap_allocator(), rc_path.text)); - - result = system_exec_command_line_app("msvc-link", - "\"%.*src.exe\" /nologo /fo \"%.*s\" \"%.*s\"", - LIT(windows_sdk_bin_path), - LIT(res_path), - LIT(rc_path) - ); - - if (result) { - return result; - } - } - - switch (build_context.build_mode) { - case BuildMode_Executable: - link_settings = gb_string_append_fmt(link_settings, " /NOIMPLIB /NOEXP"); - break; - } - - result = system_exec_command_line_app("msvc-link", - "\"%.*slink.exe\" %s %.*s -OUT:\"%.*s\" %s " - "/nologo /incremental:no /opt:ref /subsystem:%s " - "%.*s " - "%.*s " - "%s " - "", - LIT(vs_exe_path), object_files, LIT(res_path), LIT(output_filename), - link_settings, - subsystem_str, - LIT(build_context.link_flags), - LIT(build_context.extra_linker_flags), - lib_str - ); - if (result) { - return result; - } - } else { // lld - result = system_exec_command_line_app("msvc-lld-link", - "\"%.*s\\bin\\lld-link\" %s -OUT:\"%.*s\" %s " - "/nologo /incremental:no /opt:ref /subsystem:%s " - "%.*s " - "%.*s " - "%s " - "", - LIT(build_context.ODIN_ROOT), object_files, LIT(output_filename), - link_settings, - subsystem_str, - LIT(build_context.link_flags), - LIT(build_context.extra_linker_flags), - lib_str - ); - - if (result) { - return result; - } - } - } else { - timings_start_section(timings, str_lit("ld-link")); - - // NOTE(vassvik): get cwd, for used for local shared libs linking, since those have to be relative to the exe - char cwd[256]; - #if !defined(GB_SYSTEM_WINDOWS) - getcwd(&cwd[0], 256); - #endif - //printf("%s\n", cwd); - - // NOTE(vassvik): needs to add the root to the library search paths, so that the full filenames of the library - // files can be passed with -l: - gbString lib_str = gb_string_make(heap_allocator(), "-L/"); - defer (gb_string_free(lib_str)); - - StringSet libs = {}; - string_set_init(&libs, 64); - defer (string_set_destroy(&libs)); - - for (Entity *e : gen->foreign_libraries) { - GB_ASSERT(e->kind == Entity_LibraryName); - for (String lib : e->LibraryName.paths) { - lib = string_trim_whitespace(lib); - if (lib.len == 0) { - continue; - } - if (string_set_update(&libs, lib)) { - continue; - } - - // NOTE(zangent): Sometimes, you have to use -framework on MacOS. - // This allows you to specify '-f' in a #foreign_system_library, - // without having to implement any new syntax specifically for MacOS. - if (build_context.metrics.os == TargetOs_darwin) { - if (string_ends_with(lib, str_lit(".framework"))) { - // framework thingie - String lib_name = lib; - lib_name = remove_extension_from_path(lib_name); - lib_str = gb_string_append_fmt(lib_str, " -framework %.*s ", LIT(lib_name)); - } else if (string_ends_with(lib, str_lit(".a")) || string_ends_with(lib, str_lit(".o")) || string_ends_with(lib, str_lit(".dylib"))) { - // For: - // object - // dynamic lib - // static libs, absolute full path relative to the file in which the lib was imported from - lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); - } else { - // dynamic or static system lib, just link regularly searching system library paths - lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); - } - } else { - // NOTE(vassvik): static libraries (.a files) in linux can be linked to directly using the full path, - // since those are statically linked to at link time. shared libraries (.so) has to be - // available at runtime wherever the executable is run, so we make require those to be - // local to the executable (unless the system collection is used, in which case we search - // the system library paths for the library file). - if (string_ends_with(lib, str_lit(".a")) || string_ends_with(lib, str_lit(".o"))) { - // static libs and object files, absolute full path relative to the file in which the lib was imported from - lib_str = gb_string_append_fmt(lib_str, " -l:\"%.*s\" ", LIT(lib)); - } else if (string_ends_with(lib, str_lit(".so"))) { - // dynamic lib, relative path to executable - // NOTE(vassvik): it is the user's responsibility to make sure the shared library files are visible - // at runtime to the executable - lib_str = gb_string_append_fmt(lib_str, " -l:\"%s/%.*s\" ", cwd, LIT(lib)); - } else { - // dynamic or static system lib, just link regularly searching system library paths - lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); - } - } - } - } - - for (Entity *e : gen->foreign_libraries) { - GB_ASSERT(e->kind == Entity_LibraryName); - if (e->LibraryName.extra_linker_flags.len != 0) { - lib_str = gb_string_append_fmt(lib_str, " %.*s", LIT(e->LibraryName.extra_linker_flags)); - } - } - - gbString object_files = gb_string_make(heap_allocator(), ""); - defer (gb_string_free(object_files)); - for (String object_path : gen->output_object_paths) { - object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); - } - - gbString link_settings = gb_string_make_reserve(heap_allocator(), 32); - - if (build_context.no_crt) { - link_settings = gb_string_append_fmt(link_settings, "-nostdlib "); - } - - // NOTE(dweiler): We use clang as a frontend for the linker as there are - // other runtime and compiler support libraries that need to be linked in - // very specific orders such as libgcc_s, ld-linux-so, unwind, etc. - // These are not always typically inside /lib, /lib64, or /usr versions - // of that, e.g libgcc.a is in /usr/lib/gcc/{version}, and can vary on - // the distribution of Linux even. The gcc or clang specs is the only - // reliable way to query this information to call ld directly. - if (build_context.build_mode == BuildMode_DynamicLibrary) { - // NOTE(dweiler): Let the frontend know we're building a shared library - // so it doesn't generate symbols which cannot be relocated. - link_settings = gb_string_appendc(link_settings, "-shared "); - - // NOTE(dweiler): _odin_entry_point must be called at initialization - // time of the shared object, similarly, _odin_exit_point must be called - // at deinitialization. We can pass both -init and -fini to the linker by - // using a comma separated list of arguments to -Wl. - // - // This previously used ld but ld cannot actually build a shared library - // correctly this way since all the other dependencies provided implicitly - // by the compiler frontend are still needed and most of the command - // line arguments prepared previously are incompatible with ld. - if (build_context.metrics.os == TargetOs_darwin) { - link_settings = gb_string_appendc(link_settings, "-Wl,-init,'__odin_entry_point' "); - // NOTE(weshardee): __odin_exit_point should also be added, but -fini - // does not exist on MacOS - } else { - link_settings = gb_string_appendc(link_settings, "-Wl,-init,'_odin_entry_point' "); - link_settings = gb_string_appendc(link_settings, "-Wl,-fini,'_odin_exit_point' "); - } - - } else if (build_context.metrics.os != TargetOs_openbsd) { - // OpenBSD defaults to PIE executable. do not pass -no-pie for it. - link_settings = gb_string_appendc(link_settings, "-no-pie "); - } - - gbString platform_lib_str = gb_string_make(heap_allocator(), ""); - defer (gb_string_free(platform_lib_str)); - if (build_context.metrics.os == TargetOs_darwin) { - platform_lib_str = gb_string_appendc(platform_lib_str, "-lSystem -lm -Wl,-syslibroot /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk -L/usr/local/lib"); - } else { - platform_lib_str = gb_string_appendc(platform_lib_str, "-lc -lm"); - } - - if (build_context.metrics.os == TargetOs_darwin) { - // This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit. - if (build_context.minimum_os_version_string.len) { - link_settings = gb_string_append_fmt(link_settings, " -mmacosx-version-min=%.*s ", LIT(build_context.minimum_os_version_string)); - } else if (build_context.metrics.arch == TargetArch_arm64) { - link_settings = gb_string_appendc(link_settings, " -mmacosx-version-min=12.0.0 "); - } else { - link_settings = gb_string_appendc(link_settings, " -mmacosx-version-min=10.12.0 "); - } - // This points the linker to where the entry point is - link_settings = gb_string_appendc(link_settings, " -e _main "); - } - - gbString link_command_line = gb_string_make(heap_allocator(), "clang -Wno-unused-command-line-argument "); - defer (gb_string_free(link_command_line)); - - link_command_line = gb_string_appendc(link_command_line, object_files); - link_command_line = gb_string_append_fmt(link_command_line, " -o \"%.*s\" ", LIT(output_filename)); - link_command_line = gb_string_append_fmt(link_command_line, " %s ", platform_lib_str); - link_command_line = gb_string_append_fmt(link_command_line, " %s ", lib_str); - link_command_line = gb_string_append_fmt(link_command_line, " %.*s ", LIT(build_context.link_flags)); - link_command_line = gb_string_append_fmt(link_command_line, " %.*s ", LIT(build_context.extra_linker_flags)); - link_command_line = gb_string_append_fmt(link_command_line, " %s ", link_settings); - - result = system_exec_command_line_app("ld-link", link_command_line); - - if (result) { - return result; - } - - if (is_osx && build_context.ODIN_DEBUG) { - // NOTE: macOS links DWARF symbols dynamically. Dsymutil will map the stubs in the exe - // to the symbols in the object file - result = system_exec_command_line_app("dsymutil", "dsymutil %.*s", LIT(output_filename)); - - if (result) { - return result; - } - } - } - } - - return result; -} - gb_internal Array setup_args(int argc, char const **argv) { gbAllocator a = heap_allocator(); @@ -2359,6 +1945,8 @@ gb_internal void print_show_unused(Checker *c) { } gb_internal bool check_env(void) { + TIME_SECTION("init check env"); + gbAllocator a = heap_allocator(); char const *odin_root = gb_get_env("ODIN_ROOT", a); defer (gb_free(a, cast(void *)odin_root)); @@ -2560,6 +2148,7 @@ gb_internal int strip_semicolons(Parser *parser) { } gb_internal void init_terminal(void) { + TIME_SECTION("init terminal"); build_context.has_ansi_terminal_colours = false; gbAllocator a = heap_allocator(); @@ -2626,11 +2215,13 @@ int main(int arg_count, char const **arg_ptr) { return 1; } + TIME_SECTION("init default library collections"); array_init(&library_collections, heap_allocator()); // NOTE(bill): 'core' cannot be (re)defined by the user add_library_collection(str_lit("core"), get_fullpath_relative(heap_allocator(), odin_root_dir(), str_lit("core"))); add_library_collection(str_lit("vendor"), get_fullpath_relative(heap_allocator(), odin_root_dir(), str_lit("vendor"))); + TIME_SECTION("init args"); map_init(&build_context.defined_values); build_context.extra_packages.allocator = heap_allocator(); string_set_init(&build_context.test_names); @@ -2829,9 +2420,11 @@ int main(int arg_count, char const **arg_ptr) { } } + TIME_SECTION("init thread pool"); init_global_thread_pool(); defer (thread_pool_destroy(&global_thread_pool)); + TIME_SECTION("init universal"); init_universal(); // TODO(bill): prevent compiling without a linker diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index b35b28fc0..f5464cab0 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8143c9a6e..fec77733d 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -358,7 +358,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { cg_procedure_end(p); if ( - string_starts_with(p->name, str_lit("runtime@_os_write")) || + // string_starts_with(p->name, str_lit("runtime@_os_write")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); -- cgit v1.2.3 From d8445fd9dfe5bcf9b694c2b83791c88cafcdf322 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 12:53:16 +0100 Subject: Multithread tilde backend --- src/tilde.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++---------- src/tilde.hpp | 14 ++++++++----- src/tilde/tb.lib | Bin 4393788 -> 4161494 bytes src/tilde_proc.cpp | 44 +++++++++++++++++++++++++-------------- src/tilde_stmt.cpp | 2 +- 5 files changed, 88 insertions(+), 32 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 4fd891b17..8bd7e0b43 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -7,6 +7,13 @@ gb_internal TB_Arena *cg_arena(void) { return global_tb_arenas[current_thread_index()]; } +gb_internal void cg_global_arena_init(void) { + global_tb_arenas = slice_make(permanent_allocator(), global_thread_pool.threads.count); + for_array(i, global_tb_arenas) { + global_tb_arenas[i] = tb_default_arena(); + } +} + // returns TB_TYPE_VOID if not trivially possible gb_internal TB_DataType cg_data_type(Type *t) { GB_ASSERT(t != nullptr); @@ -535,7 +542,6 @@ gb_internal cgModule *cg_module_create(Checker *c) { tb_module_set_tls_index(m->mod, 10, "_tls_index"); map_init(&m->values); - array_init(&m->procedures_to_generate, heap_allocator()); map_init(&m->file_id_map); @@ -543,6 +549,8 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->proc_debug_type_map); map_init(&m->proc_proto_map); + array_init(&m->single_threaded_procedure_queue, heap_allocator()); + for_array(id, global_files) { if (AstFile *f = global_files[id]) { @@ -556,12 +564,13 @@ gb_internal cgModule *cg_module_create(Checker *c) { gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); - array_free(&m->procedures_to_generate); map_destroy(&m->file_id_map); map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); map_destroy(&m->proc_proto_map); + array_free(&m->single_threaded_procedure_queue); + tb_module_destroy(m->mod); } @@ -772,6 +781,21 @@ gb_internal String cg_filepath_obj_for_module(cgModule *m) { } +gb_internal WORKER_TASK_PROC(cg_procedure_generate_worker_proc) { + cgProcedure *p = cast(cgProcedure *)data; + cg_procedure_generate(p); + return 0; +} + +gb_internal void cg_add_procedure_to_queue(cgProcedure *p) { + cgModule *m = p->module; + if (m->do_threading) { + thread_pool_add_task(cg_procedure_generate_worker_proc, p); + } else { + array_add(&m->single_threaded_procedure_queue, p); + } +} + gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { TIME_SECTION("Tilde Module Initializtion"); @@ -779,14 +803,13 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { linker_data_init(linker_data, info, c->parser->init_fullpath); - global_tb_arenas = slice_make(permanent_allocator(), global_thread_pool.threads.count); - for_array(i, global_tb_arenas) { - global_tb_arenas[i] = tb_default_arena(); - } + cg_global_arena_init(); cgModule *m = cg_module_create(c); defer (cg_module_destroy(m)); + m->do_threading = true; + TIME_SECTION("Tilde Global Variables"); bool already_has_entry_point = cg_global_variables_create(m); @@ -798,6 +821,7 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { p->is_startup = true; cg_procedure_begin(p); + tb_inst_ret(p->func, 0, nullptr); cg_procedure_end(p); } @@ -807,14 +831,19 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { p->is_startup = true; cg_procedure_begin(p); + tb_inst_ret(p->func, 0, nullptr); cg_procedure_end(p); } auto *min_dep_set = &info->minimum_dependency_set; + Array procedures_to_generate = {}; + array_init(&procedures_to_generate, heap_allocator()); + defer (array_free(&procedures_to_generate)); + for (Entity *e : info->entities) { - String name = e->token.string; - Scope * scope = e->scope; + String name = e->token.string; + Scope *scope = e->scope; if ((scope->flags & ScopeFlag_File) == 0) { continue; @@ -832,15 +861,24 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { continue; } if (cgProcedure *p = cg_procedure_create(m, e)) { - array_add(&m->procedures_to_generate, p); + array_add(&procedures_to_generate, p); } } + for (cgProcedure *p : procedures_to_generate) { + cg_add_procedure_to_queue(p); + } - for (isize i = 0; i < m->procedures_to_generate.count; i++) { - cg_procedure_generate(m->procedures_to_generate[i]); + if (!m->do_threading) { + for (isize i = 0; i < m->single_threaded_procedure_queue.count; i++) { + cgProcedure *p = m->single_threaded_procedure_queue[i]; + cg_procedure_generate(p); + } } + thread_pool_wait(); + + TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; if (build_context.ODIN_DEBUG || true) { switch (build_context.metrics.os) { diff --git a/src/tilde.hpp b/src/tilde.hpp index 44da86c35..ce87f2dfe 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -210,13 +210,14 @@ struct cgModule { CheckerInfo *info; LinkerData * linker_data; - RwMutex values_mutex; - PtrMap values; - StringMap members; + bool do_threading; + Array single_threaded_procedure_queue; - StringMap procedures; + RwMutex values_mutex; + PtrMap values; + StringMap members; + StringMap procedures; PtrMap procedure_values; - Array procedures_to_generate; RecursiveMutex debug_type_mutex; PtrMap debug_type_map; @@ -225,6 +226,7 @@ struct cgModule { RecursiveMutex proc_proto_mutex; PtrMap proc_proto_map; + // NOTE(bill): no need to protect this with a mutex PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) std::atomic nested_type_name_guid; @@ -252,6 +254,8 @@ gb_global isize cg_global_type_info_member_tags_index = 0; gb_internal TB_Arena *cg_arena(void); +gb_internal void cg_add_procedure_to_queue(cgProcedure *p); + gb_internal cgValue cg_value(TB_Global * g, Type *type); gb_internal cgValue cg_value(TB_External *e, Type *type); gb_internal cgValue cg_value(TB_Function *f, Type *type); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index f5464cab0..a60475d1c 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index fec77733d..fe9c6c766 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -35,7 +35,9 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i cgValue *found = string_map_get(&m->members, key); if (found) { cg_add_entity(m, entity, *found); + rw_mutex_lock(&m->values_mutex); p = string_map_must_get(&m->procedures, key); + rw_mutex_unlock(&m->values_mutex); if (!ignore_body && p->func != nullptr) { return nullptr; } @@ -96,7 +98,6 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i p->debug_type = cg_debug_type_for_proc(m, p->type); p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); - tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; } @@ -148,7 +149,6 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li p->debug_type = cg_debug_type_for_proc(m, p->type); p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); - tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; @@ -164,6 +164,8 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { return; } + tb_function_set_prototype(p->func, p->proto, cg_arena()); + if (p->body == nullptr) { return; } @@ -324,19 +326,11 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { } } -gb_internal void cg_procedure_end(cgProcedure *p) { - if (p == nullptr || p->func == nullptr) { - return; - } - if (tb_inst_get_control(p->func)) { - GB_ASSERT(p->type->Proc.result_count == 0); - tb_inst_ret(p->func, 0, nullptr); - } - bool emit_asm = false; - if (string_starts_with(p->name, str_lit("runtime@_os_write"))) { - // emit_asm = true; - } +gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { + cgProcedure *p = cast(cgProcedure *)data; + + bool emit_asm = false; TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); if (emit_asm) { @@ -346,6 +340,24 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } gb_printf_err("\n"); } + + return 0; +} + +gb_internal void cg_procedure_end(cgProcedure *p) { + if (p == nullptr || p->func == nullptr) { + return; + } + if (tb_inst_get_control(p->func)) { + GB_ASSERT(p->type->Proc.result_count == 0); + tb_inst_ret(p->func, 0, nullptr); + } + + if (p->module->do_threading) { + thread_pool_add_task(cg_procedure_compile_worker_proc, p); + } else { + cg_procedure_compile_worker_proc(p); + } } gb_internal void cg_procedure_generate(cgProcedure *p) { @@ -353,10 +365,12 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { return; } + cg_procedure_begin(p); cg_build_stmt(p, p->body); cg_procedure_end(p); + if ( // string_starts_with(p->name, str_lit("runtime@_os_write")) || false @@ -408,7 +422,7 @@ gb_internal void cg_build_nested_proc(cgProcedure *p, AstProcLit *pd, Entity *e) cg_add_entity(m, e, value); array_add(&p->children, nested_proc); - array_add(&m->procedures_to_generate, nested_proc); + cg_add_procedure_to_queue(nested_proc); } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index b25be089d..6cef37ad4 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -2036,9 +2036,9 @@ gb_internal void cg_build_constant_value_decl(cgProcedure *p, AstValueDecl *vd) cgValue value = p->value; - array_add(&p->module->procedures_to_generate, nested_proc); array_add(&p->children, nested_proc); string_map_set(&p->module->members, name, value); + cg_add_procedure_to_queue(nested_proc); } } } -- cgit v1.2.3 From e2593a68838a038dce55719ca3e4e8604dbc43d3 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 14:01:10 +0100 Subject: Update Tilde for testing reg spill stuff --- src/tilde.cpp | 115 +++++++----------------------------------------- src/tilde.hpp | 3 ++ src/tilde/tb.lib | Bin 4393788 -> 4168796 bytes src/tilde_expr.cpp | 4 +- src/tilde_proc.cpp | 30 +++++++++++-- src/tilde_type_info.cpp | 77 ++++++++++++++++++++++++++++++++ 6 files changed, 125 insertions(+), 104 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 7d7b028c1..e765a5c72 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -411,28 +411,27 @@ gb_internal bool cg_global_variables_create(cgModule *m) { // LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section)); } - size_t max_objects = 0; - tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_objects); cgGlobalVariable var = {}; var.var = g; var.decl = decl; if (decl->init_expr != nullptr) { - // TypeAndValue tav = type_and_value_of_expr(decl->init_expr); - // if (!is_type_any(e->type) && !is_type_union(e->type)) { - // if (tav.mode != Addressing_Invalid) { - // if (tav.value.kind != ExactValue_Invalid) { - // ExactValue v = tav.value; - // lbValue init = lb_const_value(m, tav.type, v); - // LLVMSetInitializer(g.value, init.value); - // var.is_initialized = true; - // } - // } - // } - // if (!var.is_initialized && is_type_untyped_nil(tav.type)) { - // var.is_initialized = true; - // } + TypeAndValue tav = type_and_value_of_expr(decl->init_expr); + + isize max_regions = cg_global_const_calculate_region_count(tav.value, e->type); + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_regions); + + if (tav.mode != Addressing_Invalid && + tav.value.kind != ExactValue_Invalid) { + cg_global_const_add_region(m, tav.value, e->type, global, 0); + var.is_initialized = true; + } + if (!var.is_initialized && is_type_untyped_nil(tav.type)) { + var.is_initialized = true; + } + } else { + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), 0); } array_add(&global_variables, var); @@ -443,89 +442,7 @@ gb_internal bool cg_global_variables_create(cgModule *m) { - if (build_context.no_rtti) { - return already_has_entry_point; - } - - CheckerInfo *info = m->info; - { // Add type info data - isize max_type_info_count = info->minimum_dependency_type_info_set.count+1; - // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); - Type *t = alloc_type_array(t_type_info, max_type_info_count); - - TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); - - cgValue value = cg_value(g, alloc_type_pointer(t)); - cg_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(CG_TYPE_INFO_DATA_NAME), t, EntityState_Resolved); - cg_add_entity(m, cg_global_type_info_data_entity, value); - } - - { // Type info member buffer - // NOTE(bill): Removes need for heap allocation by making it global memory - isize count = 0; - - for (Type *t : m->info->type_info_types) { - isize index = cg_type_info_index(m->info, t, false); - if (index < 0) { - continue; - } - - switch (t->kind) { - case Type_Union: - count += t->Union.variants.count; - break; - case Type_Struct: - count += t->Struct.fields.count; - break; - case Type_Tuple: - count += t->Tuple.variables.count; - break; - } - } - - if (count > 0) { - { - char const *name = CG_TYPE_INFO_TYPES_NAME; - Type *t = alloc_type_array(t_type_info_ptr, count); - TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); - cg_global_type_info_member_types = cg_addr(cg_value(g, alloc_type_pointer(t))); - } - { - char const *name = CG_TYPE_INFO_NAMES_NAME; - Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); - cg_global_type_info_member_names = cg_addr(cg_value(g, alloc_type_pointer(t))); - } - { - char const *name = CG_TYPE_INFO_OFFSETS_NAME; - Type *t = alloc_type_array(t_uintptr, count); - TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); - cg_global_type_info_member_offsets = cg_addr(cg_value(g, alloc_type_pointer(t))); - } - - { - char const *name = CG_TYPE_INFO_USINGS_NAME; - Type *t = alloc_type_array(t_bool, count); - TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); - cg_global_type_info_member_usings = cg_addr(cg_value(g, alloc_type_pointer(t))); - } - - { - char const *name = CG_TYPE_INFO_TAGS_NAME; - Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); - cg_global_type_info_member_tags = cg_addr(cg_value(g, alloc_type_pointer(t))); - } - } - - cg_setup_type_info_data(m); - } + cg_setup_type_info_data(m); return already_has_entry_point; } diff --git a/src/tilde.hpp b/src/tilde.hpp index 289cc3e6e..d22043918 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -256,6 +256,9 @@ gb_internal TB_Arena *cg_arena(void); gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); +gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type); +gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset); + gb_internal cgValue cg_value(TB_Global * g, Type *type); gb_internal cgValue cg_value(TB_External *e, Type *type); gb_internal cgValue cg_value(TB_Function *f, Type *type); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 56b9c339a..4e97a0306 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 822c637ca..07e60f1a6 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -547,7 +547,7 @@ gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left case Token_Gt: res = tb_inst_cmp_igt(p->func, lhs, rhs, is_signed); break; case Token_GtEq: res = tb_inst_cmp_ige(p->func, lhs, rhs, is_signed); break; case Token_Lt: res = tb_inst_cmp_ilt(p->func, lhs, rhs, is_signed); break; - case Token_LtEq: res = tb_inst_cmp_ige(p->func, lhs, rhs, is_signed); break; + case Token_LtEq: res = tb_inst_cmp_ile(p->func, lhs, rhs, is_signed); break; } GB_ASSERT(res != nullptr); @@ -562,7 +562,7 @@ gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left case Token_Gt: res = tb_inst_cmp_fgt(p->func, lhs, rhs); break; case Token_GtEq: res = tb_inst_cmp_fge(p->func, lhs, rhs); break; case Token_Lt: res = tb_inst_cmp_flt(p->func, lhs, rhs); break; - case Token_LtEq: res = tb_inst_cmp_fge(p->func, lhs, rhs); break; + case Token_LtEq: res = tb_inst_cmp_fle(p->func, lhs, rhs); break; } GB_ASSERT(res != nullptr); return cg_value(res, t_bool); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index fe9c6c766..fb66e6adb 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -235,7 +235,24 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only String name = e->token.string; - tb_node_append_attrib(param_ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + TB_DebugType *param_debug_type = debug_type; + TB_Node * param_ptr_to_use = param_ptr; + if (rule == TB_PASSING_INDIRECT) { + // HACK TODO(bill): this is just to get the debug information + TB_CharUnits ptr_size = cast(TB_CharUnits)build_context.ptr_size; + TB_Node *dummy_param = tb_inst_local(p->func, ptr_size, ptr_size); + tb_inst_store(p->func, TB_TYPE_PTR, dummy_param, param_ptr, ptr_size, false); + param_ptr_to_use = dummy_param; + param_debug_type = tb_debug_create_ptr(p->module->mod, param_debug_type); + } + tb_node_append_attrib( + param_ptr_to_use, + tb_function_attrib_variable( + p->func, + name.len, cast(char const *)name.text, + param_debug_type + ) + ); } cgAddr addr = cg_addr(local); if (e) { @@ -332,13 +349,20 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { bool emit_asm = false; + if ( + string_starts_with(p->name, str_lit("runtime@_os_write")) || + false + ) { + emit_asm = true; + } + TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); if (emit_asm) { TB_Assembly *assembly = tb_output_get_asm(output); for (TB_Assembly *node = assembly; node != nullptr; node = node->next) { - gb_printf_err("%.*s", cast(int)node->length, node->data); + fprintf(stdout, "%.*s", cast(int)node->length, node->data); } - gb_printf_err("\n"); + fprintf(stdout, "\n"); } return 0; diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index 5d6a613b3..d3613cde8 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -2,7 +2,84 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { if (build_context.no_rtti) { return; } + CheckerInfo *info = m->info; + { // Add type info data + isize max_type_info_count = info->minimum_dependency_type_info_set.count+1; + // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); + Type *t = alloc_type_array(t_type_info, max_type_info_count); + + TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); + + cgValue value = cg_value(g, alloc_type_pointer(t)); + cg_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(CG_TYPE_INFO_DATA_NAME), t, EntityState_Resolved); + cg_add_entity(m, cg_global_type_info_data_entity, value); + } + + { // Type info member buffer + // NOTE(bill): Removes need for heap allocation by making it global memory + isize count = 0; + + for (Type *t : m->info->type_info_types) { + isize index = cg_type_info_index(m->info, t, false); + if (index < 0) { + continue; + } + + switch (t->kind) { + case Type_Union: + count += t->Union.variants.count; + break; + case Type_Struct: + count += t->Struct.fields.count; + break; + case Type_Tuple: + count += t->Tuple.variables.count; + break; + } + } + + if (count > 0) { + { + char const *name = CG_TYPE_INFO_TYPES_NAME; + Type *t = alloc_type_array(t_type_info_ptr, count); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); + cg_global_type_info_member_types = cg_addr(cg_value(g, alloc_type_pointer(t))); + } + { + char const *name = CG_TYPE_INFO_NAMES_NAME; + Type *t = alloc_type_array(t_string, count); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); + cg_global_type_info_member_names = cg_addr(cg_value(g, alloc_type_pointer(t))); + } + { + char const *name = CG_TYPE_INFO_OFFSETS_NAME; + Type *t = alloc_type_array(t_uintptr, count); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); + cg_global_type_info_member_offsets = cg_addr(cg_value(g, alloc_type_pointer(t))); + } + + { + char const *name = CG_TYPE_INFO_USINGS_NAME; + Type *t = alloc_type_array(t_bool, count); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); + cg_global_type_info_member_usings = cg_addr(cg_value(g, alloc_type_pointer(t))); + } + + { + char const *name = CG_TYPE_INFO_TAGS_NAME; + Type *t = alloc_type_array(t_string, count); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count*2); + cg_global_type_info_member_tags = cg_addr(cg_value(g, alloc_type_pointer(t))); + } + } + } gb_unused(info); -- cgit v1.2.3 From cf77a0e2b4b0cfcc03ae3c160a20b17944f7765c Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 15:18:20 +0100 Subject: Update Tilde to fix reg alloc bug --- src/tilde.cpp | 2 +- src/tilde/tb.lib | Bin 4168796 -> 4164088 bytes src/tilde_proc.cpp | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index e765a5c72..89075da75 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -799,7 +799,7 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; - if (build_context.ODIN_DEBUG || true) { + if (build_context.ODIN_DEBUG) { switch (build_context.metrics.os) { case TargetOs_windows: debug_format = TB_DEBUGFMT_CODEVIEW; diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 4e97a0306..7ec145bda 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index fb66e6adb..b3c81a7d5 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -350,7 +350,7 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { bool emit_asm = false; if ( - string_starts_with(p->name, str_lit("runtime@_os_write")) || + // string_starts_with(p->name, str_lit("runtime@_os_write")) || false ) { emit_asm = true; -- cgit v1.2.3 From 78116e0ea24aef3f663832edfb5f9cd6aa7b6e57 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 15:46:54 +0100 Subject: Implement for in statements for array-like values --- src/tilde_expr.cpp | 26 ++--- src/tilde_proc.cpp | 2 +- src/tilde_stmt.cpp | 318 +++++++++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 308 insertions(+), 38 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 07e60f1a6..993270c14 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -2417,22 +2417,20 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { // break; // } - // case Type_Array: { - // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); - - // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + case Type_Array: { + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - // populate(p, cl->elems, &temp_data, type); + populate(p, cl->elems, &temp_data, type); - // cgValue dst_ptr = cg_addr_get_ptr(p, v); - // for_array(i, temp_data) { - // i32 index = cast(i32)(temp_data[i].elem_index); - // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); - // } + cgValue dst_ptr = cg_addr_get_ptr(p, v); + for_array(i, temp_data) { + i32 index = cast(i32)(temp_data[i].elem_index); + temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + } - // assign_array(p, temp_data); - // break; - // } + assign_array(p, temp_data); + break; + } // case Type_EnumeratedArray: { // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); @@ -2468,7 +2466,7 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { } assign_array(p, temp_data); - cg_fill_slice(p, v, data, cg_const_int(p, t_int, cl->max_count)); + cg_fill_slice(p, v, data, cg_const_int(p, t_int, count)); return v; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index b3c81a7d5..ed28f5016 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -396,7 +396,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { if ( - // string_starts_with(p->name, str_lit("runtime@_os_write")) || + // string_starts_with(p->name, str_lit("bug@main")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 7ad6a9417..f89dbdf03 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1280,6 +1280,25 @@ gb_internal void cg_emit_increment(cgProcedure *p, cgValue addr) { } +gb_internal void cg_range_stmt_store_val(cgProcedure *p, Ast *stmt_val, cgValue const &value) { + Entity *e = entity_of_node(stmt_val); + if (e == nullptr) { + return; + } + + if (e->flags & EntityFlag_Value) { + if (value.kind == cgValue_Addr) { + cgValue ptr = cg_address_from_load_or_generate_local(p, value); + cg_add_entity(p->module, e, ptr); + return; + } + } + + cgAddr addr = cg_add_local(p, e->type, e, false); + cg_addr_store(p, addr, value); + return; +} + gb_internal void cg_build_range_stmt_interval(cgProcedure *p, AstBinaryExpr *node, AstRangeStmt *rs, Scope *scope) { bool ADD_EXTRA_WRAPPING_CHECK = true; @@ -1341,27 +1360,8 @@ gb_internal void cg_build_range_stmt_interval(cgProcedure *p, AstBinaryExpr *nod cgValue val = cg_addr_load(p, value); cgValue idx = cg_addr_load(p, index); - auto const &store_val = [](cgProcedure *p, Ast *stmt_val, cgValue const &value) { - Entity *e = entity_of_node(stmt_val); - if (e == nullptr) { - return; - } - - if (e->flags & EntityFlag_Value) { - if (value.kind == cgValue_Addr) { - cgValue ptr = cg_address_from_load_or_generate_local(p, value); - cg_add_entity(p->module, e, ptr); - return; - } - } - - cgAddr addr = cg_add_local(p, e->type, e, false); - cg_addr_store(p, addr, value); - return; - }; - - if (val0_type) store_val(p, val0, val); - if (val1_type) store_val(p, val1, idx); + if (val0_type) cg_range_stmt_store_val(p, val0, val); + if (val1_type) cg_range_stmt_store_val(p, val1, idx); { @@ -1402,6 +1402,147 @@ gb_internal void cg_build_range_stmt_interval(cgProcedure *p, AstBinaryExpr *nod } tb_inst_set_control(p->func, done); +} + +gb_internal void cg_build_range_stmt_indexed(cgProcedure *p, cgValue expr, Type *val_type, cgValue count_ptr, + cgValue *val_, cgValue *idx_, TB_Node **loop_, TB_Node **done_, + bool is_reverse) { + cgValue count = {}; + Type *expr_type = base_type(type_deref(expr.type)); + switch (expr_type->kind) { + case Type_Array: + count = cg_const_int(p, t_int, expr_type->Array.count); + break; + } + + cgValue val = {}; + cgValue idx = {}; + TB_Node *loop = nullptr; + TB_Node *done = nullptr; + TB_Node *body = nullptr; + + loop = cg_control_region(p, "for_index_loop"); + body = cg_control_region(p, "for_index_body"); + done = cg_control_region(p, "for_index_done"); + + cgAddr index = cg_add_local(p, t_int, nullptr, false); + + if (!is_reverse) { + /* + for x, i in array { + ... + } + + i := -1 + for { + i += 1 + if !(i < len(array)) { + break + } + #no_bounds_check x := array[i] + ... + } + */ + + cg_addr_store(p, index, cg_const_int(p, t_int, cast(u64)-1)); + + cg_emit_goto(p, loop); + tb_inst_set_control(p->func, loop); + + cgValue incr = cg_emit_arith(p, Token_Add, cg_addr_load(p, index), cg_const_int(p, t_int, 1), t_int); + cg_addr_store(p, index, incr); + + if (count.node == nullptr) { + GB_ASSERT(count_ptr.node != nullptr); + count = cg_emit_load(p, count_ptr); + } + cgValue cond = cg_emit_comp(p, Token_Lt, incr, count); + cg_emit_if(p, cond, body, done); + } else { + // NOTE(bill): REVERSED LOGIC + /* + #reverse for x, i in array { + ... + } + + i := len(array) + for { + i -= 1 + if i < 0 { + break + } + #no_bounds_check x := array[i] + ... + } + */ + + if (count.node == nullptr) { + GB_ASSERT(count_ptr.node != nullptr); + count = cg_emit_load(p, count_ptr); + } + count = cg_emit_conv(p, count, t_int); + cg_addr_store(p, index, count); + + cg_emit_goto(p, loop); + tb_inst_set_control(p->func, loop); + + cgValue incr = cg_emit_arith(p, Token_Sub, cg_addr_load(p, index), cg_const_int(p, t_int, 1), t_int); + cg_addr_store(p, index, incr); + + cgValue anti_cond = cg_emit_comp(p, Token_Lt, incr, cg_const_int(p, t_int, 0)); + cg_emit_if(p, anti_cond, done, body); + } + + tb_inst_set_control(p->func, body); + + idx = cg_addr_load(p, index); + switch (expr_type->kind) { + case Type_Array: { + if (val_type != nullptr) { + val = cg_emit_load(p, cg_emit_array_ep(p, expr, idx)); + } + break; + } + case Type_EnumeratedArray: { + if (val_type != nullptr) { + val = cg_emit_load(p, cg_emit_array_ep(p, expr, idx)); + // NOTE(bill): Override the idx value for the enumeration + Type *index_type = expr_type->EnumeratedArray.index; + if (compare_exact_values(Token_NotEq, *expr_type->EnumeratedArray.min_value, exact_value_u64(0))) { + idx = cg_emit_arith(p, Token_Add, idx, cg_const_value(p, index_type, *expr_type->EnumeratedArray.min_value), index_type); + } + } + break; + } + case Type_Slice: { + if (val_type != nullptr) { + cgValue elem = cg_builtin_raw_data(p, expr); + val = cg_emit_load(p, cg_emit_ptr_offset(p, elem, idx)); + } + break; + } + case Type_DynamicArray: { + if (val_type != nullptr) { + cgValue elem = cg_emit_struct_ep(p, expr, 0); + elem = cg_emit_load(p, elem); + val = cg_emit_load(p, cg_emit_ptr_offset(p, elem, idx)); + } + break; + } + case Type_Struct: { + GB_ASSERT(is_type_soa_struct(expr_type)); + break; + } + + default: + GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type)); + break; + } + + if (val_) *val_ = val; + if (idx_) *idx_ = idx; + if (loop_) *loop_ = loop; + if (done_) *done_ = done; } @@ -1410,13 +1551,144 @@ gb_internal void cg_build_range_stmt(cgProcedure *p, Ast *node) { Ast *expr = unparen_expr(rs->expr); - if (is_ast_range(expr)) { cg_build_range_stmt_interval(p, &expr->BinaryExpr, rs, rs->scope); return; } - GB_PANIC("TODO(bill): cg_build_range_stmt"); + Type *expr_type = type_of_expr(expr); + if (expr_type != nullptr) { + Type *et = base_type(type_deref(expr_type)); + if (is_type_soa_struct(et)) { + GB_PANIC("TODO(bill): #soa array range statements"); + // cg_build_range_stmt_struct_soa(p, rs, scope); + return; + } + } + + cg_scope_open(p, rs->scope); + + + Ast *val0 = rs->vals.count > 0 ? cg_strip_and_prefix(rs->vals[0]) : nullptr; + Ast *val1 = rs->vals.count > 1 ? cg_strip_and_prefix(rs->vals[1]) : nullptr; + Type *val0_type = nullptr; + Type *val1_type = nullptr; + if (val0 != nullptr && !is_blank_ident(val0)) { + val0_type = type_of_expr(val0); + } + if (val1 != nullptr && !is_blank_ident(val1)) { + val1_type = type_of_expr(val1); + } + + cgValue val = {}; + cgValue key = {}; + TB_Node *loop = nullptr; + TB_Node *done = nullptr; + bool is_map = false; + TypeAndValue tav = type_and_value_of_expr(expr); + + if (tav.mode == Addressing_Type) { + GB_PANIC("TODO(bill): range statement over enum type"); + } else { + Type *expr_type = type_of_expr(expr); + Type *et = base_type(type_deref(expr_type)); + switch (et->kind) { + case Type_Map: { + is_map = true; + cgValue map = cg_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(map.type))) { + map = cg_emit_load(p, map); + } + GB_PANIC("TODO(bill): cg_build_range_map"); + // cg_build_range_map(p, map, val1_type, &val, &key, &loop, &done); + break; + } + case Type_Array: { + cgValue array = cg_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = cg_emit_load(p, array); + } + cgAddr count_ptr = cg_add_local(p, t_int, nullptr, false); + cg_addr_store(p, count_ptr, cg_const_int(p, t_int, et->Array.count)); + cg_build_range_stmt_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse); + break; + } + case Type_EnumeratedArray: { + cgValue array = cg_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = cg_emit_load(p, array); + } + cgAddr count_ptr = cg_add_local(p, t_int, nullptr, false); + cg_addr_store(p, count_ptr, cg_const_int(p, t_int, et->EnumeratedArray.count)); + cg_build_range_stmt_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done, rs->reverse); + break; + } + case Type_DynamicArray: { + cgValue count_ptr = {}; + cgValue array = cg_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = cg_emit_load(p, array); + } + count_ptr = cg_emit_struct_ep(p, array, 1); + GB_PANIC("TODO(bill): cg_build_range_stmt_indexed"); + // cg_build_range_stmt_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse); + break; + } + case Type_Slice: { + cgValue count_ptr = {}; + cgValue slice = cg_build_expr(p, expr); + if (is_type_pointer(slice.type)) { + count_ptr = cg_emit_struct_ep(p, slice, 1); + slice = cg_emit_load(p, slice); + } else { + count_ptr = cg_add_local(p, t_int, nullptr, false).addr; + cg_emit_store(p, count_ptr, cg_builtin_len(p, slice)); + } + cg_build_range_stmt_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse); + break; + } + case Type_Basic: { + cgValue string = cg_build_expr(p, expr); + if (is_type_pointer(string.type)) { + string = cg_emit_load(p, string); + } + if (is_type_untyped(expr_type)) { + cgAddr s = cg_add_local(p, default_type(string.type), nullptr, false); + cg_addr_store(p, s, string); + string = cg_addr_load(p, s); + } + Type *t = base_type(string.type); + GB_ASSERT(!is_type_cstring(t)); + GB_PANIC("TODO(bill): cg_build_range_string"); + // cg_build_range_string(p, string, val0_type, &val, &key, &loop, &done, rs->reverse); + break; + } + case Type_Tuple: + GB_PANIC("TODO(bill): cg_build_range_tuple"); + // cg_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done); + break; + default: + GB_PANIC("Cannot range over %s", type_to_string(expr_type)); + break; + } + } + + if (is_map) { + if (val0_type) cg_range_stmt_store_val(p, val0, key); + if (val1_type) cg_range_stmt_store_val(p, val1, val); + } else { + if (val0_type) cg_range_stmt_store_val(p, val0, val); + if (val1_type) cg_range_stmt_store_val(p, val1, key); + } + + cg_push_target_list(p, rs->label, done, loop, nullptr); + + cg_build_stmt(p, rs->body); + + cg_scope_close(p, cgDeferExit_Default, nullptr); + cg_pop_target_list(p); + cg_emit_goto(p, loop); + tb_inst_set_control(p->func, done); } gb_internal bool cg_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss) { -- cgit v1.2.3 From 28fca190ee11f5c19d30007f20caa4c7bf89f655 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 16:09:01 +0100 Subject: Fix `transmute(uintptr)ptr` etc --- src/tilde.cpp | 18 ++++++++++++++++++ src/tilde.hpp | 5 ++++- src/tilde_builtin.cpp | 16 +++++++++++++++- src/tilde_expr.cpp | 41 ++++++++++++++++++++++++++++++++++++++++- src/tilde_proc.cpp | 6 ++++++ src/tilde_stmt.cpp | 3 +-- 6 files changed, 84 insertions(+), 5 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 89075da75..7574ea6b9 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -243,6 +243,24 @@ gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_ return -1; } +gb_internal cgValue cg_global_type_info_data_ptr(cgProcedure *p) { + cgValue v = cg_find_value_from_entity(p->module, cg_global_type_info_data_entity); + return cg_flatten_value(p, v); +} + + +gb_internal cgValue cg_type_info(cgProcedure *p, Type *type) { + GB_ASSERT(!build_context.no_rtti); + + type = default_type(type); + + isize index = cg_type_info_index(p->module->info, type); + GB_ASSERT(index >= 0); + + cgValue data = cg_global_type_info_data_ptr(p); + return cg_emit_array_epi(p, data, index); +} + gb_internal u64 cg_typeid_as_u64(cgModule *m, Type *type) { GB_ASSERT(!build_context.no_rtti); diff --git a/src/tilde.hpp b/src/tilde.hpp index a548252d9..2d7b2e1c3 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -301,7 +301,7 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results); gb_internal void cg_build_range_stmt(cgProcedure *p, Ast *node); - +gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e); gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); @@ -322,6 +322,9 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right); gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgValue rhs, Type *type); +gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice const &args); +gb_internal cgValue cg_emit_runtime_call(cgProcedure *p, char const *name, Slice const &args); + gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index b40eacc7f..e30ff1cb0 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -236,7 +236,6 @@ gb_internal cgValue cg_builtin_mem_copy_non_overlapping(cgProcedure *p, cgValue } - gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -419,6 +418,21 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr return cg_emit_arith(p, Token_Quo, diff, cg_const_int(p, t_int, type_size_of(elem)), t_int); } + case BuiltinProc_type_info_of: + { + Ast *arg = ce->args[0]; + TypeAndValue tav = type_and_value_of_expr(arg); + if (tav.mode == Addressing_Type) { + Type *t = default_type(type_of_expr(arg)); + return cg_type_info(p, t); + } + GB_ASSERT(is_type_typeid(tav.type)); + + auto args = slice_make(permanent_allocator(), 1); + args[0] = cg_build_expr(p, arg); + return cg_emit_runtime_call(p, "__type_info_of", args); + } + } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 993270c14..8737e75cd 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -191,7 +191,46 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%d %s -> %s", dt.type, type_to_string(value.type), type_to_string(type)); value.type = type; if (value.node->dt.raw != dt.raw) { - value.node = tb_inst_bitcast(p->func, value.node, dt); + switch (value.node->dt.type) { + case TB_INT: + switch (value.node->dt.type) { + case TB_INT: + break; + case TB_FLOAT: + value.node = tb_inst_bitcast(p->func, value.node, dt); + break; + case TB_PTR: + value.node = tb_inst_int2ptr(p->func, value.node); + break; + } + break; + case TB_FLOAT: + switch (value.node->dt.type) { + case TB_INT: + value.node = tb_inst_bitcast(p->func, value.node, dt); + break; + case TB_FLOAT: + break; + case TB_PTR: + value.node = tb_inst_bitcast(p->func, value.node, TB_TYPE_INTPTR); + value.node = tb_inst_int2ptr(p->func, value.node); + break; + } + break; + case TB_PTR: + switch (value.node->dt.type) { + case TB_INT: + value.node = tb_inst_ptr2int(p->func, value.node, dt); + break; + case TB_FLOAT: + value.node = tb_inst_ptr2int(p->func, value.node, TB_TYPE_INTPTR); + value.node = tb_inst_bitcast(p->func, value.node, dt); + break; + case TB_PTR: + break; + } + break; + } } return value; case cgValue_Addr: diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index ed28f5016..acc31ce67 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -677,6 +677,12 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice return cg_value_multi(multi, pt->results); } +gb_internal cgValue cg_emit_runtime_call(cgProcedure *p, char const *name, Slice const &args) { + AstPackage *pkg = p->module->info->runtime_package; + Entity *e = scope_lookup_current(pkg->scope, make_string_c(name)); + cgValue value = cg_find_procedure_value_from_entity(p->module, e); + return cg_emit_call(p, value, args); +} gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos) { switch (param_value.kind) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index f89dbdf03..8b577dfeb 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1630,8 +1630,7 @@ gb_internal void cg_build_range_stmt(cgProcedure *p, Ast *node) { array = cg_emit_load(p, array); } count_ptr = cg_emit_struct_ep(p, array, 1); - GB_PANIC("TODO(bill): cg_build_range_stmt_indexed"); - // cg_build_range_stmt_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse); + cg_build_range_stmt_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done, rs->reverse); break; } case Type_Slice: { -- cgit v1.2.3 From 28c97a94670b2b1cad801e9e9d3b5d465f9435d8 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 17:12:23 +0100 Subject: Begin work on setting up type information table --- src/tilde.cpp | 28 ++++- src/tilde.hpp | 2 + src/tilde_const.cpp | 72 ++++++++++++- src/tilde_proc.cpp | 2 + src/tilde_type_info.cpp | 281 +++++++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 366 insertions(+), 19 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 7574ea6b9..82d30215e 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -199,6 +199,13 @@ gb_internal void cg_set_debug_pos_from_node(cgProcedure *p, Ast *node) { } } +gb_internal void cg_add_symbol(cgModule *m, Entity *e, TB_Symbol *symbol) { + if (e) { + rw_mutex_lock(&m->values_mutex); + map_set(&m->symbols, e, symbol); + rw_mutex_unlock(&m->values_mutex); + } +} gb_internal void cg_add_entity(cgModule *m, Entity *e, cgValue const &val) { if (e) { @@ -221,12 +228,27 @@ gb_internal void cg_add_procedure_value(cgModule *m, cgProcedure *p) { rw_mutex_lock(&m->values_mutex); if (p->entity != nullptr) { map_set(&m->procedure_values, p->func, p->entity); + if (p->symbol != nullptr) { + map_set(&m->symbols, p->entity, p->symbol); + } } string_map_set(&m->procedures, p->name, p); rw_mutex_unlock(&m->values_mutex); } +gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { + if (e) { + rw_mutex_lock(&m->values_mutex); + defer (rw_mutex_unlock(&m->values_mutex)); + TB_Symbol **found = map_get(&m->symbols, e); + if (found) { + return *found; + } + } + return nullptr; +} + gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { auto *set = &info->minimum_dependency_type_info_set; isize index = type_info_index(info, type, err_on_not_found); @@ -449,11 +471,13 @@ gb_internal bool cg_global_variables_create(cgModule *m) { var.is_initialized = true; } } else { - tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), 0); + i64 max_regions = cg_global_const_calculate_region_count_from_basic_type(e->type); + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_regions); } array_add(&global_variables, var); + cg_add_symbol(m, e, cast(TB_Symbol *)global); cg_add_entity(m, e, g); cg_add_member(m, name, g); } @@ -478,6 +502,7 @@ gb_internal cgModule *cg_module_create(Checker *c) { tb_module_set_tls_index(m->mod, 10, "_tls_index"); map_init(&m->values); + map_init(&m->symbols); map_init(&m->file_id_map); @@ -500,6 +525,7 @@ gb_internal cgModule *cg_module_create(Checker *c) { gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); + map_destroy(&m->symbols); map_destroy(&m->file_id_map); map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); diff --git a/src/tilde.hpp b/src/tilde.hpp index 2d7b2e1c3..e4f047017 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -214,6 +214,7 @@ struct cgModule { RwMutex values_mutex; PtrMap values; + PtrMap symbols; StringMap members; StringMap procedures; PtrMap procedure_values; @@ -257,6 +258,7 @@ gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type); +gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *type); gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset); gb_internal cgValue cg_value(TB_Global * g, Type *type); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 11126e07a..60f8e636b 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -143,6 +143,33 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } +gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { + // Source_Code_Location :: struct { + // file_path: string, + // line, column: i32, + // procedure: string, + // } + + i64 file_path_offset = type_offset_of(t_source_code_location, 0); + i64 line_offset = type_offset_of(t_source_code_location, 1); + i64 column_offset = type_offset_of(t_source_code_location, 2); + i64 procedure_offset = type_offset_of(t_source_code_location, 3); + + String file_path = get_file_path_string(pos.file_id); + if (file_path.len != 0) { + cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); + } + + void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); + void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); + cg_write_int_at_ptr(line_ptr, pos.line, t_i32); + cg_write_int_at_ptr(column_ptr, pos.column, t_i32); + + if (proc_name.len != 0) { + cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); + } +} + gb_internal bool cg_elem_type_can_be_constant(Type *t) { t = base_type(t); if (t == t_invalid) { @@ -201,10 +228,11 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ return 1; case Type_Pointer: case Type_MultiPointer: + return 2; // allows for offsets case Type_Proc: - return true; + return 1; case Type_Slice: - return 2; + return 3; // alows for offsets case Type_DynamicArray: return 5; case Type_Map: @@ -221,6 +249,46 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ case Type_Matrix: return 1; + case Type_Array: + { + Type *elem = type->Array.elem; + i64 count = cg_global_const_calculate_region_count_from_basic_type(elem); + return count*type->Array.count; + } + case Type_EnumeratedArray: + { + Type *elem = type->EnumeratedArray.elem; + i64 count = cg_global_const_calculate_region_count_from_basic_type(elem); + return count*type->EnumeratedArray.count; + } + + case Type_Struct: + if (type->Struct.is_raw_union) { + i64 max_count = 0; + for (Entity *f : type->Struct.fields) { + i64 count = cg_global_const_calculate_region_count_from_basic_type(f->type); + max_count = gb_max(count, max_count); + } + return max_count; + } else { + i64 max_count = 0; + for (Entity *f : type->Struct.fields) { + max_count += cg_global_const_calculate_region_count_from_basic_type(f->type); + } + return max_count; + } + break; + case Type_Union: + { + i64 max_count = 0; + for (Type *t : type->Union.variants) { + i64 count = cg_global_const_calculate_region_count_from_basic_type(t); + max_count = gb_max(count, max_count); + } + return max_count+1; + } + break; + default: GB_PANIC("TODO(bill): %s", type_to_string(type)); break; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index acc31ce67..a805b2985 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -103,6 +103,8 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } p->value = cg_value(p->symbol, p->type); + + cg_add_symbol(m, entity, p->symbol); cg_add_entity(m, entity, p->value); cg_add_member(m, p->name, p->value); cg_add_procedure_value(m, p); diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index d3613cde8..1e86f6644 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -1,3 +1,16 @@ +gb_internal void cg_global_const_type_info_ptr(cgModule *m, TB_Global *type_info_array, Type *type, TB_Global *global, i64 offset) { + i64 index_in_bytes = cast(i64)cg_type_info_index(m->info, type); + index_in_bytes *= type_size_of(t_type_info); + + void *ti_ptr_ptr = tb_global_add_region(m->mod, global, offset, build_context.ptr_size); + // NOTE(bill): define the byte offset for the pointer + cg_write_int_at_ptr(ti_ptr_ptr, index_in_bytes, t_uintptr); + + // NOTE(bill): this will add to the byte offset set previously + tb_global_add_symbol_reloc(m->mod, global, offset, cast(TB_Symbol *)type_info_array); +} + + gb_internal void cg_setup_type_info_data(cgModule *m) { if (build_context.no_rtti) { return; @@ -9,11 +22,14 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); Type *t = alloc_type_array(t_type_info, max_type_info_count); + i64 max_objects = cast(i64)max_type_info_count * cg_global_const_calculate_region_count_from_basic_type(t_type_info); + TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_objects); cgValue value = cg_value(g, alloc_type_pointer(t)); cg_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(CG_TYPE_INFO_DATA_NAME), t, EntityState_Resolved); + cg_add_symbol(m, cg_global_type_info_data_entity, cast(TB_Symbol *)g); cg_add_entity(m, cg_global_type_info_data_entity, value); } @@ -83,22 +99,255 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { gb_unused(info); - // i64 global_type_info_data_entity_count = 0; - // { - // // NOTE(bill): Set the type_table slice with the global backing array - // cgValue global_type_table = cg_find_runtime_value(m, str_lit("type_table")); - // Type *type = base_type(cg_global_type_info_data_entity->type); - // GB_ASSERT(is_type_array(type)); - // global_type_info_data_entity_count = type->Array.count; + i64 global_type_info_data_entity_count = 0; + + // NOTE(bill): Set the type_table slice with the global backing array + TB_Global *type_table_slice = cast(TB_Global *)cg_find_symbol_from_entity(m, scope_lookup_current(m->info->runtime_package->scope, str_lit("type_table"))); + GB_ASSERT(type_table_slice != nullptr); + + TB_Global *type_table_array = cast(TB_Global *)cg_find_symbol_from_entity(m, cg_global_type_info_data_entity); + GB_ASSERT(type_table_array != nullptr); + + Type *type = base_type(cg_global_type_info_data_entity->type); + GB_ASSERT(is_type_array(type)); + global_type_info_data_entity_count = type->Array.count; + + tb_global_add_symbol_reloc(m->mod, type_table_slice, 0, cast(TB_Symbol *)type_table_array); + + void *len_ptr = tb_global_add_region(m->mod, type_table_slice, build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, type->Array.count, t_int); + + // Useful types + Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags")); + Type *t_type_info_flags = type_info_flags_entity->type; + GB_ASSERT(type_size_of(t_type_info_flags) == 4); + + auto entries_handled = slice_make(heap_allocator(), cast(isize)global_type_info_data_entity_count); + defer (gb_free(heap_allocator(), entries_handled.data)); + entries_handled[0] = true; + + + i64 type_info_size = type_size_of(t_type_info); + i64 size_offset = type_offset_of(t_type_info, 0); + i64 align_offset = type_offset_of(t_type_info, 1); + i64 flags_offset = type_offset_of(t_type_info, 2); + i64 id_offset = type_offset_of(t_type_info, 3); + i64 variant_offset = type_offset_of(t_type_info, 4); + + Type *type_info_union = base_type(t_type_info)->Struct.fields[4]->type; + GB_ASSERT(type_info_union->kind == Type_Union); + + i64 union_tag_offset = type_info_union->Union.variant_block_size; + Type *ti_union_tag_type = union_tag_type(type_info_union); + u64 union_tag_type_size = type_size_of(ti_union_tag_type); + + for_array(type_info_type_index, info->type_info_types) { + Type *t = info->type_info_types[type_info_type_index]; + if (t == nullptr || t == t_invalid) { + continue; + } + + isize entry_index = cg_type_info_index(info, t, false); + if (entry_index <= 0) { + continue; + } + + if (entries_handled[entry_index]) { + continue; + } + entries_handled[entry_index] = true; + + TB_Global *global = type_table_array; + + i64 offset = entry_index * type_info_size; + + i64 size = type_size_of(t); + i64 align = type_align_of(t); + u32 flags = type_info_flags_of_type(t); + u64 id = cg_typeid_as_u64(m, t); + + void *size_ptr = tb_global_add_region(m->mod, global, offset+size_offset, build_context.int_size); + void *align_ptr = tb_global_add_region(m->mod, global, offset+align_offset, build_context.int_size); + void *flags_ptr = tb_global_add_region(m->mod, global, offset+flags_offset, 4); + void *id_ptr = tb_global_add_region(m->mod, global, offset+id_offset, build_context.ptr_size); + cg_write_int_at_ptr (size_ptr, size, t_int); + cg_write_int_at_ptr (align_ptr, align, t_int); + cg_write_int_at_ptr (flags_ptr, flags, t_u32); + cg_write_uint_at_ptr(id_ptr, id, t_typeid); + + + // add data to the offset to make it easier to deal with later on + offset += variant_offset; + + Type *tag_type = nullptr; + + switch (t->kind) { + case Type_Named: { + // Type_Info_Named :: struct { + // name: string, + // base: ^Type_Info, + // pkg: string, + // loc: Source_Code_Location, + // } + tag_type = t_type_info_named; + + if (t->Named.type_name->pkg) { + i64 pkg_offset = type_offset_of(tag_type, 2); + String pkg_name = t->Named.type_name->pkg->name; + cg_global_const_string(m, pkg_name, t_string, global, offset+pkg_offset); + } + + String proc_name = {}; + if (t->Named.type_name->parent_proc_decl) { + DeclInfo *decl = t->Named.type_name->parent_proc_decl; + if (decl->entity && decl->entity->kind == Entity_Procedure) { + i64 name_offset = type_offset_of(tag_type, 0); + proc_name = decl->entity->token.string; + cg_global_const_string(m, proc_name, t_string, global, offset+name_offset); + } + } + + i64 loc_offset = type_offset_of(tag_type, 3); + TokenPos pos = t->Named.type_name->token.pos; + cg_global_source_code_location_const(m, proc_name, pos, global, offset+loc_offset); + + i64 base_offset = type_offset_of(tag_type, 1); + cg_global_const_type_info_ptr(m, type_table_array, t->Named.base, global, offset+base_offset); + break; + } + + case Type_Basic: + switch (t->Basic.kind) { + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + tag_type = t_type_info_boolean; + break; + + case Basic_i8: + case Basic_u8: + case Basic_i16: + case Basic_u16: + case Basic_i32: + case Basic_u32: + case Basic_i64: + case Basic_u64: + case Basic_i128: + case Basic_u128: + + case Basic_i16le: + case Basic_u16le: + case Basic_i32le: + case Basic_u32le: + case Basic_i64le: + case Basic_u64le: + case Basic_i128le: + case Basic_u128le: + case Basic_i16be: + case Basic_u16be: + case Basic_i32be: + case Basic_u32be: + case Basic_i64be: + case Basic_u64be: + case Basic_i128be: + case Basic_u128be: + + case Basic_int: + case Basic_uint: + case Basic_uintptr: { + tag_type = t_type_info_integer; + + bool is_signed = (t->Basic.flags & BasicFlag_Unsigned) == 0; + // NOTE(bill): This is matches the runtime layout + u8 endianness_value = 0; + if (t->Basic.flags & BasicFlag_EndianLittle) { + endianness_value = 1; + } else if (t->Basic.flags & BasicFlag_EndianBig) { + endianness_value = 2; + } + u8 *signed_ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+0, 1); + u8 *endianness_ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+1, 1); + *signed_ptr = is_signed; + *endianness_ptr = endianness_value; + break; + } + + case Basic_rune: + tag_type = t_type_info_rune; + break; + + case Basic_f16: + case Basic_f32: + case Basic_f64: + case Basic_f16le: + case Basic_f32le: + case Basic_f64le: + case Basic_f16be: + case Basic_f32be: + case Basic_f64be: + { + tag_type = t_type_info_float; + + // // NOTE(bill): This is matches the runtime layout + u8 endianness_value = 0; + if (t->Basic.flags & BasicFlag_EndianLittle) { + endianness_value = 1; + } else if (t->Basic.flags & BasicFlag_EndianBig) { + endianness_value = 2; + } + + u8 *ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+0, 1); + *ptr = endianness_value; + } + break; + + case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + tag_type = t_type_info_complex; + break; - // LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)}; - // LLVMValueRef data = LLVMConstInBoundsGEP2(cg_type(m, cg_global_type_info_data_entity->type), cg_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)); - // LLVMValueRef len = LLVMConstInt(cg_type(m, t_int), type->Array.count, true); - // Type *t = type_deref(global_type_table.type); - // GB_ASSERT(is_type_slice(t)); - // LLVMValueRef slice = llvm_const_slice_internal(m, data, len); + case Basic_quaternion64: + case Basic_quaternion128: + case Basic_quaternion256: + tag_type = t_type_info_quaternion; + break; - // LLVMSetInitializer(global_type_table.value, slice); - // } + case Basic_rawptr: + tag_type = t_type_info_pointer; + break; + case Basic_string: + tag_type = t_type_info_string; + break; + + case Basic_cstring: + { + tag_type = t_type_info_string; + bool *b = cast(bool *)tb_global_add_region(m->mod, global, offset+0, 1); + *b = true; + } + break; + + case Basic_any: + tag_type = t_type_info_any; + break; + + case Basic_typeid: + tag_type = t_type_info_typeid; + break; + } + break; + } + + if (tag_type != nullptr) { + i64 union_index = union_variant_index(type_info_union, tag_type); + GB_ASSERT(union_index != 0); + void *tag_ptr = tb_global_add_region(m->mod, global, offset+union_tag_offset, union_tag_type_size); + cg_write_int_at_ptr(tag_ptr, union_index, ti_union_tag_type); + } + + } } \ No newline at end of file -- cgit v1.2.3 From b934e4b564e58c62b8c6848a71fe99b02c588a94 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 00:33:43 +0100 Subject: Implement basic runtime type information This allows for `runtime.println_any` to work! --- src/tilde.cpp | 2 +- src/tilde/tb.lib | Bin 4164088 -> 4164640 bytes src/tilde_builtin.cpp | 3 +- src/tilde_const.cpp | 81 ++++++++++------- src/tilde_expr.cpp | 229 +++++++++++++++++++++++++++++++++++++++++++++--- src/tilde_proc.cpp | 5 +- src/tilde_stmt.cpp | 43 ++++----- src/tilde_type_info.cpp | 167 +++++++++++++++++++++++++++++++++++ 8 files changed, 459 insertions(+), 71 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 82d30215e..729b8fa1e 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -260,7 +260,7 @@ gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_ } } if (err_on_not_found) { - GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index); + GB_PANIC("NOT FOUND lb_type_info_index '%s' @ index %td", type_to_string(type), index); } return -1; } diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 7ec145bda..78e661bf8 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index e30ff1cb0..edf436424 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -267,8 +267,7 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr pos = e->token.pos; } - GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); - // return cg_emit_source_code_location_as_global(p, procedure, pos); + return cg_emit_source_code_location_as_global(p, procedure, pos); } break; case BuiltinProc_len: { diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 60f8e636b..30038cfdf 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -31,7 +31,7 @@ gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { if (is_type_internally_pointer_like(type)) { return cg_value(tb_inst_uint(p->func, dt, 0), type); - } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type)) { + } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type) || is_type_typeid(type)) { return cg_value(tb_inst_uint(p->func, dt, 0), type); } else if (is_type_float(type)) { switch (size) { @@ -51,10 +51,49 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return cg_const_nil(p->module, p, type); } +gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Type *type, TB_Global *global, i64 offset); +gb_internal void cg_write_int_at_ptr(void *dst, i64 i, Type *original_type); + +gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { + // Source_Code_Location :: struct { + // file_path: string, + // line, column: i32, + // procedure: string, + // } + + i64 file_path_offset = type_offset_of(t_source_code_location, 0); + i64 line_offset = type_offset_of(t_source_code_location, 1); + i64 column_offset = type_offset_of(t_source_code_location, 2); + i64 procedure_offset = type_offset_of(t_source_code_location, 3); + + String file_path = get_file_path_string(pos.file_id); + if (file_path.len != 0) { + cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); + } + + void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); + void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); + cg_write_int_at_ptr(line_ptr, pos.line, t_i32); + cg_write_int_at_ptr(column_ptr, pos.column, t_i32); + + if (proc_name.len != 0) { + cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); + } +} + gb_internal cgValue cg_emit_source_code_location_as_global(cgProcedure *p, String const &proc_name, TokenPos pos) { - // TODO(bill): cg_emit_source_code_location_as_global - return cg_const_nil(p, t_source_code_location); + cgModule *m = p->module; + char name[32] = {}; + gb_snprintf(name, 31, "scl$%u", 1+m->const_nil_guid.fetch_add(1)); + + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, t_source_code_location), TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(t_source_code_location), type_align_of(t_source_code_location), 6); + + cg_global_source_code_location_const(m, proc_name, pos, global, 0); + + TB_Node *ptr = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + return cg_lvalue_addr(ptr, t_source_code_location); } @@ -143,33 +182,6 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } -gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { - // Source_Code_Location :: struct { - // file_path: string, - // line, column: i32, - // procedure: string, - // } - - i64 file_path_offset = type_offset_of(t_source_code_location, 0); - i64 line_offset = type_offset_of(t_source_code_location, 1); - i64 column_offset = type_offset_of(t_source_code_location, 2); - i64 procedure_offset = type_offset_of(t_source_code_location, 3); - - String file_path = get_file_path_string(pos.file_id); - if (file_path.len != 0) { - cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); - } - - void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); - void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); - cg_write_int_at_ptr(line_ptr, pos.line, t_i32); - cg_write_int_at_ptr(column_ptr, pos.column, t_i32); - - if (proc_name.len != 0) { - cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); - } -} - gb_internal bool cg_elem_type_can_be_constant(Type *t) { t = base_type(t); if (t == t_invalid) { @@ -1003,3 +1015,12 @@ gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { gb_internal cgValue cg_const_bool(cgProcedure *p, Type *type, bool v) { return cg_value(tb_inst_bool(p->func, v), type); } + +gb_internal cgValue cg_const_string(cgProcedure *p, Type *type, String const &str) { + return cg_const_value(p, type, exact_value_string(str)); +} + +gb_internal cgValue cg_const_union_tag(cgProcedure *p, Type *u, Type *v) { + return cg_const_value(p, union_tag_type(u), exact_value_i64(union_variant_index(u, v))); +} + diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 8737e75cd..551ffbfbb 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -267,7 +267,8 @@ gb_internal cgValue cg_emit_byte_swap(cgProcedure *p, cgValue value, Type *end_t GB_ASSERT(value.kind == cgValue_Value); - value.node = tb_inst_bswap(p->func, value.node); + // TODO(bill): bswap + // value.node = tb_inst_bswap(p->func, value.node); return cg_emit_transmute(p, value, end_type); } @@ -913,13 +914,12 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { - GB_PANIC("TODO(bill): cstring_to_string call"); - // TEMPORARY_ALLOCATOR_GUARD(); - // lbValue c = lb_emit_conv(p, value, t_cstring); - // auto args = array_make(temporary_allocator(), 1); - // args[0] = c; - // lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args); - // return lb_emit_conv(p, s, dst); + TEMPORARY_ALLOCATOR_GUARD(); + cgValue c = cg_emit_conv(p, value, t_cstring); + auto args = slice_make(temporary_allocator(), 1); + args[0] = c; + cgValue s = cg_emit_runtime_call(p, "cstring_to_string", args); + return cg_emit_conv(p, s, dst); } // float -> float @@ -1115,7 +1115,29 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { } if (is_type_any(dst)) { - GB_PANIC("TODO(bill): ? -> any"); + if (is_type_untyped_nil(src) || + is_type_untyped_uninit(src)) { + return cg_const_nil(p, t); + } + + cgAddr result = cg_add_local(p, t, nullptr, false); + + Type *st = default_type(src_type); + + cgValue data = cg_address_from_load_or_generate_local(p, value); + GB_ASSERT(is_type_pointer(data.type)); + GB_ASSERT(is_type_typed(st)); + + data = cg_emit_conv(p, data, t_rawptr); + + cgValue id = cg_typeid(p, st); + cgValue data_ptr = cg_emit_struct_ep(p, result.addr, 0); + cgValue id_ptr = cg_emit_struct_ep(p, result.addr, 1); + + cg_emit_store(p, data_ptr, data); + cg_emit_store(p, id_ptr, id); + + return cg_addr_load(p, result); } i64 src_sz = type_size_of(src); @@ -2868,6 +2890,190 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { return cg_build_addr_ptr(p, ue->expr); } +gb_internal cgValue cg_emit_cast_union(cgProcedure *p, cgValue value, Type *type, TokenPos pos) { + Type *src_type = value.type; + bool is_ptr = is_type_pointer(src_type); + + bool is_tuple = true; + Type *tuple = type; + if (type->kind != Type_Tuple) { + is_tuple = false; + tuple = make_optional_ok_type(type); + } + + + if (is_ptr) { + value = cg_emit_load(p, value); + } + Type *src = base_type(type_deref(src_type)); + GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type)); + Type *dst = tuple->Tuple.variables[0]->type; + + cgValue value_ = cg_address_from_load_or_generate_local(p, value); + + if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) { + // just do a bit cast of the data at the front + cgValue ptr = cg_emit_conv(p, value_, alloc_type_pointer(type)); + return cg_emit_load(p, ptr); + } + + + cgValue tag = {}; + cgValue dst_tag = {}; + cgValue cond = {}; + cgValue data = {}; + + cgValue gep0 = cg_add_local(p, tuple->Tuple.variables[0]->type, nullptr, true).addr; + cgValue gep1 = cg_add_local(p, tuple->Tuple.variables[1]->type, nullptr, true).addr; + + if (is_type_union_maybe_pointer(src)) { + data = cg_emit_load(p, cg_emit_conv(p, value_, gep0.type)); + } else { + tag = cg_emit_load(p, cg_emit_union_tag_ptr(p, value_)); + dst_tag = cg_const_union_tag(p, src, dst); + } + + TB_Node *ok_block = cg_control_region(p, "union_cast_ok"); + TB_Node *end_block = cg_control_region(p, "union_cast_end"); + + if (data.node != nullptr) { + GB_ASSERT(is_type_union_maybe_pointer(src)); + cond = cg_emit_comp_against_nil(p, Token_NotEq, data); + } else { + cond = cg_emit_comp(p, Token_CmpEq, tag, dst_tag); + } + + cg_emit_if(p, cond, ok_block, end_block); + tb_inst_set_control(p->func, ok_block); + + if (data.node == nullptr) { + data = cg_emit_load(p, cg_emit_conv(p, value_, gep0.type)); + } + cg_emit_store(p, gep0, data); + cg_emit_store(p, gep1, cg_const_bool(p, t_bool, true)); + + cg_emit_goto(p, end_block); + tb_inst_set_control(p->func, end_block); + + if (!is_tuple) { + GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0); + // NOTE(bill): Panic on invalid conversion + Type *dst_type = tuple->Tuple.variables[0]->type; + + isize arg_count = 7; + if (build_context.no_rtti) { + arg_count = 4; + } + + cgValue ok = cg_emit_load(p, gep1); + auto args = slice_make(permanent_allocator(), arg_count); + args[0] = ok; + + args[1] = cg_const_string(p, t_string, get_file_path_string(pos.file_id)); + args[2] = cg_const_int(p, t_i32, pos.line); + args[3] = cg_const_int(p, t_i32, pos.column); + + if (!build_context.no_rtti) { + args[4] = cg_typeid(p, src_type); + args[5] = cg_typeid(p, dst_type); + args[6] = cg_emit_conv(p, value_, t_rawptr); + } + cg_emit_runtime_call(p, "type_assertion_check2", args); + + return cg_emit_load(p, gep0); + } + + return cg_value_multi2(cg_emit_load(p, gep0), cg_emit_load(p, gep1), tuple); +} + +gb_internal cgValue cg_emit_cast_any(cgProcedure *p, cgValue value, Type *type, TokenPos pos) { + Type *src_type = value.type; + + if (is_type_pointer(src_type)) { + value = cg_emit_load(p, value); + } + + bool is_tuple = true; + Type *tuple = type; + if (type->kind != Type_Tuple) { + is_tuple = false; + tuple = make_optional_ok_type(type); + } + Type *dst_type = tuple->Tuple.variables[0]->type; + + if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) { + // just do a bit cast of the data at the front + cgValue ptr = cg_emit_struct_ev(p, value, 0); + ptr = cg_emit_conv(p, ptr, alloc_type_pointer(type)); + return cg_emit_load(p, ptr); + } + + cgValue dst_typeid = cg_typeid(p, dst_type); + cgValue any_typeid = cg_emit_struct_ev(p, value, 1); + + + TB_Node *ok_block = cg_control_region(p, "any_cast_ok"); + TB_Node *end_block = cg_control_region(p, "any_cast_end"); + cgValue cond = cg_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid); + cg_emit_if(p, cond, ok_block, end_block); + tb_inst_set_control(p->func, ok_block); + + cgValue gep0 = cg_add_local(p, tuple->Tuple.variables[0]->type, nullptr, true).addr; + cgValue gep1 = cg_add_local(p, tuple->Tuple.variables[1]->type, nullptr, true).addr; + + cgValue any_data = cg_emit_struct_ev(p, value, 0); + cgValue ptr = cg_emit_conv(p, any_data, alloc_type_pointer(dst_type)); + cg_emit_store(p, gep0, cg_emit_load(p, ptr)); + cg_emit_store(p, gep1, cg_const_bool(p, t_bool, true)); + + cg_emit_goto(p, end_block); + tb_inst_set_control(p->func, end_block); + + if (!is_tuple) { + // NOTE(bill): Panic on invalid conversion + cgValue ok = cg_emit_load(p, gep1); + + isize arg_count = 7; + if (build_context.no_rtti) { + arg_count = 4; + } + auto args = slice_make(permanent_allocator(), arg_count); + args[0] = ok; + + args[1] = cg_const_string(p, t_string, get_file_path_string(pos.file_id)); + args[2] = cg_const_int(p, t_i32, pos.line); + args[3] = cg_const_int(p, t_i32, pos.column); + + if (!build_context.no_rtti) { + args[4] = any_typeid; + args[5] = dst_typeid; + args[6] = cg_emit_struct_ev(p, value, 0); + } + cg_emit_runtime_call(p, "type_assertion_check2", args); + + return cg_emit_load(p, gep0); + } + + return cg_value_multi2(cg_emit_load(p, gep0), cg_emit_load(p, gep1), tuple); +} + + +gb_internal cgValue cg_build_type_assertion(cgProcedure *p, Ast *expr, Type *type) { + ast_node(ta, TypeAssertion, expr); + + TokenPos pos = ast_token(expr).pos; + cgValue e = cg_build_expr(p, ta->expr); + Type *t = type_deref(e.type); + + if (is_type_union(t)) { + return cg_emit_cast_union(p, e, type, pos); + } else if (is_type_any(t)) { + return cg_emit_cast_any(p, e, type, pos); + } + GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type)); + return {}; +} + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { expr = unparen_expr(expr); @@ -3079,8 +3285,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(oe, OrElseExpr, expr); return cg_build_or_else(p, oe->x, oe->y, tv.type); case_end; + + case_ast_node(ta, TypeAssertion, expr); + return cg_build_type_assertion(p, expr, tv.type); + case_end; } - GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index a805b2985..398148965 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -352,7 +352,7 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { bool emit_asm = false; if ( - // string_starts_with(p->name, str_lit("runtime@_os_write")) || + // string_starts_with(p->name, str_lit("bug@main")) || false ) { emit_asm = true; @@ -866,8 +866,7 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { cgValue base_elem = cg_emit_array_epi(p, base_array.addr, 0); cgValue len = cg_const_int(p, t_int, slice_len); - GB_PANIC("TODO(bill): cg_fill_slice"); - // cg_fill_slice(p, slice, base_elem, len); + cg_fill_slice(p, slice, base_elem, len); variadic_args = cg_addr_load(p, slice); } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 8b577dfeb..a663a401d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -409,11 +409,9 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { switch (t->kind) { case Type_Struct: - { - type_set_offsets(t); - result_type = t->Struct.fields[index]->type; - offset = t->Struct.offsets[index]; - } + type_set_offsets(t); + result_type = t->Struct.fields[index]->type; + offset = t->Struct.offsets[index]; break; case Type_Union: GB_ASSERT(index == -1); @@ -421,7 +419,10 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { break; // return cg_emit_union_tag_ptr(p, s); case Type_Tuple: - GB_PANIC("TODO(bill): cg_emit_tuple_ep"); + type_set_offsets(t); + result_type = t->Tuple.variables[index]->type; + offset = t->Tuple.offsets[index]; + GB_PANIC("TODO(bill): cg_emit_tuple_ep %d", s.kind); break; // return cg_emit_tuple_ep(p, s, index); case Type_Slice: @@ -1799,8 +1800,11 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { expr = unparen_expr(expr); GB_ASSERT(!is_ast_range(expr)); if (expr->tav.mode == Addressing_Type) { - GB_PANIC("TODO(bill): cg_typeid as i64"); - // key = cg_typeid(p, expr->tav.value.value_typeid); + Type *type = expr->tav.value.value_typeid; + if (type == nullptr || type == t_invalid) { + type = expr->tav.type; + } + key = cg_typeid_as_u64(p->module, type); } else { auto tv = type_and_value_of_expr(expr); GB_ASSERT(tv.mode == Addressing_Constant); @@ -1912,21 +1916,16 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { cg_scope_close(p, cgDeferExit_Default, done); } -gb_internal void cg_type_case_body(cgProcedure *p, Ast *label, Ast *clause, TB_Node *body_region, TB_Node *done_region) { - // ast_node(cc, CaseClause, clause); - - // cg_push_target_list(p, label, done, nullptr, nullptr); - // cg_build_stmt_list(p, cc->stmts); - // cg_scope_close(p, cgDeferExit_Default, body_region); - // cg_pop_target_list(p); - - // cg_emit_goto(p, done_region); -} - gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { ast_node(ss, TypeSwitchStmt, node); + TB_Node *done_region = cg_control_region(p, "typeswitch_done"); + TB_Node *else_region = done_region; + TB_Node *default_region = nullptr; + isize num_cases = 0; + cg_scope_open(p, ss->scope); + defer (cg_scope_close(p, cgDeferExit_Default, done_region)); ast_node(as, AssignStmt, ss->tag); GB_ASSERT(as->lhs.count == 1); @@ -1969,11 +1968,6 @@ gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { ast_node(body, BlockStmt, ss->body); - TB_Node *done_region = cg_control_region(p, "typeswitch_done"); - TB_Node *else_region = done_region; - TB_Node *default_region = nullptr; - isize num_cases = 0; - for (Ast *clause : body->stmts) { ast_node(cc, CaseClause, clause); num_cases += cc->list.count; @@ -2158,7 +2152,6 @@ gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { cg_emit_goto(p, done_region); tb_inst_set_control(p->func, done_region); - cg_scope_close(p, cgDeferExit_Default, done_region); } diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index 1e86f6644..adad2cace 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -340,6 +340,173 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { break; } break; + + case Type_Pointer: + tag_type = t_type_info_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->Pointer.elem, global, offset+0); + break; + case Type_MultiPointer: + tag_type = t_type_info_multi_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->MultiPointer.elem, global, offset+0); + break; + case Type_SoaPointer: + tag_type = t_type_info_soa_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->SoaPointer.elem, global, offset+0); + break; + + case Type_Array: + { + tag_type = t_type_info_array; + + cg_global_const_type_info_ptr(m, type_table_array, t->Array.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + void *count_ptr = tb_global_add_region(m->mod, global, offset+2*build_context.int_size, build_context.int_size); + + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->Array.elem), t_int); + cg_write_int_at_ptr(count_ptr, t->Array.count, t_int); + } + break; + + case Type_EnumeratedArray: + { + tag_type = t_type_info_enumerated_array; + + i64 elem_offset = type_offset_of(tag_type, 0); + i64 index_offset = type_offset_of(tag_type, 1); + i64 elem_size_offset = type_offset_of(tag_type, 2); + i64 count_offset = type_offset_of(tag_type, 3); + i64 min_value_offset = type_offset_of(tag_type, 4); + i64 max_value_offset = type_offset_of(tag_type, 5); + i64 is_sparse_offset = type_offset_of(tag_type, 6); + + cg_global_const_type_info_ptr(m, type_table_array, t->EnumeratedArray.elem, global, offset+elem_offset); + cg_global_const_type_info_ptr(m, type_table_array, t->EnumeratedArray.index, global, offset+index_offset); + + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+elem_size_offset, build_context.int_size); + void *count_ptr = tb_global_add_region(m->mod, global, offset+count_offset, build_context.int_size); + + void *min_value_ptr = tb_global_add_region(m->mod, global, offset+min_value_offset, type_size_of(t_type_info_enum_value)); + void *max_value_ptr = tb_global_add_region(m->mod, global, offset+max_value_offset, type_size_of(t_type_info_enum_value)); + void *is_sparse_ptr = tb_global_add_region(m->mod, global, offset+is_sparse_offset, 1); + + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->EnumeratedArray.elem), t_int); + cg_write_int_at_ptr(count_ptr, t->EnumeratedArray.count, t_int); + + cg_write_int_at_ptr(min_value_ptr, exact_value_to_i64(*t->EnumeratedArray.min_value), t_type_info_enum_value); + cg_write_int_at_ptr(max_value_ptr, exact_value_to_i64(*t->EnumeratedArray.max_value), t_type_info_enum_value); + *(bool *)is_sparse_ptr = t->EnumeratedArray.is_sparse; + } + break; + + case Type_DynamicArray: + { + tag_type = t_type_info_dynamic_array; + + cg_global_const_type_info_ptr(m, type_table_array, t->DynamicArray.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->DynamicArray.elem), t_int); + } + break; + case Type_Slice: + { + tag_type = t_type_info_slice; + + cg_global_const_type_info_ptr(m, type_table_array, t->Slice.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->Slice.elem), t_int); + } + break; + + case Type_Proc: + { + tag_type = t_type_info_procedure; + + i64 params_offset = type_offset_of(tag_type, 0); + i64 results_offset = type_offset_of(tag_type, 1); + i64 variadic_offset = type_offset_of(tag_type, 2); + i64 convention_offset = type_offset_of(tag_type, 3); + + if (t->Proc.params) { + cg_global_const_type_info_ptr(m, type_table_array, t->Proc.params, global, offset+params_offset); + } + if (t->Proc.results) { + cg_global_const_type_info_ptr(m, type_table_array, t->Proc.results, global, offset+results_offset); + } + + bool *variadic_ptr = cast(bool *)tb_global_add_region(m->mod, global, offset+variadic_offset, 1); + u8 * convention_ptr = cast(u8 *) tb_global_add_region(m->mod, global, offset+convention_offset, 1); + + *variadic_ptr = t->Proc.variadic; + *convention_ptr = cast(u8)t->Proc.calling_convention; + } + break; + + case Type_Tuple: + { + tag_type = t_type_info_parameters; + + // TODO(bill): Type_Info_Parameters + } + break; + + case Type_Enum: + { + tag_type = t_type_info_enum; + + // TODO(bill): Type_Info_Enum + } + break; + case Type_Struct: + { + tag_type = t_type_info_struct; + + // TODO(bill): Type_Info_Struct + } + break; + case Type_Union: + { + tag_type = t_type_info_union; + + // TODO(bill): Type_Info_Union + } + break; + case Type_Map: + { + tag_type = t_type_info_map; + + // TODO(bill): Type_Info_Map + } + break; + case Type_BitSet: + { + tag_type = t_type_info_bit_set; + + // TODO(bill): Type_Info_Bit_Set + } + break; + case Type_SimdVector: + { + tag_type = t_type_info_simd_vector; + + // TODO(bill): Type_Info_Simd_Vector + } + break; + + case Type_RelativePointer: + { + tag_type = t_type_info_relative_pointer; + } + break; + case Type_RelativeSlice: + { + tag_type = t_type_info_relative_slice; + } + break; + case Type_Matrix: + { + tag_type = t_type_info_matrix; + } + break; } if (tag_type != nullptr) { -- cgit v1.2.3 From e4006eb58343d35e7e26177a1adf41b0d9665b10 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 01:11:57 +0100 Subject: Update tilde --- src/tilde/tb.lib | Bin 4164640 -> 4162070 bytes src/tilde_proc.cpp | 54 +++++++++++++++-------------------------------------- src/tilde_stmt.cpp | 34 +++++++++++++++++++++++++++------ 3 files changed, 43 insertions(+), 45 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 78e661bf8..adf355d07 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 398148965..08cbcc631 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -260,44 +260,6 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (e) { map_set(&p->variable_map, e, addr); } - - // if (arg_type->kind == lbArg_Ignore) { - // continue; - // } else if (arg_type->kind == lbArg_Direct) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // LLVMTypeRef param_type = lb_type(p->module, e->type); - // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); - // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); - - // lbValue param = {}; - // param.value = value; - // param.type = e->type; - - // map_set(&p->direct_parameters, e, param); - - // lbValue ptr = lb_address_from_load_or_generate_local(p, param); - // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); - // lb_add_entity(p->module, e, ptr); - - // lbBlock *block = p->decl_block; - // if (original_value != value) { - // block = p->curr_block; - // } - // LLVMValueRef debug_storage_value = value; - // if (original_value != value && LLVMIsALoadInst(value)) { - // debug_storage_value = LLVMGetOperand(value, 0); - // } - // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); - // } - // } else if (arg_type->kind == lbArg_Indirect) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // lbValue ptr = {}; - // ptr.value = LLVMGetParam(p->value, param_offset+param_index); - // ptr.type = alloc_type_pointer(e->type); - // lb_add_entity(p->module, e, ptr); - // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); - // } - // } } if (is_odin_like_cc) { @@ -351,6 +313,20 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { bool emit_asm = false; + if (false && + string_starts_with(p->name, str_lit("bug@main"))) { + TB_Arena *arena = cg_arena(); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + + tb_funcopt_peephole(opt); + tb_funcopt_mem2reg(opt); + tb_funcopt_peephole(opt); + + emit_asm = true; + } + + if ( // string_starts_with(p->name, str_lit("bug@main")) || false @@ -398,7 +374,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { if ( - // string_starts_with(p->name, str_lit("bug@main")) || + string_starts_with(p->name, str_lit("bug@main")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index a663a401d..794061335 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -2246,20 +2246,42 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { TEMPORARY_ALLOCATOR_GUARD(); + auto inits = array_make(temporary_allocator(), 0, vd->values.count != 0 ? vd->names.count : 0); + for (Ast *rhs : vd->values) { + cgValue init = cg_build_expr(p, rhs); + cg_append_tuple_values(p, &inits, init); + } + + auto lvals = slice_make(temporary_allocator(), vd->names.count); for_array(i, vd->names) { Ast *name = vd->names[i]; if (!is_blank_ident(name)) { Entity *e = entity_of_node(name); - lvals[i] = cg_add_local(p, e->type, e, true); + bool zero_init = vd->values.count == 0; + if (vd->names.count == vd->values.count) { + Ast *expr = unparen_expr(vd->values[i]); + if (expr->kind == Ast_CompoundLit && + inits[i].kind == cgValue_Addr) { + TB_Node *ptr = inits[i].node; + + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + } + + cgAddr addr = cg_addr(inits[i]); + map_set(&p->variable_map, e, addr); + continue; + } + } + + lvals[i] = cg_add_local(p, e->type, e, zero_init); } } - auto inits = array_make(temporary_allocator(), 0, vd->values.count != 0 ? lvals.count : 0); - for (Ast *rhs : vd->values) { - cgValue init = cg_build_expr(p, rhs); - cg_append_tuple_values(p, &inits, init); - } GB_ASSERT(vd->values.count == 0 || lvals.count == inits.count); for_array(i, inits) { -- cgit v1.2.3 From baea6a1da88444db322f83b8300b5d64d117cfd1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 13:31:22 +0100 Subject: Generate anonymous procedure literals --- src/tilde.cpp | 24 +++++++++++++++------- src/tilde.hpp | 7 +++++++ src/tilde_const.cpp | 23 +++++++++++++-------- src/tilde_expr.cpp | 16 ++++++++++++++- src/tilde_proc.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 112 insertions(+), 17 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index a7f37dc6f..9550374e8 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -238,14 +238,21 @@ gb_internal void cg_add_procedure_value(cgModule *m, cgProcedure *p) { } gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { - if (e) { - rw_mutex_lock(&m->values_mutex); - defer (rw_mutex_unlock(&m->values_mutex)); - TB_Symbol **found = map_get(&m->symbols, e); - if (found) { - return *found; - } + GB_ASSERT(e != nullptr); + + rw_mutex_lock(&m->values_mutex); + defer (rw_mutex_unlock(&m->values_mutex)); + TB_Symbol **found = map_get(&m->symbols, e); + if (found) { + return *found; + } + + String link_name = cg_get_entity_name(m, e); + cgProcedure **proc_found = string_map_get(&m->procedures, link_name); + if (proc_found) { + return (*proc_found)->symbol; } + GB_PANIC("could not find entity's symbol %.*s", LIT(e->token.string)); return nullptr; } @@ -397,6 +404,8 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->proc_debug_type_map); map_init(&m->proc_proto_map); + map_init(&m->anonymous_proc_lits_map); + array_init(&m->single_threaded_procedure_queue, heap_allocator()); @@ -417,6 +426,7 @@ gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); map_destroy(&m->proc_proto_map); + map_destroy(&m->anonymous_proc_lits_map); array_free(&m->single_threaded_procedure_queue); diff --git a/src/tilde.hpp b/src/tilde.hpp index 857247305..087655d83 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -227,6 +227,10 @@ struct cgModule { RecursiveMutex proc_proto_mutex; PtrMap proc_proto_map; + BlockingMutex anonymous_proc_lits_mutex; + PtrMap anonymous_proc_lits_map; + + // NOTE(bill): no need to protect this with a mutex PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) @@ -259,11 +263,14 @@ gb_internal TB_Arena *cg_arena(void); gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); +gb_internal cgProcedure *cg_procedure_generate_anonymous(cgModule *m, Ast *expr, cgProcedure *parent); gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type); gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *type); gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset); +gb_internal String cg_get_entity_name(cgModule *m, Entity *e); + gb_internal cgValue cg_value(TB_Global * g, Type *type); gb_internal cgValue cg_value(TB_External *e, Type *type); gb_internal cgValue cg_value(TB_Function *f, Type *type); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 30038cfdf..05b57a97a 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -911,17 +911,24 @@ gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const case ExactValue_Procedure: { Ast *expr = unparen_expr(value.value_procedure); + if (expr->kind == Ast_ProcLit) { + cgProcedure *anon = cg_procedure_generate_anonymous(p->module, expr, p); + TB_Node *ptr = tb_inst_get_symbol_address(p->func, anon->symbol); + GB_ASSERT(are_types_identical(type, anon->type)); + return cg_value(ptr, type); + } + Entity *e = entity_of_node(expr); if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(p->module, e); - GB_ASSERT_MSG(are_types_identical(type, found.type), - "%.*s %s == %s", - LIT(p->name), - type_to_string(type), type_to_string(found.type)); - GB_ASSERT(found.kind == cgValue_Symbol); - return cg_flatten_value(p, found); + TB_Symbol *found = cg_find_symbol_from_entity(p->module, e); + GB_ASSERT_MSG(found != nullptr, "could not find '%.*s'", LIT(e->token.string)); + TB_Node *ptr = tb_inst_get_symbol_address(p->func, found); + GB_ASSERT(type != nullptr); + GB_ASSERT(are_types_identical(type, e->type)); + return cg_value(ptr, type); } - GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); + + GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure %s", expr_to_string(expr)); } break; } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 551ffbfbb..4caf33ccf 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -3090,7 +3090,6 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr); // GB_PANIC("%s\n", type_to_string(tv.type)); // } - // NOTE(bill): Short on constant values return cg_const_value(p, type, tv.value); } else if (tv.mode == Addressing_Type) { @@ -3289,7 +3288,22 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(ta, TypeAssertion, expr); return cg_build_type_assertion(p, expr, tv.type); case_end; + + case_ast_node(pl, ProcLit, expr); + cgProcedure *anon = cg_procedure_generate_anonymous(p->module, expr, p); + GB_ASSERT(anon != nullptr); + GB_ASSERT(anon->symbol != nullptr); + return cg_value(tb_inst_get_symbol_address(p->func, anon->symbol), type); + case_end; + } + TokenPos token_pos = ast_token(expr).pos; + GB_PANIC("Unexpected expression\n" + "\tAst: %.*s @ " + "%s\n", + LIT(ast_strings[expr->kind]), + token_pos_to_string(token_pos)); + return {}; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 08cbcc631..3a0624583 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -161,6 +161,63 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li return p; } +gb_internal cgProcedure *cg_procedure_generate_anonymous(cgModule *m, Ast *expr, cgProcedure *parent) { + expr = unparen_expr(expr); + ast_node(pl, ProcLit, expr); + + mutex_lock(&m->anonymous_proc_lits_mutex); + defer (mutex_unlock(&m->anonymous_proc_lits_mutex)); + + cgProcedure **found = map_get(&m->anonymous_proc_lits_map, expr); + if (found) { + return *found; + } + + TokenPos pos = ast_token(expr).pos; + + // NOTE(bill): Generate a new name + // parent$count + + String prefix_name = str_lit("proc_lit"); + if (parent) { + prefix_name = parent->name; + } + + isize name_len = prefix_name.len + 6 + 11; + char *name_text = gb_alloc_array(permanent_allocator(), char, name_len); + + static std::atomic name_id; + name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), 1+name_id.fetch_add(1)); + String name = make_string((u8 *)name_text, name_len-1); + + Type *type = type_of_expr(expr); + + GB_ASSERT(pl->decl->entity == nullptr); + Token token = {}; + token.pos = ast_token(expr).pos; + token.kind = Token_Ident; + token.string = name; + Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags); + e->file = expr->file(); + + // NOTE(bill): this is to prevent a race condition since these procedure literals can be created anywhere at any time + e->decl_info = pl->decl; + pl->decl->entity = e; + e->flags |= EntityFlag_ProcBodyChecked; + + cgProcedure *p = cg_procedure_create(m, e); + + map_set(&m->anonymous_proc_lits_map, expr, p); + + if (parent != nullptr) { + array_add(&parent->children, p); + } + + cg_add_procedure_to_queue(p); + return p; + +} + gb_internal void cg_procedure_begin(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; @@ -374,7 +431,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { if ( - string_starts_with(p->name, str_lit("bug@main")) || + // string_starts_with(p->name, str_lit("bug@main")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); -- cgit v1.2.3 From c4033c215e01343709a0d7928c277a6425f53524 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 14:37:19 +0100 Subject: Support non-constant global slices --- src/tilde.cpp | 25 ++++++++++++++---------- src/tilde.hpp | 3 +++ src/tilde_const.cpp | 8 +++++++- src/tilde_expr.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++-------- src/tilde_proc.cpp | 7 +++++-- 5 files changed, 77 insertions(+), 21 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 6cd8a42af..64fe70ec4 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -694,22 +694,14 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); cgProcedure *p = cg_procedure_create_dummy(m, str_lit(CG_STARTUP_RUNTIME_PROC_NAME), proc_type); p->is_startup = true; - - cg_procedure_begin(p); - cg_global_variables_initialize(p, &global_variables); - - tb_inst_ret(p->func, 0, nullptr); - cg_procedure_end(p); + cg_startup_runtime_proc = p; } if (true) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); cgProcedure *p = cg_procedure_create_dummy(m, str_lit(CG_CLEANUP_RUNTIME_PROC_NAME), proc_type); p->is_startup = true; - - cg_procedure_begin(p); - tb_inst_ret(p->func, 0, nullptr); - cg_procedure_end(p); + cg_cleanup_runtime_proc = p; } auto *min_dep_set = &info->minimum_dependency_set; @@ -741,6 +733,19 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { array_add(&procedures_to_generate, p); } } + { + cgProcedure *p = cg_startup_runtime_proc; + cg_procedure_begin(p); + cg_global_variables_initialize(p, &global_variables); + tb_inst_ret(p->func, 0, nullptr); + cg_procedure_end(p); + } + { + cgProcedure *p = cg_cleanup_runtime_proc; + cg_procedure_begin(p); + tb_inst_ret(p->func, 0, nullptr); + cg_procedure_end(p); + } for (cgProcedure *p : procedures_to_generate) { cg_add_procedure_to_queue(p); diff --git a/src/tilde.hpp b/src/tilde.hpp index 087655d83..72d5048bb 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -257,6 +257,9 @@ gb_global GlobalTypeInfoData cg_global_type_info_member_usings = {}; gb_global GlobalTypeInfoData cg_global_type_info_member_tags = {}; gb_global GlobalTypeInfoData cg_global_type_info_member_enum_values = {}; +gb_global cgProcedure *cg_startup_runtime_proc = nullptr; +gb_global cgProcedure *cg_cleanup_runtime_proc = nullptr; + gb_internal TB_Arena *cg_arena(void); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index d37edb89a..5b34480f4 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -555,11 +555,11 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value return true; } - GB_ASSERT(!is_type_array_like(bt)); switch (value.kind) { case ExactValue_Bool: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); *res = !!value.value_bool; } @@ -567,6 +567,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Integer: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *res = tb_global_add_region(m->mod, global, offset, size); cg_write_big_int_at_ptr(res, &value.value_integer, type); } @@ -574,6 +575,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Float: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); f64 f = exact_value_to_f64(value); void *res = tb_global_add_region(m->mod, global, offset, size); switch (size) { @@ -586,6 +588,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Pointer: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *res = tb_global_add_region(m->mod, global, offset, size); *(u64 *)res = exact_value_to_u64(value); } @@ -603,6 +606,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Typeid: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *dst = tb_global_add_region(m->mod, global, offset, size); u64 id = cg_typeid_as_u64(m, value.value_typeid); cg_write_uint_at_ptr(dst, id, t_typeid); @@ -621,6 +625,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value break; case ExactValue_Complex: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); Complex128 c = {}; if (value.value_complex) { c = *value.value_complex; @@ -644,6 +649,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value break; case ExactValue_Quaternion: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); // @QuaternionLayout Quaternion256 q = {}; if (value.value_quaternion) { diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 4caf33ccf..96f17bfcf 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -86,6 +86,39 @@ gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e) { return {}; } +gb_internal cgValue cg_get_using_variable(cgProcedure *p, Entity *e) { + GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using); + String name = e->token.string; + Entity *parent = e->using_parent; + Selection sel = lookup_field(parent->type, name, false); + GB_ASSERT(sel.entity != nullptr); + cgValue *pv = map_get(&p->module->values, parent); + + cgValue v = {}; + + if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) { + // NOTE(bill): using SOA value (probably from for-in statement) + GB_PANIC("TODO(bill): cg_get_soa_variable_addr"); + // cgAddr parent_addr = cg_get_soa_variable_addr(p, parent); + // v = cg_addr_get_ptr(p, parent_addr); + } else if (pv != nullptr) { + v = *pv; + } else { + GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s %.*s", LIT(e->token.string), LIT(name)); + v = cg_build_addr_ptr(p, e->using_expr); + } + GB_ASSERT(v.node != nullptr); + GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type)); + cgValue ptr = cg_emit_deep_field_gep(p, v, sel); + // if (parent->scope) { + // if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) { + // cg_add_debug_local_variable(p, ptr.value, e->type, e->token); + // } + // } else { + // cg_add_debug_local_variable(p, ptr.value, e->type, e->token); + // } + return ptr; +} gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *expr) { GB_ASSERT(e != nullptr); if (e->kind == Entity_Constant) { @@ -111,9 +144,8 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp if (found) { v = *found; } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { - GB_PANIC("TODO(bill): cg_get_using_variable"); // NOTE(bill): Calculate the using variable every time - // v = cg_get_using_variable(p, e); + v = cg_get_using_variable(p, e); } else if (e->flags & EntityFlag_SoaPtrField) { GB_PANIC("TODO(bill): cg_get_soa_variable_addr"); // return cg_get_soa_variable_addr(p, e); @@ -434,11 +466,10 @@ gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left } GB_ASSERT(runtime_procedure != nullptr); - GB_PANIC("TODO(bill): cg_emit_runtime_call"); - // auto args = array_make(permanent_allocator(), 2); - // args[0] = left; - // args[1] = right; - // return cg_emit_runtime_call(p, runtime_procedure, args); + auto args = slice_make(permanent_allocator(), 2); + args[0] = left; + args[1] = right; + return cg_emit_runtime_call(p, runtime_procedure, args); } if (is_type_complex(a)) { @@ -2514,7 +2545,15 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { TB_CharUnits backing_size = cast(TB_CharUnits)(type_size_of(bt->Slice.elem) * count); TB_CharUnits align = cast(TB_CharUnits)type_align_of(bt->Slice.elem); - TB_Node *backing = tb_inst_local(p->func, backing_size, align); + + TB_Node *backing = nullptr; + if (p->is_startup) { + TB_Global *global = tb_global_create(p->module->mod, 0, "", nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(p->module->mod, tb_module_get_data(p->module->mod), global, backing_size, align, 0); + backing = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + } else { + backing = tb_inst_local(p->func, backing_size, align); + } cgValue data = cg_value(backing, alloc_type_multi_pointer(bt->Slice.elem)); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 3a0624583..80948adea 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -408,8 +408,11 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } if (tb_inst_get_control(p->func)) { - GB_ASSERT(p->type->Proc.result_count == 0); - tb_inst_ret(p->func, 0, nullptr); + if (p->type->Proc.result_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + } else { + tb_inst_unreachable(p->func); + } } if (p->module->do_threading) { -- cgit v1.2.3 From 0f217c715ecd9fc265b1c6a3d579b99ecf849139 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 15:15:35 +0100 Subject: Fix dependency issue; Allow polymorphic procedures in tilde --- src/check_expr.cpp | 3 +- src/tilde.hpp | 3 +- src/tilde_debug.cpp | 11 ++- src/tilde_expr.cpp | 278 ++++++++++++++++++++++++++-------------------------- src/tilde_proc.cpp | 55 +++++++---- src/tilde_stmt.cpp | 28 ++++++ src/types.cpp | 30 ++++-- 7 files changed, 233 insertions(+), 175 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 98154f33d..d5e5f7952 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -5985,8 +5985,8 @@ gb_internal bool check_call_arguments_single(CheckerContext *c, Ast *call, Opera } Entity *entity_to_use = data->gen_entity != nullptr ? data->gen_entity : e; + add_entity_use(c, ident, entity_to_use); if (!return_on_failure && entity_to_use != nullptr) { - add_entity_use(c, ident, entity_to_use); update_untyped_expr_type(c, operand->expr, entity_to_use->type, true); add_type_and_value(c, operand->expr, operand->mode, entity_to_use->type, operand->value); } @@ -7174,6 +7174,7 @@ gb_internal ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *c c->decl->defer_used += 1; } } + add_entity_use(c, operand->expr, initial_entity); } if (operand->mode != Addressing_ProcGroup) { diff --git a/src/tilde.hpp b/src/tilde.hpp index 72d5048bb..7f2ee8076 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -309,7 +309,8 @@ gb_internal cgValue cg_addr_get_ptr(cgProcedure *p, cgAddr const &addr); gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false); gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue src, bool is_volatile=false); -gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); +gb_internal cgAddr cg_add_local (cgProcedure *p, Type *type, Entity *e, bool zero_init); +gb_internal cgAddr cg_add_global(cgProcedure *p, Type *type, Entity *e); gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgValue value); gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment); diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index e6e60be96..708476377 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -76,9 +76,18 @@ gb_internal TB_DebugType *cg_debug_type_internal_record(cgModule *m, Type *type, type_set_offsets(bt); TB_DebugType *record = tb_debug_create_struct(m->mod, 0, ""); - TB_DebugType **fields = tb_debug_record_begin(record, bt->Tuple.variables.count); + isize record_count = 0; + for (Entity *e : bt->Tuple.variables) { + if (e->kind == Entity_Variable) { + record_count += 1; + } + } + TB_DebugType **fields = tb_debug_record_begin(record, record_count); for_array(i, bt->Tuple.variables) { Entity *e = bt->Tuple.variables[i]; + if (e->kind != Entity_Variable) { + continue; + } Type *type = e->type; if (is_type_proc(type)) { type = t_rawptr; diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 96f17bfcf..1966dcd8e 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -2399,7 +2399,12 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { Type *type = type_of_expr(expr); Type *bt = base_type(type); - cgAddr v = cg_add_local(p, type, nullptr, true); + cgAddr v = {}; + if (p->is_startup) { + v = cg_add_global(p, type, nullptr); + } else { + v = cg_add_local(p, type, nullptr, true); + } if (cl->elems.count == 0) { // No need to create it @@ -2424,8 +2429,6 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { } TokenPos pos = ast_token(expr).pos; - if (cl->elems.count == 0) { - } switch (bt->kind) { default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break; @@ -2493,21 +2496,22 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { return v; } - // case Type_Map: { - // GB_ASSERT(!build_context.no_dynamic_literals); + case Type_Map: { + GB_ASSERT(!build_context.no_dynamic_literals); + GB_PANIC("TODO(bill): map literals"); - // cgValue err = cg_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos); - // gb_unused(err); + // cgValue err = cg_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos); + // gb_unused(err); - // for (Ast *elem : cl->elems) { - // ast_node(fv, FieldValue, elem); + // for (Ast *elem : cl->elems) { + // ast_node(fv, FieldValue, elem); - // cgValue key = cg_build_expr(p, fv->field); - // cgValue value = cg_build_expr(p, fv->value); - // cg_internal_dynamic_map_set(p, v.addr, type, key, value, elem); - // } - // break; - // } + // cgValue key = cg_build_expr(p, fv->field); + // cgValue value = cg_build_expr(p, fv->value); + // cg_internal_dynamic_map_set(p, v.addr, type, key, value, elem); + // } + break; + } case Type_Array: { auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); @@ -2523,23 +2527,21 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { assign_array(p, temp_data); break; } - // case Type_EnumeratedArray: { - // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); - - // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + case Type_EnumeratedArray: { + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - // populate(p, cl->elems, &temp_data, type); + populate(p, cl->elems, &temp_data, type); - // cgValue dst_ptr = cg_addr_get_ptr(p, v); - // i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value); - // for_array(i, temp_data) { - // i32 index = cast(i32)(temp_data[i].elem_index - index_offset); - // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); - // } + cgValue dst_ptr = cg_addr_get_ptr(p, v); + i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value); + for_array(i, temp_data) { + i32 index = cast(i32)(temp_data[i].elem_index - index_offset); + temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + } - // assign_array(p, temp_data); - // break; - // } + assign_array(p, temp_data); + break; + } case Type_Slice: { isize count = gb_max(cl->elems.count, cl->max_count); @@ -2570,88 +2572,89 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { return v; } - // case Type_DynamicArray: { - // GB_ASSERT(!build_context.no_dynamic_literals); + case Type_DynamicArray: { + GB_ASSERT(!build_context.no_dynamic_literals); - // Type *et = bt->DynamicArray.elem; - // cgValue size = cg_const_int(p->module, t_int, type_size_of(et)); - // cgValue align = cg_const_int(p->module, t_int, type_align_of(et)); + Type *et = bt->DynamicArray.elem; + cgValue size = cg_const_int(p, t_int, type_size_of(et)); + cgValue align = cg_const_int(p, t_int, type_align_of(et)); - // i64 item_count = gb_max(cl->max_count, cl->elems.count); - // { + i64 item_count = gb_max(cl->max_count, cl->elems.count); + { - // auto args = array_make(temporary_allocator(), 5); - // args[0] = cg_emit_conv(p, cg_addr_get_ptr(p, v), t_rawptr); - // args[1] = size; - // args[2] = align; - // args[3] = cg_const_int(p->module, t_int, item_count); - // args[4] = cg_emit_source_code_location_as_global(p, proc_name, pos); - // cg_emit_runtime_call(p, "__dynamic_array_reserve", args); - // } + auto args = slice_make(temporary_allocator(), 5); + args[0] = cg_emit_conv(p, cg_addr_get_ptr(p, v), t_rawptr); + args[1] = size; + args[2] = align; + args[3] = cg_const_int(p, t_int, item_count); + args[4] = cg_emit_source_code_location_as_global(p, proc_name, pos); + cg_emit_runtime_call(p, "__dynamic_array_reserve", args); + } - // cgValue items = cg_generate_local_array(p, et, item_count); + Type *array_type = alloc_type_array(et, item_count); + cgAddr items_addr = cg_add_local(p, array_type, nullptr, true); + cgValue items = cg_addr_get_ptr(p, items_addr); - // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - // populate(p, cl->elems, &temp_data, type); + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + populate(p, cl->elems, &temp_data, type); - // for_array(i, temp_data) { - // temp_data[i].gep = cg_emit_array_epi(p, items, temp_data[i].elem_index); - // } - // assign_array(p, temp_data); - - // { - // auto args = array_make(temporary_allocator(), 6); - // args[0] = cg_emit_conv(p, v.addr, t_rawptr); - // args[1] = size; - // args[2] = align; - // args[3] = cg_emit_conv(p, items, t_rawptr); - // args[4] = cg_const_int(p->module, t_int, item_count); - // args[5] = cg_emit_source_code_location_as_global(p, proc_name, pos); - // cg_emit_runtime_call(p, "__dynamic_array_append", args); - // } - // break; - // } + for_array(i, temp_data) { + temp_data[i].gep = cg_emit_array_epi(p, items, temp_data[i].elem_index); + } + assign_array(p, temp_data); - // case Type_Basic: { - // GB_ASSERT(is_type_any(bt)); - // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); - // String field_names[2] = { - // str_lit("data"), - // str_lit("id"), - // }; - // Type *field_types[2] = { - // t_rawptr, - // t_typeid, - // }; - - // for_array(field_index, cl->elems) { - // Ast *elem = cl->elems[field_index]; - - // cgValue field_expr = {}; - // isize index = field_index; - - // if (elem->kind == Ast_FieldValue) { - // ast_node(fv, FieldValue, elem); - // Selection sel = lookup_field(bt, fv->field->Ident.token.string, false); - // index = sel.index[0]; - // elem = fv->value; - // } else { - // TypeAndValue tav = type_and_value_of_expr(elem); - // Selection sel = lookup_field(bt, field_names[field_index], false); - // index = sel.index[0]; - // } - - // field_expr = cg_build_expr(p, elem); - - // GB_ASSERT(field_expr.type->kind != Type_Tuple); - - // Type *ft = field_types[index]; - // cgValue fv = cg_emit_conv(p, field_expr, ft); - // cgValue gep = cg_emit_struct_ep(p, cg_addr_get_ptr(p, v), cast(i32)index); - // cg_emit_store(p, gep, fv); - // } - // break; - // } + { + auto args = slice_make(temporary_allocator(), 6); + args[0] = cg_emit_conv(p, v.addr, t_rawptr); + args[1] = size; + args[2] = align; + args[3] = cg_emit_conv(p, items, t_rawptr); + args[4] = cg_const_int(p, t_int, item_count); + args[5] = cg_emit_source_code_location_as_global(p, proc_name, pos); + cg_emit_runtime_call(p, "__dynamic_array_append", args); + } + break; + } + + case Type_Basic: { + GB_ASSERT(is_type_any(bt)); + String field_names[2] = { + str_lit("data"), + str_lit("id"), + }; + Type *field_types[2] = { + t_rawptr, + t_typeid, + }; + + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + + cgValue field_expr = {}; + isize index = field_index; + + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + Selection sel = lookup_field(bt, fv->field->Ident.token.string, false); + index = sel.index[0]; + elem = fv->value; + } else { + TypeAndValue tav = type_and_value_of_expr(elem); + Selection sel = lookup_field(bt, field_names[field_index], false); + index = sel.index[0]; + } + + field_expr = cg_build_expr(p, elem); + + GB_ASSERT(field_expr.type->kind != Type_Tuple); + + Type *ft = field_types[index]; + cgValue fv = cg_emit_conv(p, field_expr, ft); + cgValue gep = cg_emit_struct_ep(p, cg_addr_get_ptr(p, v), index); + cg_emit_store(p, gep, fv); + } + break; + } case Type_BitSet: { i64 sz = type_size_of(type); @@ -2679,48 +2682,41 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { return v; } - // case Type_Matrix: { - // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + case Type_Matrix: { + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + populate(p, cl->elems, &temp_data, type); - // populate(p, cl->elems, &temp_data, type); + cgValue dst_ptr = cg_addr_get_ptr(p, v); + for_array(i, temp_data) { + temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, temp_data[i].elem_index); + } - // cgValue dst_ptr = cg_addr_get_ptr(p, v); - // for_array(i, temp_data) { - // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, temp_data[i].elem_index); - // } + assign_array(p, temp_data); + break; + } - // assign_array(p, temp_data); - // break; - // } + case Type_SimdVector: { + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - // case Type_SimdVector: { - // cgValue vector_value = cg_const_value(p->module, type, exact_value_compound(expr)); - // defer (cg_addr_store(p, v, vector_value)); - - // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); - - // populate(p, cl->elems, &temp_data, type); - - // // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector` - // // might be a better option - // for (auto const &td : temp_data) { - // if (td.value.value != nullptr) { - // if (td.elem_length > 0) { - // for (i64 k = 0; k < td.elem_length; k++) { - // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index + k).value; - // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); - // } - // } else { - // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index).value; - // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); - - // } - // } - // } - // break; - // } + // populate(p, cl->elems, &temp_data, type); + + // // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector` + // // might be a better option + // for (auto const &td : temp_data) if (td.value.node != nullptr) { + // if (td.elem_length > 0) { + // for (i64 k = 0; k < td.elem_length; k++) { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index + k).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + // } + // } else { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + + // } + // } + break; + } } return v; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 80948adea..7e751ac82 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -582,8 +582,13 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice params[param_index++] = local; } } + isize param_entity_index = 0; for_array(i, args) { - Type *param_type = param_entities[i]->type; + Entity *param_entity = nullptr; + do { + param_entity = param_entities[param_entity_index++]; + } while (param_entity->kind != Entity_Variable); + Type *param_type = param_entity->type; cgValue arg = args[i]; arg = cg_emit_conv(p, arg, param_type); arg = cg_flatten_value(p, arg); @@ -839,7 +844,15 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { GB_ASSERT(ce->split_args != nullptr); - auto args = array_make(temporary_allocator(), 0, pt->param_count); + isize internal_param_count = 0; + if (pt->params) for (Entity *e : pt->params->Tuple.variables) { + if (e->kind == Entity_Variable) { + internal_param_count += 1; + } + } + GB_ASSERT(internal_param_count <= pt->param_count); + + auto args = array_make(temporary_allocator(), 0, internal_param_count); bool vari_expand = (ce->ellipsis.pos.line != 0); bool is_c_vararg = pt->c_vararg; @@ -918,7 +931,7 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { } if (!is_c_vararg) { - array_resize(&args, pt->param_count); + array_resize(&args, internal_param_count); } for (Ast *arg : ce->split_args->named) { @@ -938,39 +951,39 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { if (pt->params != nullptr) { - isize min_count = pt->params->Tuple.variables.count; + isize min_count = internal_param_count; if (is_c_vararg) { min_count -= 1; } - GB_ASSERT(args.count >= min_count); - for_array(arg_index, pt->params->Tuple.variables) { - Entity *e = pt->params->Tuple.variables[arg_index]; - if (pt->variadic && arg_index == pt->variadic_index) { + GB_ASSERT_MSG(args.count >= min_count, "in %.*s", LIT(p->name)); + isize arg_index = 0; + for_array(param_index, pt->params->Tuple.variables) { + Entity *e = pt->params->Tuple.variables[param_index]; + if (e->kind == Entity_TypeName) { + continue; + } else if (e->kind == Entity_Constant) { + continue; + } + GB_ASSERT(e->kind == Entity_Variable); + + if (pt->variadic && param_index == pt->variadic_index) { if (!is_c_vararg && args[arg_index].node == nullptr) { - args[arg_index] = cg_const_nil(p, e->type); + args[arg_index++] = cg_const_nil(p, e->type); } continue; } cgValue arg = args[arg_index]; if (arg.node == nullptr) { - switch (e->kind) { - case Entity_TypeName: - case Entity_Constant: - break; - case Entity_Variable: - args[arg_index] = cg_handle_param_value(p, e->type, e->Variable.param_value, pos); - break; - default: - GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind])); - } + GB_ASSERT(e->kind == Entity_Variable); + args[arg_index++] = cg_handle_param_value(p, e->type, e->Variable.param_value, pos); } else { - args[arg_index] = cg_emit_conv(p, arg, e->type); + args[arg_index++] = cg_emit_conv(p, arg, e->type); } } } - isize final_count = is_c_vararg ? args.count : pt->param_count; + isize final_count = is_c_vararg ? args.count : internal_param_count; auto call_args = slice(args, 0, final_count); return cg_emit_call(p, value, call_args); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 88c266689..0b5f122d4 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -747,6 +747,34 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero return addr; } +gb_internal cgAddr cg_add_global(cgProcedure *p, Type *type, Entity *e) { + GB_ASSERT(type != nullptr); + + isize size = type_size_of(type); + TB_CharUnits alignment = cast(TB_CharUnits)type_align_of(type); + if (is_type_matrix(type)) { + alignment *= 2; // NOTE(bill): Just in case + } + + TB_Global *global = tb_global_create(p->module->mod, 0, "", nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(p->module->mod, tb_module_get_data(p->module->mod), global, size, alignment, 0); + TB_Node *local = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, type); + tb_node_append_attrib(local, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + } + + cgAddr addr = cg_addr(cg_value(local, alloc_type_pointer(type))); + if (e) { + map_set(&p->variable_map, e, addr); + } + return addr; +} + + gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment) { TB_CharUnits size = cast(TB_CharUnits)type_size_of(original_type); TB_CharUnits align = cast(TB_CharUnits)gb_max(type_align_of(original_type), min_alignment); diff --git a/src/types.cpp b/src/types.cpp index 17945b109..f6e377cdc 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -3646,18 +3646,26 @@ gb_internal i64 *type_set_offsets_of(Slice const &fields, bool is_pack } } else if (is_packed) { for_array(i, fields) { - i64 size = type_size_of(fields[i]->type); - offsets[i] = curr_offset; - curr_offset += size; + if (fields[i]->kind != Entity_Variable) { + offsets[i] = -1; + } else { + i64 size = type_size_of(fields[i]->type); + offsets[i] = curr_offset; + curr_offset += size; + } } } else { for_array(i, fields) { - Type *t = fields[i]->type; - i64 align = gb_max(type_align_of(t), 1); - i64 size = gb_max(type_size_of( t), 0); - curr_offset = align_formula(curr_offset, align); - offsets[i] = curr_offset; - curr_offset += size; + if (fields[i]->kind != Entity_Variable) { + offsets[i] = -1; + } else { + Type *t = fields[i]->type; + i64 align = gb_max(type_align_of(t), 1); + i64 size = gb_max(type_size_of( t), 0); + curr_offset = align_formula(curr_offset, align); + offsets[i] = curr_offset; + curr_offset += size; + } } } return offsets; @@ -3924,7 +3932,9 @@ gb_internal i64 type_offset_of(Type *t, i64 index, Type **field_type_) { if (gb_is_between(index, 0, t->Tuple.variables.count-1)) { GB_ASSERT(t->Tuple.offsets != nullptr); if (field_type_) *field_type_ = t->Tuple.variables[index]->type; - return t->Tuple.offsets[index]; + i64 offset = t->Tuple.offsets[index]; + GB_ASSERT(offset >= 0); + return offset; } break; -- cgit v1.2.3 From f6d1724835489120ae4a3805495dafc97c86db80 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 28 Jul 2023 12:12:06 +0100 Subject: BODGE for finding procedure symbols Related to a dependency graph race condition bug (THIS NEEDS TO BE FIXED) --- src/check_expr.cpp | 46 +++++++++++++++++++++++++--------------------- src/tilde.cpp | 20 +++++++++++++++++++- src/tilde.hpp | 1 + src/tilde/tb.lib | Bin 4162070 -> 4162224 bytes src/tilde_proc.cpp | 7 ++++--- 5 files changed, 49 insertions(+), 25 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index d5e5f7952..8bc73229e 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -5112,27 +5112,6 @@ gb_internal bool check_identifier_exists(Scope *s, Ast *node, bool nested = fals return false; } -gb_internal isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) { - if (lhs != nullptr && c->decl != nullptr) { - for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) { - Entity *e = lhs[tuple_index + j]; - if (e != nullptr) { - DeclInfo *decl = decl_info_of_entity(e); - if (decl != nullptr) { - rw_mutex_shared_lock(&decl->deps_mutex); - rw_mutex_lock(&c->decl->deps_mutex); - for (Entity *dep : decl->deps) { - ptr_set_add(&c->decl->deps, dep); - } - rw_mutex_unlock(&c->decl->deps_mutex); - rw_mutex_shared_unlock(&decl->deps_mutex); - } - } - } - } - return tuple_count; -} - gb_internal bool check_no_copy_assignment(Operand const &o, String const &context) { if (o.type && is_type_no_copy(o.type)) { Ast *expr = unparen_expr(o.expr); @@ -5240,6 +5219,31 @@ enum UnpackFlag : u32 { gb_internal bool check_unpack_arguments(CheckerContext *ctx, Entity **lhs, isize lhs_count, Array *operands, Slice const &rhs_arguments, UnpackFlags flags) { + auto const &add_dependencies_from_unpacking = [](CheckerContext *c, Entity **lhs, isize lhs_count, isize tuple_index, isize tuple_count) -> isize { + if (lhs == nullptr || c->decl == nullptr) { + return tuple_count; + } + for (isize j = 0; (tuple_index + j) < lhs_count && j < tuple_count; j++) { + Entity *e = lhs[tuple_index + j]; + if (e == nullptr) { + continue; + } + DeclInfo *decl = decl_info_of_entity(e); + if (decl == nullptr) { + continue; + } + rw_mutex_shared_lock(&decl->deps_mutex); + rw_mutex_lock(&c->decl->deps_mutex); + for (Entity *dep : decl->deps) { + ptr_set_add(&c->decl->deps, dep); + } + rw_mutex_unlock(&c->decl->deps_mutex); + rw_mutex_shared_unlock(&decl->deps_mutex); + } + return tuple_count; + }; + + bool allow_ok = (flags & UnpackFlag_AllowOk) != 0; bool is_variadic = (flags & UnpackFlag_IsVariadic) != 0; bool allow_undef = (flags & UnpackFlag_AllowUndef) != 0; diff --git a/src/tilde.cpp b/src/tilde.cpp index 64fe70ec4..fc51a1156 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -241,9 +241,9 @@ gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { GB_ASSERT(e != nullptr); rw_mutex_lock(&m->values_mutex); - defer (rw_mutex_unlock(&m->values_mutex)); TB_Symbol **found = map_get(&m->symbols, e); if (found) { + rw_mutex_unlock(&m->values_mutex); return *found; } @@ -252,8 +252,23 @@ gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { if (proc_found) { TB_Symbol *symbol = (*proc_found)->symbol; map_set(&m->symbols, e, symbol); + rw_mutex_unlock(&m->values_mutex); return symbol; } + rw_mutex_unlock(&m->values_mutex); + + if (e->kind == Entity_Procedure) { + debugf("[Tilde] try to generate procedure %.*s as it was not in the minimum_dependency_set", LIT(e->token.string)); + // IMPORTANT TODO(bill): This is an utter bodge, try and fix this shit + cgProcedure *p = cg_procedure_create(m, e); + if (p != nullptr) { + GB_ASSERT(p->symbol != nullptr); + cg_add_procedure_to_queue(p); + return p->symbol; + } + } + + GB_PANIC("could not find entity's symbol %.*s", LIT(e->token.string)); return nullptr; } @@ -662,6 +677,9 @@ gb_internal WORKER_TASK_PROC(cg_procedure_generate_worker_proc) { } gb_internal void cg_add_procedure_to_queue(cgProcedure *p) { + if (p == nullptr) { + return; + } cgModule *m = p->module; if (m->do_threading) { thread_pool_add_task(cg_procedure_generate_worker_proc, p); diff --git a/src/tilde.hpp b/src/tilde.hpp index 7f2ee8076..6ff5602b5 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -264,6 +264,7 @@ gb_global cgProcedure *cg_cleanup_runtime_proc = nullptr; gb_internal TB_Arena *cg_arena(void); +gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body=false); gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); gb_internal cgProcedure *cg_procedure_generate_anonymous(cgModule *m, Ast *expr, cgProcedure *parent); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index adf355d07..43e477536 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 7e751ac82..8cfc564a7 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -18,7 +18,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty return proto; } -gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body=false) { +gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool ignore_body) { GB_ASSERT(entity != nullptr); GB_ASSERT(entity->kind == Entity_Procedure); if (!entity->Procedure.is_foreign) { @@ -385,7 +385,7 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { if ( - // string_starts_with(p->name, str_lit("bug@main")) || + // string_starts_with(p->name, str_lit("runtime@_windows_default_alloc_or_resize")) || false ) { emit_asm = true; @@ -434,7 +434,8 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { if ( - // string_starts_with(p->name, str_lit("bug@main")) || + // string_starts_with(p->name, str_lit("runtime@_windows_default_alloc")) || + // p->name == str_lit("runtime@_windows_default_alloc_or_resize") || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); -- cgit v1.2.3 From c39a3603720917d6970026e5c0595d468ea9b372 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 28 Jul 2023 14:57:04 +0100 Subject: Update Tilde for the new TB_Passes approach --- core/runtime/os_specific_windows.odin | 15 ++-- core/runtime/print.odin | 10 ++- src/tilde.cpp | 44 ++++++---- src/tilde.hpp | 12 +++ src/tilde/tb.h | 106 +++++++++++------------ src/tilde/tb.lib | Bin 4162224 -> 4177320 bytes src/tilde/tb_arena.h | 76 ++++++++++++++++ src/tilde_expr.cpp | 42 ++++++++- src/tilde_proc.cpp | 158 ++++++++++++++++++++++++++-------- src/tilde_stmt.cpp | 8 ++ 10 files changed, 345 insertions(+), 126 deletions(-) create mode 100644 src/tilde/tb_arena.h (limited to 'src/tilde_proc.cpp') diff --git a/core/runtime/os_specific_windows.odin b/core/runtime/os_specific_windows.odin index 732715793..9f001fa5a 100644 --- a/core/runtime/os_specific_windows.odin +++ b/core/runtime/os_specific_windows.odin @@ -1,9 +1,6 @@ -//+private //+build windows package runtime -import "core:intrinsics" - foreign import kernel32 "system:Kernel32.lib" @(private="file") @@ -102,12 +99,12 @@ _windows_default_alloc_or_resize :: proc "contextless" (size, alignment: int, ol allocated_mem: rawptr if old_ptr != nil { - original_old_ptr := intrinsics.ptr_offset((^rawptr)(old_ptr), -1)^ + original_old_ptr := ([^]rawptr)(old_ptr)[-1] allocated_mem = heap_resize(original_old_ptr, space+size_of(rawptr)) } else { allocated_mem = heap_alloc(space+size_of(rawptr), zero_memory) } - aligned_mem := rawptr(intrinsics.ptr_offset((^u8)(allocated_mem), size_of(rawptr))) + aligned_mem := ([^]u8)(allocated_mem)[size_of(rawptr):] ptr := uintptr(aligned_mem) aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a) @@ -116,10 +113,10 @@ _windows_default_alloc_or_resize :: proc "contextless" (size, alignment: int, ol return nil, .Out_Of_Memory } - aligned_mem = rawptr(aligned_ptr) - intrinsics.ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem + aligned_mem = ([^]byte)(aligned_ptr) + ([^]rawptr)(aligned_mem)[-1] = allocated_mem - return byte_slice(aligned_mem, size), nil + return aligned_mem[:size], nil } _windows_default_alloc :: proc "contextless" (size, alignment: int, zero_memory := true) -> ([]byte, Allocator_Error) { @@ -129,7 +126,7 @@ _windows_default_alloc :: proc "contextless" (size, alignment: int, zero_memory _windows_default_free :: proc "contextless" (ptr: rawptr) { if ptr != nil { - heap_free(intrinsics.ptr_offset((^rawptr)(ptr), -1)^) + heap_free(([^]rawptr)(ptr)[-1]) } } diff --git a/core/runtime/print.odin b/core/runtime/print.odin index 20788b66f..035d47f15 100644 --- a/core/runtime/print.odin +++ b/core/runtime/print.odin @@ -8,6 +8,11 @@ _INTEGER_DIGITS_VAR := _INTEGER_DIGITS when !ODIN_NO_RTTI { print_any_single :: proc "contextless" (arg: any) { x := arg + if x.data == nil { + print_string("nil") + return + } + if loc, ok := x.(Source_Code_Location); ok { print_caller_location(loc) return @@ -48,6 +53,7 @@ when !ODIN_NO_RTTI { case int: print_int(v) case uint: print_uint(v) case uintptr: print_uintptr(v) + case rawptr: print_uintptr(uintptr(v)) case bool: print_string("true" if v else "false") case b8: print_string("true" if v else "false") @@ -58,7 +64,7 @@ when !ODIN_NO_RTTI { case: ti := type_info_of(x.id) #partial switch v in ti.variant { - case Type_Info_Pointer: + case Type_Info_Pointer, Type_Info_Multi_Pointer: print_uintptr((^uintptr)(x.data)^) return } @@ -67,7 +73,9 @@ when !ODIN_NO_RTTI { } } println_any :: proc "contextless" (args: ..any) { + context = default_context() loop: for arg, i in args { + assert(arg.id != nil) if i != 0 { print_string(" ") } diff --git a/src/tilde.cpp b/src/tilde.cpp index fc51a1156..0cbc975c4 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -1,16 +1,16 @@ #include "tilde.hpp" -gb_global Slice global_tb_arenas; +gb_global Slice global_tb_arenas; gb_internal TB_Arena *cg_arena(void) { - return global_tb_arenas[current_thread_index()]; + return &global_tb_arenas[current_thread_index()]; } gb_internal void cg_global_arena_init(void) { - global_tb_arenas = slice_make(permanent_allocator(), global_thread_pool.threads.count); + global_tb_arenas = slice_make(permanent_allocator(), global_thread_pool.threads.count); for_array(i, global_tb_arenas) { - global_tb_arenas[i] = tb_default_arena(); + tb_arena_create(&global_tb_arenas[i], 2ull<<20); } } @@ -426,14 +426,15 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->values); map_init(&m->symbols); - map_init(&m->file_id_map); - map_init(&m->debug_type_map); map_init(&m->proc_debug_type_map); map_init(&m->proc_proto_map); - map_init(&m->anonymous_proc_lits_map); + map_init(&m->equal_procs); + map_init(&m->hasher_procs); + map_init(&m->map_get_procs); + map_init(&m->map_set_procs); array_init(&m->single_threaded_procedure_queue, heap_allocator()); @@ -456,6 +457,10 @@ gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->proc_debug_type_map); map_destroy(&m->proc_proto_map); map_destroy(&m->anonymous_proc_lits_map); + map_destroy(&m->equal_procs); + map_destroy(&m->hasher_procs); + map_destroy(&m->map_get_procs); + map_destroy(&m->map_set_procs); array_free(&m->single_threaded_procedure_queue); @@ -751,6 +756,19 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { array_add(&procedures_to_generate, p); } } + for (cgProcedure *p : procedures_to_generate) { + cg_add_procedure_to_queue(p); + } + + if (!m->do_threading) { + for (isize i = 0; i < m->single_threaded_procedure_queue.count; i++) { + cgProcedure *p = m->single_threaded_procedure_queue[i]; + cg_procedure_generate(p); + } + } + + thread_pool_wait(); + { cgProcedure *p = cg_startup_runtime_proc; cg_procedure_begin(p); @@ -765,18 +783,6 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { cg_procedure_end(p); } - for (cgProcedure *p : procedures_to_generate) { - cg_add_procedure_to_queue(p); - } - - if (!m->do_threading) { - for (isize i = 0; i < m->single_threaded_procedure_queue.count; i++) { - cgProcedure *p = m->single_threaded_procedure_queue[i]; - cg_procedure_generate(p); - } - } - - thread_pool_wait(); TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; diff --git a/src/tilde.hpp b/src/tilde.hpp index 6ff5602b5..a70d03a6c 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -6,6 +6,7 @@ #endif #include "tilde/tb.h" +#include "tilde/tb_arena.h" #define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } @@ -230,6 +231,12 @@ struct cgModule { BlockingMutex anonymous_proc_lits_mutex; PtrMap anonymous_proc_lits_map; + RecursiveMutex generated_procs_mutex; + PtrMap equal_procs; + PtrMap hasher_procs; + PtrMap map_get_procs; + PtrMap map_set_procs; + // NOTE(bill): no need to protect this with a mutex PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) @@ -319,6 +326,7 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results); gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results); +gb_internal void cg_build_return_stmt_internal_single(cgProcedure *p, cgValue result); gb_internal void cg_build_range_stmt(cgProcedure *p, Ast *node); gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e); @@ -341,6 +349,10 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t); gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, cgValue x); gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right); gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgValue rhs, Type *type); +gb_internal cgValue cg_emit_unary_arith(cgProcedure *p, TokenKind op, cgValue x, Type *type); + +gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type); + gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice const &args); gb_internal cgValue cg_emit_runtime_call(cgProcedure *p, char const *name, Slice const &args); diff --git a/src/tilde/tb.h b/src/tilde/tb.h index a68f06554..b20b98b35 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -15,20 +15,21 @@ #define TB_VERSION_MINOR 2 #define TB_VERSION_PATCH 0 -#ifdef __cplusplus -#define TB_EXTERN extern "C" -#else -#define TB_EXTERN -#endif - -#ifdef TB_DLL -# ifdef TB_IMPORT_DLL -# define TB_API TB_EXTERN __declspec(dllimport) +#ifndef TB_API +# ifdef __cplusplus +# define TB_EXTERN extern "C" # else -# define TB_API TB_EXTERN __declspec(dllexport) +# define TB_EXTERN +# endif +# ifdef TB_DLL +# ifdef TB_IMPORT_DLL +# define TB_API TB_EXTERN __declspec(dllimport) +# else +# define TB_API TB_EXTERN __declspec(dllexport) +# endif +# else +# define TB_API TB_EXTERN # endif -#else -# define TB_API TB_EXTERN #endif // These are flags @@ -171,7 +172,6 @@ typedef enum TB_FloatFormat { typedef union TB_DataType { struct { uint8_t type; - // 2^N where N is the width value. // Only integers and floats can be wide. uint8_t width; // for integers it's the bitwidth @@ -406,8 +406,6 @@ typedef struct TB_Symbol { typedef int TB_Reg; -#define TB_NULL_REG NULL - typedef struct TB_Node TB_Node; struct TB_Node { TB_NodeType type; @@ -586,29 +584,13 @@ typedef struct { typedef void (*TB_PrintCallback)(void* user_data, const char* fmt, ...); -//////////////////////////////// -// Arena -//////////////////////////////// -// the goal is to move more things to transparent arenas, for now it's just function -// IR which is a big one if you're interested in freeing them in whatever organization -// you please. - -// allocations can make no guarentees about being sequential -// tho it would be greatly appreciated at least to some degree. +// defined in common/arena.h typedef struct TB_Arena TB_Arena; -struct TB_Arena { - // alignment never goes past max_align_t - void* (*alloc)(TB_Arena* arena, size_t size, size_t align); - // clearing but we're not done with it yet, cheap - void (*clear)(TB_Arena* arena); - - // frees everything within the arena, potentially expensive - void (*free)(TB_Arena* arena); -}; - -// allocates in 16MiB chunks and does linear allocation in 'em -TB_API TB_Arena* tb_default_arena(void); +// 0 for default +TB_API void tb_arena_create(TB_Arena* restrict arena, size_t chunk_size); +TB_API void tb_arena_destroy(TB_Arena* restrict arena); +TB_API bool tb_arena_is_empty(TB_Arena* arena); //////////////////////////////// // Module management @@ -651,8 +633,7 @@ struct TB_Assembly { // this is where the machine code and other relevant pieces go. typedef struct TB_FunctionOutput TB_FunctionOutput; -// returns NULL if it fails -TB_API TB_FunctionOutput* tb_module_compile_function(TB_Module* m, TB_Function* f, TB_ISelMode isel_mode, bool emit_asm); +TB_API void tb_output_print_asm(TB_FunctionOutput* out, FILE* fp); TB_API uint8_t* tb_output_get_code(TB_FunctionOutput* out, size_t* out_length); @@ -865,6 +846,9 @@ TB_API TB_DebugType* tb_debug_create_func(TB_Module* m, TB_CallingConv cc, size_ TB_API TB_DebugType* tb_debug_field_type(TB_DebugType* type); +TB_API size_t tb_debug_func_return_count(TB_DebugType* type); +TB_API size_t tb_debug_func_param_count(TB_DebugType* type); + // you'll need to fill these if you make a function TB_API TB_DebugType** tb_debug_func_params(TB_DebugType* type); TB_API TB_DebugType** tb_debug_func_returns(TB_DebugType* type); @@ -895,9 +879,6 @@ TB_API void tb_default_print_callback(void* user_data, const char* fmt, ...); TB_API void tb_inst_set_location(TB_Function* f, TB_FileID file, int line); -// this only allows for power of two vector types -TB_API TB_DataType tb_vector_type(TB_DataTypeEnum type, int width); - // if section is NULL, default to .text TB_API TB_Function* tb_function_create(TB_Module* m, ptrdiff_t len, const char* name, TB_Linkage linkage, TB_ComdatType comdat); @@ -1073,25 +1054,40 @@ TB_API void tb_inst_branch(TB_Function* f, TB_DataType dt, TB_Node* key, TB_Node TB_API void tb_inst_ret(TB_Function* f, size_t count, TB_Node** values); //////////////////////////////// -// Optimizer +// Passes //////////////////////////////// // Function analysis, optimizations, and codegen are all part of this -typedef struct TB_FuncOpt TB_FuncOpt; +typedef struct TB_Passes TB_Passes; -// the arena is used to allocate the nodes -TB_API TB_FuncOpt* tb_funcopt_enter(TB_Function* f, TB_Arena* arena); -TB_API void tb_funcopt_exit(TB_FuncOpt* opt); +// the arena is used to allocate the nodes while passes are being done. +TB_API TB_Passes* tb_pass_enter(TB_Function* f, TB_Arena* arena); +TB_API void tb_pass_exit(TB_Passes* opt); -TB_API bool tb_funcopt_peephole(TB_FuncOpt* opt); -TB_API bool tb_funcopt_mem2reg(TB_FuncOpt* opt); -TB_API bool tb_funcopt_loop(TB_FuncOpt* opt); +// transformation passes: +// peephole: runs most simple reductions on the code, +// should be run after any bigger passes (it's incremental +// so it's not that bad) +// +// mem2reg: lowers TB_LOCALs into SSA values, this makes more +// data flow analysis possible on the code and allows to codegen +// to place variables into registers. +// +// loop: NOT READY +// +TB_API bool tb_pass_peephole(TB_Passes* opt); +TB_API bool tb_pass_mem2reg(TB_Passes* opt); +TB_API bool tb_pass_loop(TB_Passes* opt); -// isn't an optimization, just does the name flat form of IR printing -TB_API bool tb_funcopt_print(TB_FuncOpt* opt); +// analysis +// print: prints IR in a flattened text form. +TB_API bool tb_pass_print(TB_Passes* opt); -TB_API void tb_funcopt_kill(TB_FuncOpt* opt, TB_Node* n); -TB_API bool tb_funcopt_mark(TB_FuncOpt* opt, TB_Node* n); -TB_API void tb_funcopt_mark_users(TB_FuncOpt* opt, TB_Node* n); +// codegen +TB_API TB_FunctionOutput* tb_pass_codegen(TB_Passes* opt, bool emit_asm); + +TB_API void tb_pass_kill_node(TB_Passes* opt, TB_Node* n); +TB_API bool tb_pass_mark(TB_Passes* opt, TB_Node* n); +TB_API void tb_pass_mark_users(TB_Passes* opt, TB_Node* n); //////////////////////////////// // IR access @@ -1099,8 +1095,6 @@ TB_API void tb_funcopt_mark_users(TB_FuncOpt* opt, TB_Node* n); TB_API const char* tb_node_get_name(TB_Node* n); TB_API TB_Node* tb_get_parent_region(TB_Node* n); -TB_API bool tb_has_effects(TB_Node* n); - TB_API bool tb_node_is_constant_non_zero(TB_Node* n); TB_API bool tb_node_is_constant_zero(TB_Node* n); diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 43e477536..b0886ebfb 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde/tb_arena.h b/src/tilde/tb_arena.h new file mode 100644 index 000000000..d50e777da --- /dev/null +++ b/src/tilde/tb_arena.h @@ -0,0 +1,76 @@ +#pragma once +#include +#include + +#ifndef TB_API +# ifdef __cplusplus +# define TB_EXTERN extern "C" +# else +# define TB_EXTERN +# endif +# ifdef TB_DLL +# ifdef TB_IMPORT_DLL +# define TB_API TB_EXTERN __declspec(dllimport) +# else +# define TB_API TB_EXTERN __declspec(dllexport) +# endif +# else +# define TB_API TB_EXTERN +# endif +#endif + +enum { + TB_ARENA_SMALL_CHUNK_SIZE = 4 * 1024, + TB_ARENA_MEDIUM_CHUNK_SIZE = 512 * 1024, + TB_ARENA_LARGE_CHUNK_SIZE = 2 * 1024 * 1024, + + TB_ARENA_ALIGNMENT = 16, +}; + +typedef struct TB_ArenaChunk TB_ArenaChunk; +struct TB_ArenaChunk { + TB_ArenaChunk* next; + size_t pad; + char data[]; +}; + +typedef struct TB_Arena { + size_t chunk_size; + TB_ArenaChunk* base; + TB_ArenaChunk* top; + + // top of the allocation space + char* watermark; + char* high_point; // &top->data[chunk_size] +} TB_Arena; + +typedef struct TB_ArenaSavepoint { + TB_ArenaChunk* top; + char* watermark; +} TB_ArenaSavepoint; + +#define TB_ARENA_FOR(it, arena) for (TB_ArenaChunk* it = (arena)->base; it != NULL; it = it->next) + +#define TB_ARENA_ALLOC(arena, T) tb_arena_alloc(arena, sizeof(T)) +#define TB_ARENA_ARR_ALLOC(arena, count, T) tb_arena_alloc(arena, (count) * sizeof(T)) + +TB_API void tb_arena_create(TB_Arena* restrict arena, size_t chunk_size); +TB_API void tb_arena_destroy(TB_Arena* restrict arena); + +TB_API void* tb_arena_unaligned_alloc(TB_Arena* restrict arena, size_t size); +TB_API void* tb_arena_alloc(TB_Arena* restrict arena, size_t size); + +// asserts if ptr+size != watermark +TB_API void tb_arena_pop(TB_Arena* restrict arena, void* ptr, size_t size); + +// in case you wanna mix unaligned and aligned arenas +TB_API void tb_arena_realign(TB_Arena* restrict arena); + +TB_API bool tb_arena_is_empty(TB_Arena* arena); + +// savepoints +TB_API TB_ArenaSavepoint tb_arena_save(TB_Arena* arena); +TB_API void tb_arena_restore(TB_Arena* arena, TB_ArenaSavepoint sp); + +// resets to only having one chunk +TB_API void tb_arena_clear(TB_Arena* arena); diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 1966dcd8e..fdd26e3db 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -304,6 +304,42 @@ gb_internal cgValue cg_emit_byte_swap(cgProcedure *p, cgValue value, Type *end_t return cg_emit_transmute(p, value, end_type); } +gb_internal cgValue cg_emit_comp_records(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right, Type *type) { + GB_ASSERT((is_type_struct(type) || is_type_union(type)) && is_type_comparable(type)); + cgValue left_ptr = cg_address_from_load_or_generate_local(p, left); + cgValue right_ptr = cg_address_from_load_or_generate_local(p, right); + cgValue res = {}; + if (type_size_of(type) == 0) { + switch (op_kind) { + case Token_CmpEq: + return cg_const_bool(p, t_bool, true); + case Token_NotEq: + return cg_const_bool(p, t_bool, false); + } + GB_PANIC("invalid operator"); + } + TEMPORARY_ALLOCATOR_GUARD(); + if (is_type_simple_compare(type)) { + // TODO(bill): Test to see if this is actually faster!!!! + auto args = slice_make(temporary_allocator(), 3); + args[0] = cg_emit_conv(p, left_ptr, t_rawptr); + args[1] = cg_emit_conv(p, right_ptr, t_rawptr); + args[2] = cg_const_int(p, t_int, type_size_of(type)); + res = cg_emit_runtime_call(p, "memory_equal", args); + } else { + cgProcedure *equal_proc = cg_equal_proc_for_type(p->module, type); + cgValue value = cg_value(tb_inst_get_symbol_address(p->func, equal_proc->symbol), equal_proc->type); + auto args = slice_make(temporary_allocator(), 2); + args[0] = cg_emit_conv(p, left_ptr, t_rawptr); + args[1] = cg_emit_conv(p, right_ptr, t_rawptr); + res = cg_emit_call(p, value, args); + } + if (op_kind == Token_NotEq) { + res = cg_emit_unary_arith(p, Token_Not, res, res.type); + } + return res; +} + gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right) { GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1)); @@ -440,13 +476,11 @@ gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left } if ((is_type_struct(a) || is_type_union(a)) && is_type_comparable(a)) { - GB_PANIC("TODO(bill): cg_compare_records"); - // return cg_compare_records(p, op_kind, left, right, a); + return cg_emit_comp_records(p, op_kind, left, right, a); } if ((is_type_struct(b) || is_type_union(b)) && is_type_comparable(b)) { - GB_PANIC("TODO(bill): cg_compare_records"); - // return cg_compare_records(p, op_kind, left, right, b); + return cg_emit_comp_records(p, op_kind, left, right, b); } if (is_type_string(a)) { diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8cfc564a7..26c70b508 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -368,22 +368,17 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { cgProcedure *p = cast(cgProcedure *)data; - bool emit_asm = false; - - if (false && - string_starts_with(p->name, str_lit("bug@main"))) { - TB_Arena *arena = cg_arena(); - TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - defer (tb_funcopt_exit(opt)); - - tb_funcopt_peephole(opt); - tb_funcopt_mem2reg(opt); - tb_funcopt_peephole(opt); - - emit_asm = true; + TB_Passes *opt = tb_pass_enter(p->func, cg_arena()); + defer (tb_pass_exit(opt)); + + // optimization passes + if (false) { + tb_pass_peephole(opt); + tb_pass_mem2reg(opt); + tb_pass_peephole(opt); } - + bool emit_asm = false; if ( // string_starts_with(p->name, str_lit("runtime@_windows_default_alloc_or_resize")) || false @@ -391,12 +386,27 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { emit_asm = true; } - TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); + // emit ir + if ( + // string_starts_with(p->name, str_lit("bug@main")) || + // p->name == str_lit("runtime@_windows_default_alloc_or_resize") || + false + ) { // IR Printing + TB_Arena *arena = cg_arena(); + TB_Passes *passes = tb_pass_enter(p->func, arena); + defer (tb_pass_exit(passes)); + + tb_pass_print(passes); + fprintf(stdout, "\n"); + } + if (false) { // GraphViz printing + tb_function_print(p->func, tb_default_print_callback, stdout); + } + + // compile + TB_FunctionOutput *output = tb_pass_codegen(opt, emit_asm); if (emit_asm) { - TB_Assembly *assembly = tb_output_get_asm(output); - for (TB_Assembly *node = assembly; node != nullptr; node = node->next) { - fprintf(stdout, "%.*s", cast(int)node->length, node->data); - } + tb_output_print_asm(output, stdout); fprintf(stdout, "\n"); } @@ -427,27 +437,9 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { return; } - cg_procedure_begin(p); cg_build_stmt(p, p->body); cg_procedure_end(p); - - - if ( - // string_starts_with(p->name, str_lit("runtime@_windows_default_alloc")) || - // p->name == str_lit("runtime@_windows_default_alloc_or_resize") || - false - ) { // IR Printing - TB_Arena *arena = tb_default_arena(); - defer (arena->free(arena)); - TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); - defer (tb_funcopt_exit(opt)); - tb_funcopt_print(opt); - fprintf(stdout, "\n"); - } - if (false) { // GraphViz printing - tb_function_print(p->func, tb_default_print_callback, stdout); - } } gb_internal void cg_build_nested_proc(cgProcedure *p, AstProcLit *pd, Entity *e) { @@ -989,3 +981,95 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { return cg_emit_call(p, value, call_args); } + + + + +gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type) { + type = base_type(type); + GB_ASSERT(is_type_comparable(type)); + + mutex_lock(&m->generated_procs_mutex); + defer (mutex_unlock(&m->generated_procs_mutex)); + + cgProcedure **found = map_get(&m->equal_procs, type); + if (found) { + return *found; + } + + static std::atomic proc_index; + + char buf[32] = {}; + isize n = gb_snprintf(buf, 32, "__$equal%u", 1+proc_index.fetch_add(1)); + char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1); + String proc_name = make_string_c(str); + + + cgProcedure *p = cg_procedure_create_dummy(m, proc_name, t_equal_proc); + map_set(&m->equal_procs, type, p); + + cg_procedure_begin(p); + + TB_Node *x = tb_inst_param(p->func, 0); + TB_Node *y = tb_inst_param(p->func, 1); + GB_ASSERT(x->dt.type == TB_PTR); + GB_ASSERT(y->dt.type == TB_PTR); + + TB_DataType ret_dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; + + TB_Node *node_true = tb_inst_uint(p->func, ret_dt, true); + TB_Node *node_false = tb_inst_uint(p->func, ret_dt, false); + + TB_Node *same_ptr_region = cg_control_region(p, "same_ptr"); + TB_Node *diff_ptr_region = cg_control_region(p, "diff_ptr"); + + TB_Node *is_same_ptr = tb_inst_cmp_eq(p->func, x, y); + tb_inst_if(p->func, is_same_ptr, same_ptr_region, diff_ptr_region); + + tb_inst_set_control(p->func, same_ptr_region); + tb_inst_ret(p->func, 1, &node_true); + + tb_inst_set_control(p->func, diff_ptr_region); + + Type *pt = alloc_type_pointer(type); + cgValue lhs = cg_value(x, pt); + cgValue rhs = cg_value(y, pt); + + if (type->kind == Type_Struct) { + type_set_offsets(type); + + TB_Node *false_region = cg_control_region(p, "bfalse"); + cgValue res = cg_const_bool(p, t_bool, true); + + for_array(i, type->Struct.fields) { + TB_Node *next_region = cg_control_region(p, "btrue"); + + cgValue plhs = cg_emit_struct_ep(p, lhs, i); + cgValue prhs = cg_emit_struct_ep(p, rhs, i); + cgValue left = cg_emit_load(p, plhs); + cgValue right = cg_emit_load(p, prhs); + cgValue ok = cg_emit_comp(p, Token_CmpEq, left, right); + + cg_emit_if(p, ok, next_region, false_region); + + cg_emit_goto(p, next_region); + tb_inst_set_control(p->func, next_region); + } + + tb_inst_ret(p->func, 1, &node_true); + tb_inst_set_control(p->func, false_region); + tb_inst_ret(p->func, 1, &node_false); + + } else if (type->kind == Type_Union) { + GB_PANIC("TODO(bill): union comparison"); + } else { + cgValue left = cg_lvalue_addr(x, type); + cgValue right = cg_lvalue_addr(y, type); + cgValue ok = cg_emit_comp(p, Token_CmpEq, left, right); + cg_build_return_stmt_internal_single(p, ok); + } + + cg_procedure_end(p); + + return p; +} \ No newline at end of file diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 0b5f122d4..382b4c02d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1047,6 +1047,14 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { } } +gb_internal void cg_build_return_stmt_internal_single(cgProcedure *p, cgValue result) { + Slice results = {}; + results.data = &result; + results.count = 1; + cg_build_return_stmt_internal(p, results); +} + + gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results) { TypeTuple *tuple = &p->type->Proc.results->Tuple; isize return_count = p->type->Proc.result_count; -- cgit v1.2.3 From aadc8477b9773a5d2f22310cad5833e81c15c4bd Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 3 Aug 2023 13:42:14 +0100 Subject: Generate equal proc for unions --- src/tilde/tb.lib | Bin 4177320 -> 4173944 bytes src/tilde_proc.cpp | 46 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index b0886ebfb..1dc4f3557 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 26c70b508..00062d708 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1061,7 +1061,51 @@ gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type) { tb_inst_ret(p->func, 1, &node_false); } else if (type->kind == Type_Union) { - GB_PANIC("TODO(bill): union comparison"); + if (type_size_of(type) == 0) { + tb_inst_ret(p->func, 1, &node_true); + } else if (is_type_union_maybe_pointer(type)) { + Type *v = type->Union.variants[0]; + Type *pv = alloc_type_pointer(v); + + cgValue left = cg_emit_load(p, cg_emit_conv(p, lhs, pv)); + cgValue right = cg_emit_load(p, cg_emit_conv(p, rhs, pv)); + cgValue ok = cg_emit_comp(p, Token_CmpEq, left, right); + cg_build_return_stmt_internal_single(p, ok); + } else { + TB_Node *false_region = cg_control_region(p, "bfalse"); + TB_Node *switch_region = cg_control_region(p, "bswitch"); + + cgValue lhs_tag = cg_emit_load(p, cg_emit_union_tag_ptr(p, lhs)); + cgValue rhs_tag = cg_emit_load(p, cg_emit_union_tag_ptr(p, rhs)); + + cgValue tag_eq = cg_emit_comp(p, Token_CmpEq, lhs_tag, rhs_tag); + cg_emit_if(p, tag_eq, switch_region, false_region); + + size_t entry_count = type->Union.variants.count; + TB_SwitchEntry *keys = gb_alloc_array(temporary_allocator(), TB_SwitchEntry, entry_count); + for (size_t i = 0; i < entry_count; i++) { + TB_Node *region = cg_control_region(p, "bcase"); + Type *variant = type->Union.variants[i]; + keys[i].key = union_variant_index(type, variant); + keys[i].value = region; + + tb_inst_set_control(p->func, region); + Type *vp = alloc_type_pointer(variant); + cgValue left = cg_emit_load(p, cg_emit_conv(p, lhs, vp)); + cgValue right = cg_emit_load(p, cg_emit_conv(p, rhs, vp)); + cgValue ok = cg_emit_comp(p, Token_CmpEq, left, right); + cg_build_return_stmt_internal_single(p, ok); + } + + + tb_inst_set_control(p->func, switch_region); + TB_DataType tag_dt = cg_data_type(lhs_tag.type); + GB_ASSERT(lhs_tag.kind == cgValue_Value); + tb_inst_branch(p->func, tag_dt, lhs_tag.node, false_region, entry_count, keys); + + tb_inst_set_control(p->func, false_region); + tb_inst_ret(p->func, 1, &node_false); + } } else { cgValue left = cg_lvalue_addr(x, type); cgValue right = cg_lvalue_addr(y, type); -- cgit v1.2.3 From 4a71603a777783a2ee4cd78368f1b1fbe76d7773 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 3 Aug 2023 14:46:22 +0100 Subject: Add hasher proc generation --- src/tilde.hpp | 7 +- src/tilde_builtin.cpp | 6 ++ src/tilde_expr.cpp | 42 +++++++++++ src/tilde_proc.cpp | 188 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 241 insertions(+), 2 deletions(-) (limited to 'src/tilde_proc.cpp') diff --git a/src/tilde.hpp b/src/tilde.hpp index a70d03a6c..5944c9ef7 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -350,9 +350,12 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left, cgValue right); gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgValue rhs, Type *type); gb_internal cgValue cg_emit_unary_arith(cgProcedure *p, TokenKind op, cgValue x, Type *type); +gb_internal void cg_emit_increment(cgProcedure *p, cgValue addr); -gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type); - +gb_internal cgProcedure *cg_equal_proc_for_type (cgModule *m, Type *type); +gb_internal cgProcedure *cg_hasher_proc_for_type(cgModule *m, Type *type); +gb_internal cgValue cg_hasher_proc_value_for_type(cgProcedure *p, Type *type); +gb_internal cgValue cg_equal_proc_value_for_type(cgProcedure *p, Type *type); gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice const &args); gb_internal cgValue cg_emit_runtime_call(cgProcedure *p, char const *name, Slice const &args); diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index edf436424..9dbc3f7c5 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -432,6 +432,12 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr return cg_emit_runtime_call(p, "__type_info_of", args); } + + case BuiltinProc_type_equal_proc: + return cg_equal_proc_value_for_type(p, ce->args[0]->tav.type); + + case BuiltinProc_type_hasher_proc: + return cg_hasher_proc_value_for_type(p, ce->args[0]->tav.type); } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index fdd26e3db..b654eb5e9 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1780,6 +1780,48 @@ gb_internal void cg_emit_if(cgProcedure *p, cgValue const &cond, TB_Node *true_r tb_inst_if(p->func, cond.node, true_region, false_region); } + +struct cgLoopData { + cgAddr index_addr; + cgValue index; + TB_Node *body; + TB_Node *done; + TB_Node *loop; +}; + +gb_internal cgLoopData cg_loop_start(cgProcedure *p, isize count, Type *index_type) { + cgLoopData data = {}; + + cgValue max = cg_const_int(p, index_type, count); + + data.index_addr = cg_add_local(p, index_type, nullptr, true); + + data.body = cg_control_region(p, "loop_body"); + data.done = cg_control_region(p, "loop_done"); + data.loop = cg_control_region(p, "loop_loop"); + + cg_emit_goto(p, data.loop); + tb_inst_set_control(p->func, data.loop); + + data.index = cg_addr_load(p, data.index_addr); + + cgValue cond = cg_emit_comp(p, Token_Lt, data.index, max); + cg_emit_if(p, cond, data.body, data.done); + tb_inst_set_control(p->func, data.body); + + return data; +} + +gb_internal void cg_loop_end(cgProcedure *p, cgLoopData const &data) { + if (data.index_addr.addr.node != nullptr) { + cg_emit_increment(p, data.index_addr.addr); + cg_emit_goto(p, data.loop); + tb_inst_set_control(p->func, data.done); + } +} + + + gb_internal void cg_build_try_lhs_rhs(cgProcedure *p, Ast *arg, Type *final_type, cgValue *lhs_, cgValue *rhs_) { cgValue lhs = {}; cgValue rhs = {}; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 00062d708..1981d32ce 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -984,6 +984,17 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { +gb_internal cgValue cg_hasher_proc_value_for_type(cgProcedure *p, Type *type) { + cgProcedure *found = cg_hasher_proc_for_type(p->module, type); + return cg_value(tb_inst_get_symbol_address(p->func, found->symbol), found->type); +} + +gb_internal cgValue cg_equal_proc_value_for_type(cgProcedure *p, Type *type) { + cgProcedure *found = cg_equal_proc_for_type(p->module, type); + return cg_value(tb_inst_get_symbol_address(p->func, found->symbol), found->type); +} + + gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type) { type = base_type(type); @@ -1115,5 +1126,182 @@ gb_internal cgProcedure *cg_equal_proc_for_type(cgModule *m, Type *type) { cg_procedure_end(p); + return p; +} + + +gb_internal cgValue cg_simple_compare_hash(cgProcedure *p, Type *type, cgValue data, cgValue seed) { + TEMPORARY_ALLOCATOR_GUARD(); + + GB_ASSERT_MSG(is_type_simple_compare(type), "%s", type_to_string(type)); + + auto args = slice_make(temporary_allocator(), 3); + args[0] = data; + args[1] = seed; + args[2] = cg_const_int(p, t_int, type_size_of(type)); + return cg_emit_runtime_call(p, "default_hasher", args); +} + + + + + +gb_internal cgProcedure *cg_hasher_proc_for_type(cgModule *m, Type *type) { + type = base_type(type); + GB_ASSERT(is_type_valid_for_keys(type)); + + mutex_lock(&m->generated_procs_mutex); + defer (mutex_unlock(&m->generated_procs_mutex)); + + cgProcedure **found = map_get(&m->hasher_procs, type); + if (found) { + return *found; + } + + static std::atomic proc_index; + + char buf[32] = {}; + isize n = gb_snprintf(buf, 32, "__$hasher%u", 1+proc_index.fetch_add(1)); + char *str = gb_alloc_str_len(permanent_allocator(), buf, n-1); + String proc_name = make_string_c(str); + + + cgProcedure *p = cg_procedure_create_dummy(m, proc_name, t_hasher_proc); + map_set(&m->hasher_procs, type, p); + + cg_procedure_begin(p); + defer (cg_procedure_end(p)); + + TB_Node *x = tb_inst_param(p->func, 0); // data + TB_Node *y = tb_inst_param(p->func, 1); // seed + + cgValue data = cg_value(x, t_rawptr); + cgValue seed = cg_value(y, t_uintptr); + + if (is_type_simple_compare(type)) { + cgValue res = cg_simple_compare_hash(p, type, data, seed); + cg_build_return_stmt_internal_single(p, res); + return p; + } + + TEMPORARY_ALLOCATOR_GUARD(); + + auto args = slice_make(temporary_allocator(), 2); + + if (type->kind == Type_Struct) { + type_set_offsets(type); + for_array(i, type->Struct.fields) { + i64 offset = type->Struct.offsets[i]; + Entity *field = type->Struct.fields[i]; + cgValue field_hasher = cg_hasher_proc_value_for_type(p, field->type); + + TB_Node *ptr = tb_inst_member_access(p->func, data.node, offset); + + args[0] = cg_value(ptr, alloc_type_pointer(field->type)); + args[1] = seed; + seed = cg_emit_call(p, field_hasher, args); + } + + cg_build_return_stmt_internal_single(p, seed); + } else if (type->kind == Type_Union) { + if (type_size_of(type) == 0) { + cg_build_return_stmt_internal_single(p, seed); + } else if (is_type_union_maybe_pointer(type)) { + Type *v = type->Union.variants[0]; + cgValue variant_hasher = cg_hasher_proc_value_for_type(p, v); + + args[0] = data; + args[1] = seed; + cgValue res = cg_emit_call(p, variant_hasher, args); + cg_build_return_stmt_internal_single(p, seed); + } else { + TB_Node *end_region = cg_control_region(p, "bend"); + TB_Node *switch_region = cg_control_region(p, "bswitch"); + + cg_emit_goto(p, switch_region); + + size_t entry_count = type->Union.variants.count; + TB_SwitchEntry *keys = gb_alloc_array(temporary_allocator(), TB_SwitchEntry, entry_count); + for (size_t i = 0; i < entry_count; i++) { + TB_Node *region = cg_control_region(p, "bcase"); + Type *variant = type->Union.variants[i]; + keys[i].key = union_variant_index(type, variant); + keys[i].value = region; + + tb_inst_set_control(p->func, region); + + cgValue variant_hasher = cg_hasher_proc_value_for_type(p, variant); + + args[0] = data; + args[1] = seed; + cgValue res = cg_emit_call(p, variant_hasher, args); + cg_build_return_stmt_internal_single(p, res); + } + + tb_inst_set_control(p->func, switch_region); + + cgValue tag_ptr = cg_emit_union_tag_ptr(p, data); + cgValue tag = cg_emit_load(p, tag_ptr); + + TB_DataType tag_dt = cg_data_type(tag.type); + GB_ASSERT(tag.kind == cgValue_Value); + tb_inst_branch(p->func, tag_dt, tag.node, end_region, entry_count, keys); + + tb_inst_set_control(p->func, end_region); + cg_build_return_stmt_internal_single(p, seed); + } + } else if (type->kind == Type_Array) { + cgAddr pres = cg_add_local(p, t_uintptr, nullptr, false); + cg_addr_store(p, pres, seed); + + cgValue elem_hasher = cg_hasher_proc_value_for_type(p, type->Array.elem); + + auto loop_data = cg_loop_start(p, type->Array.count, t_int); + + i64 stride = type_size_of(type->Array.elem); + TB_Node *ptr = tb_inst_array_access(p->func, data.node, loop_data.index.node, stride); + args[0] = cg_value(ptr, alloc_type_pointer(type->Array.elem)); + args[1] = cg_addr_load(p, pres); + + cgValue new_seed = cg_emit_call(p, elem_hasher, args); + cg_addr_store(p, pres, new_seed); + + cg_loop_end(p, loop_data); + + cgValue res = cg_addr_load(p, pres); + cg_build_return_stmt_internal_single(p, res); + } else if (type->kind == Type_EnumeratedArray) { + cgAddr pres = cg_add_local(p, t_uintptr, nullptr, false); + cg_addr_store(p, pres, seed); + + cgValue elem_hasher = cg_hasher_proc_value_for_type(p, type->EnumeratedArray.elem); + + auto loop_data = cg_loop_start(p, type->EnumeratedArray.count, t_int); + + i64 stride = type_size_of(type->EnumeratedArray.elem); + TB_Node *ptr = tb_inst_array_access(p->func, data.node, loop_data.index.node, stride); + args[0] = cg_value(ptr, alloc_type_pointer(type->EnumeratedArray.elem)); + args[1] = cg_addr_load(p, pres); + + cgValue new_seed = cg_emit_call(p, elem_hasher, args); + cg_addr_store(p, pres, new_seed); + + cg_loop_end(p, loop_data); + + cgValue res = cg_addr_load(p, pres); + cg_build_return_stmt_internal_single(p, res); + } else if (is_type_cstring(type)) { + args[0] = data; + args[1] = seed; + cgValue res = cg_emit_runtime_call(p, "default_hasher_cstring", args); + cg_build_return_stmt_internal_single(p, seed); + } else if (is_type_string(type)) { + args[0] = data; + args[1] = seed; + cgValue res = cg_emit_runtime_call(p, "default_hasher_string", args); + cg_build_return_stmt_internal_single(p, seed); + } else { + GB_PANIC("Unhandled type for hasher: %s", type_to_string(type)); + } return p; } \ No newline at end of file -- cgit v1.2.3