From ad91bde59722cada146f52d776f3a67952965215 Mon Sep 17 00:00:00 2001 From: Brendan Hansen Date: Sat, 4 Dec 2021 12:14:43 -0600 Subject: [PATCH] implicit zero-ing of stack allocated variables --- include/astnodes.h | 2 ++ src/checker.c | 7 +++++++ src/wasm_emit.c | 23 ++++++++++++++++++++++- 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/include/astnodes.h b/include/astnodes.h index 3b76bd00..66deb9a8 100644 --- a/include/astnodes.h +++ b/include/astnodes.h @@ -260,6 +260,8 @@ typedef enum AstFlags { Ast_Flag_Symbol_Invisible = BH_BIT(18), Ast_Flag_Header_Check_No_Error = BH_BIT(19), + + Ast_Flag_Decl_Followed_By_Init = BH_BIT(20), } AstFlags; typedef enum UnaryOp { diff --git a/src/checker.c b/src/checker.c index 72d2350c..20cc4723 100644 --- a/src/checker.c +++ b/src/checker.c @@ -1911,6 +1911,13 @@ CheckStatus check_statement(AstNode** pstmt) { YIELD(typed_stmt->token->pos, "Waiting for local variable's type."); } + + if (typed_stmt->next != NULL && typed_stmt->next->kind == Ast_Kind_Binary_Op) { + AstBinaryOp *next = (AstBinaryOp *) typed_stmt->next; + if (next->operation == Binary_Op_Assign && next->left == typed_stmt) { + typed_stmt->flags |= Ast_Flag_Decl_Followed_By_Init; + } + } return Check_Success; } diff --git a/src/wasm_emit.c b/src/wasm_emit.c index b7aea1a6..2a9f5b98 100644 --- a/src/wasm_emit.c +++ b/src/wasm_emit.c @@ -439,7 +439,28 @@ EMIT_FUNC(statement, AstNode* stmt) { } EMIT_FUNC(local_allocation, AstTyped* stmt) { - bh_imap_put(&mod->local_map, (u64) stmt, local_allocate(mod->local_alloc, stmt)); + u64 local_idx = local_allocate(mod->local_alloc, stmt); + bh_imap_put(&mod->local_map, (u64) stmt, local_idx); + + if (stmt->kind == Ast_Kind_Local && !(stmt->flags & Ast_Flag_Decl_Followed_By_Init)) { + bh_arr(WasmInstruction) code = *pcode; + if (local_is_wasm_local(stmt)) { + emit_zero_value(mod, &code, onyx_type_to_wasm_type(stmt->type)); + WIL(WI_LOCAL_SET, local_idx); + + } else { + emit_location(mod, &code, stmt); + WID(WI_I32_CONST, 0); + WID(WI_I32_CONST, type_size_of(stmt->type)); + if (context.options->use_post_mvp_features) { + WID(WI_MEMORY_FILL, 0x00); + } else { + emit_intrinsic_memory_fill(mod, &code); + } + } + + *pcode = code; + } bh_arr_push(mod->local_allocations, ((AllocatedSpace) { .depth = bh_arr_length(mod->structured_jump_target), -- 2.25.1