From 122a7be6a24ded04b3e9801e0438a8d2ffc9b1f4 Mon Sep 17 00:00:00 2001 From: MineGame159 Date: Fri, 26 Jan 2024 14:39:28 +0100 Subject: [PATCH] CORE: Zero initialize variables without an initializer --- core/codegen/statements.go | 20 ++++++++++++-------- tests/src/statements.fb | 8 ++++++++ 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/core/codegen/statements.go b/core/codegen/statements.go index 1425777..b8d7d90 100644 --- a/core/codegen/statements.go +++ b/core/codegen/statements.go @@ -25,17 +25,21 @@ func (c *codegen) VisitVar(stmt *ast.Var) { c.scopes.addVariable(stmt.Name, stmt.ActualType, pointer, 0) // Initializer + var initializer ir.Value + if stmt.Value != nil { - initializer := c.implicitCastLoadExpr(stmt.ActualType, stmt.Value) + initializer = c.implicitCastLoadExpr(stmt.ActualType, stmt.Value).v + } else { + initializer = &ir.ZeroInitConst{Typ: c.types.get(stmt.ActualType)} + } - store := c.block.Add(&ir.StoreInst{ - Pointer: pointer.v, - Value: initializer.v, - Align: stmt.ActualType.Align() * 8, - }) + store := c.block.Add(&ir.StoreInst{ + Pointer: pointer.v, + Value: initializer, + Align: stmt.ActualType.Align() * 8, + }) - c.setLocationMeta(store, stmt) - } + c.setLocationMeta(store, stmt) } func (c *codegen) VisitIf(stmt *ast.If) { diff --git a/tests/src/statements.fb b/tests/src/statements.fb index 95b8c08..681e620 100644 --- a/tests/src/statements.fb +++ b/tests/src/statements.fb @@ -1,5 +1,13 @@ namespace Tests.Statements; +#[Test] +func variableZeroInit() bool { + var n i32; + var p *void; + + return n == 0 && p == nil; +} + #[Test] func variableShadowing() bool { var a = 3;