From ccce3d852681bfe60bce92a6766b4f431dd73571 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 31 May 2019 01:36:57 -0400 Subject: no-copy semantics for function forwarding ```zig fn foo() Foo { return bar(); } ``` ```llvm define internal fastcc void @foo(%Foo* nonnull sret) unnamed_addr #2 !dbg !48 { Entry: call fastcc void @bar(%Foo* sret %0), !dbg !52 ret void, !dbg !54 } ``` --- src/analyze.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/analyze.cpp') diff --git a/src/analyze.cpp b/src/analyze.cpp index a62c24460e..24c81d2a3f 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -7278,6 +7278,6 @@ void src_assert(bool ok, AstNode *source_node) { buf_ptr(source_node->owner->data.structure.root_struct->path), (unsigned)source_node->line + 1, (unsigned)source_node->column + 1); } - const char *msg = "assertion failed"; + const char *msg = "assertion failed. This is a bug in the Zig compiler."; stage2_panic(msg, strlen(msg)); } -- cgit v1.2.3 From 52eb34718862928b5d83c58990d5d7a6b07e20e2 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 8 Jun 2019 01:16:19 -0400 Subject: hook up result locs for `try` --- src/all_types.hpp | 2 +- src/analyze.cpp | 2 +- src/ast_render.cpp | 6 +++--- src/ir.cpp | 10 +++++----- src/parser.cpp | 6 +++--- 5 files changed, 13 insertions(+), 13 deletions(-) (limited to 'src/analyze.cpp') diff --git a/src/all_types.hpp b/src/all_types.hpp index df7b8b5493..0061b5999f 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -430,7 +430,7 @@ enum NodeType { NodeTypeVariableDeclaration, NodeTypeTestDecl, NodeTypeBinOpExpr, - NodeTypeUnwrapErrorExpr, + NodeTypeCatchExpr, NodeTypeFloatLiteral, NodeTypeIntLiteral, NodeTypeStringLiteral, diff --git a/src/analyze.cpp b/src/analyze.cpp index 24c81d2a3f..771e11e93f 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -2993,7 +2993,7 @@ void scan_decls(CodeGen *g, ScopeDecls *decls_scope, AstNode *node) { case NodeTypeBlock: case NodeTypeGroupedExpr: case NodeTypeBinOpExpr: - case NodeTypeUnwrapErrorExpr: + case NodeTypeCatchExpr: case NodeTypeFnCallExpr: case NodeTypeArrayAccessExpr: case NodeTypeSliceExpr: diff --git a/src/ast_render.cpp b/src/ast_render.cpp index 95ae216f70..078cd61edd 100644 --- a/src/ast_render.cpp +++ b/src/ast_render.cpp @@ -165,8 +165,8 @@ static const char *node_type_str(NodeType node_type) { return "Parens"; case NodeTypeBinOpExpr: return "BinOpExpr"; - case NodeTypeUnwrapErrorExpr: - return "UnwrapErrorExpr"; + case NodeTypeCatchExpr: + return "CatchExpr"; case NodeTypeFnCallExpr: return "FnCallExpr"; case NodeTypeArrayAccessExpr: @@ -1100,7 +1100,7 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) { fprintf(ar->f, "]"); break; } - case NodeTypeUnwrapErrorExpr: + case NodeTypeCatchExpr: { render_node_ungrouped(ar, node->data.unwrap_err_expr.op1); fprintf(ar->f, " catch "); diff --git a/src/ir.cpp b/src/ir.cpp index 34d3c2fb5b..7f5b7da6e1 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -3383,7 +3383,7 @@ static IrInstruction *ir_gen_async_return(IrBuilder *irb, Scope *scope, AstNode return ir_build_cond_br(irb, scope, node, is_canceled_bool, irb->exec->coro_final_cleanup_block, irb->exec->coro_early_final, is_comptime); } -static IrInstruction *ir_gen_return(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval) { +static IrInstruction *ir_gen_return(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval, ResultLoc *result_loc) { assert(node->type == NodeTypeReturnExpr); ZigFn *fn_entry = exec_fn_entry(irb->exec); @@ -3508,7 +3508,7 @@ static IrInstruction *ir_gen_return(IrBuilder *irb, Scope *scope, AstNode *node, if (lval == LValPtr) return unwrapped_ptr; else - return ir_build_load_ptr(irb, scope, node, unwrapped_ptr); + return ir_expr_wrap(irb, scope, ir_build_load_ptr(irb, scope, node, unwrapped_ptr), result_loc); } } zig_unreachable(); @@ -7083,7 +7083,7 @@ static IrInstruction *ir_gen_slice(IrBuilder *irb, Scope *scope, AstNode *node) static IrInstruction *ir_gen_catch(IrBuilder *irb, Scope *parent_scope, AstNode *node, LVal lval, ResultLoc *result_loc) { - assert(node->type == NodeTypeUnwrapErrorExpr); + assert(node->type == NodeTypeCatchExpr); AstNode *op1_node = node->data.unwrap_err_expr.op1; AstNode *op2_node = node->data.unwrap_err_expr.op2; @@ -7895,7 +7895,7 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop case NodeTypeArrayAccessExpr: return ir_gen_array_access(irb, scope, node, lval, result_loc); case NodeTypeReturnExpr: - return ir_gen_return(irb, scope, node, lval); + return ir_gen_return(irb, scope, node, lval, result_loc); case NodeTypeFieldAccessExpr: { IrInstruction *ptr_instruction = ir_gen_field_access(irb, scope, node); @@ -7968,7 +7968,7 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop return ir_lval_wrap(irb, scope, ir_gen_defer(irb, scope, node), lval, result_loc); case NodeTypeSliceExpr: return ir_lval_wrap(irb, scope, ir_gen_slice(irb, scope, node), lval, result_loc); - case NodeTypeUnwrapErrorExpr: + case NodeTypeCatchExpr: return ir_gen_catch(irb, scope, node, lval, result_loc); case NodeTypeContainerDecl: return ir_lval_wrap(irb, scope, ir_gen_container_decl(irb, scope, node), lval, result_loc); diff --git a/src/parser.cpp b/src/parser.cpp index 3d7bbf7801..43af347563 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -341,7 +341,7 @@ static AstNode *ast_parse_bin_op_expr( op->data.bin_op_expr.op1 = left; op->data.bin_op_expr.op2 = right; break; - case NodeTypeUnwrapErrorExpr: + case NodeTypeCatchExpr: op->data.unwrap_err_expr.op1 = left; op->data.unwrap_err_expr.op2 = right; break; @@ -2377,7 +2377,7 @@ static AstNode *ast_parse_bitwise_op(ParseContext *pc) { Token *catch_token = eat_token_if(pc, TokenIdKeywordCatch); if (catch_token != nullptr) { Token *payload = ast_parse_payload(pc); - AstNode *res = ast_create_node(pc, NodeTypeUnwrapErrorExpr, catch_token); + AstNode *res = ast_create_node(pc, NodeTypeCatchExpr, catch_token); if (payload != nullptr) res->data.unwrap_err_expr.symbol = token_symbol(pc, payload); @@ -2864,7 +2864,7 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont visit_field(&node->data.bin_op_expr.op1, visit, context); visit_field(&node->data.bin_op_expr.op2, visit, context); break; - case NodeTypeUnwrapErrorExpr: + case NodeTypeCatchExpr: visit_field(&node->data.unwrap_err_expr.op1, visit, context); visit_field(&node->data.unwrap_err_expr.symbol, visit, context); visit_field(&node->data.unwrap_err_expr.op2, visit, context); -- cgit v1.2.3 From 771e88951a9af48335abe14e4c44b5c4f5b252de Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Sat, 8 Jun 2019 18:51:31 -0400 Subject: result location mechanism for struct initialization ```zig export fn entry() void { const static = Foo{ .x = 9, .bar = Bar{ .y = 10 }, }; const runtime = foo(true); } fn foo(c: bool) Foo { return Foo{ .x = 12, .bar = if (c) bar1() else bar2(), }; } fn bar1() Bar { return Bar{ .y = 34 }; } fn bar2() Bar { return Bar{ .y = 56 }; } ``` ```llvm @0 = internal unnamed_addr constant %Foo { i32 9, %Bar { i32 10 } }, align 4 @1 = internal unnamed_addr constant %Bar { i32 34 }, align 4 @2 = internal unnamed_addr constant %Bar { i32 56 }, align 4 define void @entry() #2 !dbg !35 { Entry: %runtime = alloca %Foo, align 4 call void @llvm.dbg.declare(metadata %Foo* @0, metadata !39, metadata !DIExpression()), !dbg !50 call fastcc void @foo(%Foo* sret %runtime, i1 true), !dbg !51 call void @llvm.dbg.declare(metadata %Foo* %runtime, metadata !49, metadata !DIExpression()), !dbg !52 ret void, !dbg !53 } define internal fastcc void @foo(%Foo* nonnull sret, i1) unnamed_addr #2 !dbg !54 { Entry: %c = alloca i1, align 1 store i1 %1, i1* %c, align 1 call void @llvm.dbg.declare(metadata i1* %c, metadata !60, metadata !DIExpression()), !dbg !61 %2 = getelementptr inbounds %Foo, %Foo* %0, i32 0, i32 0, !dbg !62 store i32 12, i32* %2, align 4, !dbg !62 %3 = getelementptr inbounds %Foo, %Foo* %0, i32 0, i32 1, !dbg !64 %4 = load i1, i1* %c, align 1, !dbg !65 br i1 %4, label %Then, label %Else, !dbg !65 Then: ; preds = %Entry call fastcc void @bar1(%Bar* sret %3), !dbg !66 br label %EndIf, !dbg !64 Else: ; preds = %Entry call fastcc void @bar2(%Bar* sret %3), !dbg !67 br label %EndIf, !dbg !64 EndIf: ; preds = %Else, %Then ret void, !dbg !68 } define internal fastcc void @bar1(%Bar* nonnull sret) unnamed_addr #2 !dbg !69 { Entry: %1 = bitcast %Bar* %0 to i8*, !dbg !73 call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %1, i8* align 4 bitcast (%Bar* @1 to i8*), i64 4, i1 false), !dbg !73 ret void, !dbg !73 } define internal fastcc void @bar2(%Bar* nonnull sret) unnamed_addr #2 !dbg !75 { Entry: %1 = bitcast %Bar* %0 to i8*, !dbg !76 call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 4 %1, i8* align 4 bitcast (%Bar* @2 to i8*), i64 4, i1 false), !dbg !76 ret void, !dbg !76 } !39 = !DILocalVariable(name: "static", scope: !40, file: !5, line: 2, type: !41) !49 = !DILocalVariable(name: "runtime", scope: !40, file: !5, line: 6, type: !41) ``` --- BRANCH_TODO | 8 +- src/all_types.hpp | 49 ++++++++---- src/analyze.cpp | 6 ++ src/analyze.hpp | 1 + src/codegen.cpp | 73 +++++++++-------- src/ir.cpp | 236 +++++++++++++++++++++++++++++++++++++----------------- src/ir_print.cpp | 40 +++++---- 7 files changed, 270 insertions(+), 143 deletions(-) (limited to 'src/analyze.cpp') diff --git a/BRANCH_TODO b/BRANCH_TODO index fc8a654772..843703e20b 100644 --- a/BRANCH_TODO +++ b/BRANCH_TODO @@ -1,8 +1,8 @@ Scratch pad for stuff to do before merging master ================================================= - * struct initializations - * function call parameters + * array initializations + * union initializations * bitCast look at all the ir_gen_node ir_gen_node_extra calls and make sure result locations are properly propagated @@ -25,7 +25,3 @@ inferred comptime return ir_build_ref(irb, scope, value->source_node, value, false, false); handle if with no else - - - - diff --git a/src/all_types.hpp b/src/all_types.hpp index 0061b5999f..fbd788c9d9 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -1957,6 +1957,7 @@ enum ScopeId { ScopeIdCompTime, ScopeIdCoroPrelude, ScopeIdRuntime, + ScopeIdElide, }; struct Scope { @@ -1970,6 +1971,14 @@ struct Scope { ScopeId id; }; +// This scope, when activated, causes all the instructions in the scope to be omitted +// from the generated code. +struct ScopeElide { + Scope base; + + bool activated; +}; + // This scope comes from global declarations or from // declarations in a container declaration // NodeTypeContainerDecl @@ -2189,7 +2198,6 @@ enum IrInstructionId { IrInstructionIdResizeSlice, IrInstructionIdContainerInitList, IrInstructionIdContainerInitFields, - IrInstructionIdStructInit, IrInstructionIdUnionInit, IrInstructionIdUnreachable, IrInstructionIdTypeOf, @@ -2279,6 +2287,7 @@ enum IrInstructionId { IrInstructionIdPtrType, IrInstructionIdAlignCast, IrInstructionIdImplicitCast, + IrInstructionIdResolveResult, IrInstructionIdOpaqueType, IrInstructionIdSetAlignStack, IrInstructionIdArgType, @@ -2366,6 +2375,7 @@ struct IrInstructionCondBr { IrBasicBlock *then_block; IrBasicBlock *else_block; IrInstruction *is_comptime; + ResultLoc *result_loc; }; struct IrInstructionBr { @@ -2646,20 +2656,6 @@ struct IrInstructionContainerInitFields { IrInstructionContainerInitFieldsField *fields; }; -struct IrInstructionStructInitField { - IrInstruction *value; - TypeStructField *type_struct_field; -}; - -struct IrInstructionStructInit { - IrInstruction base; - - ZigType *struct_type; - size_t field_count; - IrInstructionStructInitField *fields; - LLVMValueRef tmp_ptr; -}; - struct IrInstructionUnionInit { IrInstruction base; @@ -3581,13 +3577,22 @@ struct IrInstructionImplicitCast { IrInstruction *target; }; +struct IrInstructionResolveResult { + IrInstruction base; + + ResultLoc *result_loc; + IrInstruction *ty; +}; + enum ResultLocId { ResultLocIdInvalid, ResultLocIdNone, ResultLocIdVar, + ResultLocIdField, ResultLocIdReturn, ResultLocIdPeer, ResultLocIdPeerParent, + ResultLocIdInstruction, }; struct ResultLoc { @@ -3597,6 +3602,7 @@ struct ResultLoc { IrInstruction *source_instruction; IrInstruction *gen_instruction; // value to store to the result loc ZigType *implicit_elem_type; + ScopeElide *scope_elide; }; struct ResultLocNone { @@ -3609,6 +3615,14 @@ struct ResultLocVar { ZigVar *var; }; +struct ResultLocField { + ResultLoc base; + + ResultLoc *parent; + Buf *name; + IrInstruction *container_type; +}; + struct ResultLocReturn { ResultLoc base; }; @@ -3636,6 +3650,11 @@ struct ResultLocPeer { IrSuspendPosition suspend_pos; }; +// The result location is the source instruction +struct ResultLocInstruction { + ResultLoc base; +}; + static const size_t slice_ptr_index = 0; static const size_t slice_len_index = 1; diff --git a/src/analyze.cpp b/src/analyze.cpp index 771e11e93f..6299ac6699 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -166,6 +166,12 @@ Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstruct return &scope->base; } +ScopeElide *create_elide_scope(CodeGen *g, AstNode *node, Scope *parent) { + ScopeElide *scope = allocate(1); + init_scope(g, &scope->base, ScopeIdElide, node, parent); + return scope; +} + ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeSuspend); ScopeSuspend *scope = allocate(1); diff --git a/src/analyze.hpp b/src/analyze.hpp index 57f1072355..2f3ec663da 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -121,6 +121,7 @@ ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn * Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent); Scope *create_coro_prelude_scope(CodeGen *g, AstNode *node, Scope *parent); Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstruction *is_comptime); +ScopeElide *create_elide_scope(CodeGen *g, AstNode *node, Scope *parent); void init_const_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str); ConstExprValue *create_const_str_lit(CodeGen *g, Buf *str); diff --git a/src/codegen.cpp b/src/codegen.cpp index eecc2239db..4fa13c39a2 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -715,6 +715,7 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) { case ScopeIdCompTime: case ScopeIdCoroPrelude: case ScopeIdRuntime: + case ScopeIdElide: return get_di_scope(g, scope->parent); } zig_unreachable(); @@ -2383,7 +2384,6 @@ static LLVMValueRef ir_render_save_err_ret_addr(CodeGen *g, IrExecutable *execut } static LLVMValueRef ir_render_return(CodeGen *g, IrExecutable *executable, IrInstructionReturn *return_instruction) { - LLVMValueRef value = ir_llvm_value(g, return_instruction->value); ZigType *return_type = return_instruction->value->value.type; if (want_first_arg_sret(g, &g->cur_fn->type_entry->data.fn.fn_type_id)) { @@ -2391,13 +2391,16 @@ static LLVMValueRef ir_render_return(CodeGen *g, IrExecutable *executable, IrIns if (return_instruction->value->value.special != ConstValSpecialRuntime) { // if it's comptime we have to do this but if it's runtime trust that // result location mechanism took care of it. + LLVMValueRef value = ir_llvm_value(g, return_instruction->value); gen_assign_raw(g, g->cur_ret_ptr, get_pointer_to_type(g, return_type, false), value); } LLVMBuildRetVoid(g->builder); } else if (handle_is_ptr(return_type)) { + LLVMValueRef value = ir_llvm_value(g, return_instruction->value); LLVMValueRef by_val_value = gen_load_untyped(g, value, 0, false, ""); LLVMBuildRet(g->builder, by_val_value); } else { + LLVMValueRef value = ir_llvm_value(g, return_instruction->value); LLVMBuildRet(g->builder, value); } return nullptr; @@ -5032,29 +5035,6 @@ static LLVMValueRef ir_render_union_tag(CodeGen *g, IrExecutable *executable, Ir return get_handle_value(g, tag_field_ptr, tag_type, ptr_type); } -static LLVMValueRef ir_render_struct_init(CodeGen *g, IrExecutable *executable, IrInstructionStructInit *instruction) { - for (size_t i = 0; i < instruction->field_count; i += 1) { - IrInstructionStructInitField *field = &instruction->fields[i]; - TypeStructField *type_struct_field = field->type_struct_field; - if (!type_has_bits(type_struct_field->type_entry)) - continue; - - LLVMValueRef field_ptr = LLVMBuildStructGEP(g->builder, instruction->tmp_ptr, - (unsigned)type_struct_field->gen_index, ""); - LLVMValueRef value = ir_llvm_value(g, field->value); - - uint32_t field_align_bytes = get_abi_alignment(g, type_struct_field->type_entry); - uint32_t host_int_bytes = get_host_int_bytes(g, instruction->struct_type, type_struct_field); - - ZigType *ptr_type = get_pointer_to_type_extra(g, type_struct_field->type_entry, - false, false, PtrLenSingle, field_align_bytes, - (uint32_t)type_struct_field->bit_offset_in_host, host_int_bytes, false); - - gen_assign_raw(g, field_ptr, ptr_type, value); - } - return instruction->tmp_ptr; -} - static LLVMValueRef ir_render_union_init(CodeGen *g, IrExecutable *executable, IrInstructionUnionInit *instruction) { TypeUnionField *type_union_field = instruction->field; @@ -5531,10 +5511,6 @@ static void set_debug_location(CodeGen *g, IrInstruction *instruction) { } static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, IrInstruction *instruction) { - if (!g->strip_debug_symbols) { - set_debug_location(g, instruction); - } - switch (instruction->id) { case IrInstructionIdInvalid: case IrInstructionIdConst: @@ -5609,6 +5585,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, case IrInstructionIdEndExpr: case IrInstructionIdAllocaGen: case IrInstructionIdImplicitCast: + case IrInstructionIdResolveResult: zig_unreachable(); case IrInstructionIdDeclVarGen: @@ -5705,8 +5682,6 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, return ir_render_err_wrap_payload(g, executable, (IrInstructionErrWrapPayload *)instruction); case IrInstructionIdUnionTag: return ir_render_union_tag(g, executable, (IrInstructionUnionTag *)instruction); - case IrInstructionIdStructInit: - return ir_render_struct_init(g, executable, (IrInstructionStructInit *)instruction); case IrInstructionIdUnionInit: return ir_render_union_init(g, executable, (IrInstructionUnionInit *)instruction); case IrInstructionIdPtrCastGen: @@ -5791,6 +5766,34 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, zig_unreachable(); } +static bool scope_is_elided(Scope *scope) { + for (;;) { + switch (scope->id) { + case ScopeIdDecls: + case ScopeIdCompTime: + case ScopeIdCImport: + zig_unreachable(); + case ScopeIdElide: + if (reinterpret_cast(scope)->activated) + return true; + // fallthrough + case ScopeIdBlock: + case ScopeIdDefer: + case ScopeIdDeferExpr: + case ScopeIdVarDecl: + case ScopeIdLoop: + case ScopeIdSuspend: + case ScopeIdCoroPrelude: + case ScopeIdRuntime: + scope = scope->parent; + continue; + case ScopeIdFnDef: + return false; + } + zig_unreachable(); + } +} + static void ir_render(CodeGen *g, ZigFn *fn_entry) { assert(fn_entry); @@ -5806,7 +5809,12 @@ static void ir_render(CodeGen *g, ZigFn *fn_entry) { if (instruction->ref_count == 0 && !ir_has_side_effects(instruction)) continue; - instruction->llvm_value = ir_render_instruction(g, executable, instruction); + if (!scope_is_elided(instruction->scope)) { + if (!g->strip_debug_symbols) { + set_debug_location(g, instruction); + } + instruction->llvm_value = ir_render_instruction(g, executable, instruction); + } } current_block->llvm_exit_block = LLVMGetInsertBlock(g->builder); } @@ -6891,9 +6899,6 @@ static void do_code_gen(CodeGen *g) { } else if (instruction->id == IrInstructionIdContainerInitList) { IrInstructionContainerInitList *container_init_list_instruction = (IrInstructionContainerInitList *)instruction; slot = &container_init_list_instruction->tmp_ptr; - } else if (instruction->id == IrInstructionIdStructInit) { - IrInstructionStructInit *struct_init_instruction = (IrInstructionStructInit *)instruction; - slot = &struct_init_instruction->tmp_ptr; } else if (instruction->id == IrInstructionIdUnionInit) { IrInstructionUnionInit *union_init_instruction = (IrInstructionUnionInit *)instruction; slot = &union_init_instruction->tmp_ptr; diff --git a/src/ir.cpp b/src/ir.cpp index 7f5b7da6e1..d34630554c 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -616,10 +616,6 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionRef *) { return IrInstructionIdRef; } -static constexpr IrInstructionId ir_instruction_id(IrInstructionStructInit *) { - return IrInstructionIdStructInit; -} - static constexpr IrInstructionId ir_instruction_id(IrInstructionUnionInit *) { return IrInstructionIdUnionInit; } @@ -888,6 +884,10 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionImplicitCast *) return IrInstructionIdImplicitCast; } +static constexpr IrInstructionId ir_instruction_id(IrInstructionResolveResult *) { + return IrInstructionIdResolveResult; +} + static constexpr IrInstructionId ir_instruction_id(IrInstructionOpaqueType *) { return IrInstructionIdOpaqueType; } @@ -1517,20 +1517,6 @@ static IrInstruction *ir_build_container_init_fields(IrBuilder *irb, Scope *scop return &container_init_fields_instruction->base; } -static IrInstruction *ir_build_struct_init(IrBuilder *irb, Scope *scope, AstNode *source_node, - ZigType *struct_type, size_t field_count, IrInstructionStructInitField *fields) -{ - IrInstructionStructInit *struct_init_instruction = ir_build_instruction(irb, scope, source_node); - struct_init_instruction->struct_type = struct_type; - struct_init_instruction->field_count = field_count; - struct_init_instruction->fields = fields; - - for (size_t i = 0; i < field_count; i += 1) - ir_ref_instruction(fields[i].value, irb->current_basic_block); - - return &struct_init_instruction->base; -} - static IrInstruction *ir_build_union_init(IrBuilder *irb, Scope *scope, AstNode *source_node, ZigType *union_type, TypeUnionField *field, IrInstruction *init_value) { @@ -2764,6 +2750,18 @@ static IrInstruction *ir_build_implicit_cast(IrBuilder *irb, Scope *scope, AstNo return &instruction->base; } +static IrInstruction *ir_build_resolve_result(IrBuilder *irb, Scope *scope, AstNode *source_node, + ResultLoc *result_loc, IrInstruction *ty) +{ + IrInstructionResolveResult *instruction = ir_build_instruction(irb, scope, source_node); + instruction->result_loc = result_loc; + instruction->ty = ty; + + ir_ref_instruction(ty, irb->current_basic_block); + + return &instruction->base; +} + static IrInstruction *ir_build_opaque_type(IrBuilder *irb, Scope *scope, AstNode *source_node) { IrInstructionOpaqueType *instruction = ir_build_instruction(irb, scope, source_node); @@ -3220,6 +3218,7 @@ static void ir_count_defers(IrBuilder *irb, Scope *inner_scope, Scope *outer_sco case ScopeIdSuspend: case ScopeIdCompTime: case ScopeIdRuntime: + case ScopeIdElide: scope = scope->parent; continue; case ScopeIdDeferExpr: @@ -3276,6 +3275,7 @@ static bool ir_gen_defers_for_block(IrBuilder *irb, Scope *inner_scope, Scope *o case ScopeIdSuspend: case ScopeIdCompTime: case ScopeIdRuntime: + case ScopeIdElide: scope = scope->parent; continue; case ScopeIdDeferExpr: @@ -5549,7 +5549,9 @@ static IrInstruction *ir_gen_prefix_op_expr(IrBuilder *irb, Scope *scope, AstNod zig_unreachable(); } -static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, AstNode *node) { +static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, AstNode *node, LVal lval, + ResultLoc *result_loc) +{ assert(node->type == NodeTypeContainerInitExpr); AstNodeContainerInitExpr *container_init_expr = &node->data.container_init_expr; @@ -5559,39 +5561,61 @@ static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, A if (container_type == irb->codegen->invalid_instruction) return container_type; - if (kind == ContainerInitKindStruct) { - size_t field_count = container_init_expr->entries.length; - IrInstructionContainerInitFieldsField *fields = allocate(field_count); - for (size_t i = 0; i < field_count; i += 1) { - AstNode *entry_node = container_init_expr->entries.at(i); - assert(entry_node->type == NodeTypeStructValueField); - - Buf *name = entry_node->data.struct_val_field.name; - AstNode *expr_node = entry_node->data.struct_val_field.expr; - IrInstruction *expr_value = ir_gen_node(irb, expr_node, scope); - if (expr_value == irb->codegen->invalid_instruction) - return expr_value; - - fields[i].name = name; - fields[i].value = expr_value; - fields[i].source_node = entry_node; - } - return ir_build_container_init_fields(irb, scope, node, container_type, field_count, fields); - } else if (kind == ContainerInitKindArray) { - size_t item_count = container_init_expr->entries.length; - IrInstruction **values = allocate(item_count); - for (size_t i = 0; i < item_count; i += 1) { - AstNode *expr_node = container_init_expr->entries.at(i); - IrInstruction *expr_value = ir_gen_node(irb, expr_node, scope); - if (expr_value == irb->codegen->invalid_instruction) - return expr_value; - - values[i] = expr_value; - } - return ir_build_container_init_list(irb, scope, node, container_type, item_count, values); - } else { - zig_unreachable(); + switch (kind) { + case ContainerInitKindStruct: { + src_assert(result_loc->scope_elide == nullptr, node); + result_loc->scope_elide = create_elide_scope(irb->codegen, node, scope); + size_t field_count = container_init_expr->entries.length; + IrInstructionContainerInitFieldsField *fields = allocate(field_count); + for (size_t i = 0; i < field_count; i += 1) { + AstNode *entry_node = container_init_expr->entries.at(i); + assert(entry_node->type == NodeTypeStructValueField); + + Buf *name = entry_node->data.struct_val_field.name; + AstNode *expr_node = entry_node->data.struct_val_field.expr; + + ResultLoc *child_result_loc = nullptr; + if (result_loc != nullptr) { + IrInstruction *container_ptr = ir_build_resolve_result(irb, &result_loc->scope_elide->base, + expr_node, result_loc, container_type); + IrInstruction *field_ptr = ir_build_field_ptr(irb, &result_loc->scope_elide->base, expr_node, + container_ptr, name); + ResultLocInstruction *result_loc_inst = allocate(1); + result_loc_inst->base.id = ResultLocIdInstruction; + result_loc_inst->base.source_instruction = field_ptr; + ir_ref_instruction(field_ptr, irb->current_basic_block); + child_result_loc = &result_loc_inst->base; + } + + IrInstruction *expr_value = ir_gen_node_extra(irb, expr_node, &result_loc->scope_elide->base, + LValNone, child_result_loc); + if (expr_value == irb->codegen->invalid_instruction) + return expr_value; + + fields[i].name = name; + fields[i].value = expr_value; + fields[i].source_node = entry_node; + } + IrInstruction *init_fields = ir_build_container_init_fields(irb, scope, node, container_type, field_count, fields); + + return ir_lval_wrap(irb, scope, init_fields, lval, result_loc); + } + case ContainerInitKindArray: { + size_t item_count = container_init_expr->entries.length; + IrInstruction **values = allocate(item_count); + for (size_t i = 0; i < item_count; i += 1) { + AstNode *expr_node = container_init_expr->entries.at(i); + IrInstruction *expr_value = ir_gen_node(irb, expr_node, scope); + if (expr_value == irb->codegen->invalid_instruction) + return expr_value; + + values[i] = expr_value; + } + IrInstruction *init_list = ir_build_container_init_list(irb, scope, node, container_type, item_count, values); + return ir_lval_wrap(irb, scope, init_list, lval, result_loc); + } } + zig_unreachable(); } static ResultLocVar *create_var_result_loc(IrInstruction *alloca, ZigVar *var) { @@ -7885,7 +7909,7 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop case NodeTypePrefixOpExpr: return ir_gen_prefix_op_expr(irb, scope, node, lval, result_loc); case NodeTypeContainerInitExpr: - return ir_lval_wrap(irb, scope, ir_gen_container_init_expr(irb, scope, node), lval, result_loc); + return ir_gen_container_init_expr(irb, scope, node, lval, result_loc); case NodeTypeVariableDeclaration: return ir_lval_wrap(irb, scope, ir_gen_var_decl(irb, scope, node), lval, result_loc); case NodeTypeWhileExpr: @@ -14468,7 +14492,9 @@ static IrInstruction *ir_analyze_alloca(IrAnalyze *ira, IrInstruction *source_in return &result->base; } -static ZigType *ir_result_loc_expected_type(IrAnalyze *ira, ResultLoc *result_loc) { +static ZigType *ir_result_loc_expected_type(IrAnalyze *ira, IrInstruction *suspend_source_instr, + ResultLoc *result_loc) +{ switch (result_loc->id) { case ResultLocIdInvalid: case ResultLocIdPeerParent: @@ -14476,6 +14502,30 @@ static ZigType *ir_result_loc_expected_type(IrAnalyze *ira, ResultLoc *result_lo case ResultLocIdNone: case ResultLocIdVar: return nullptr; + case ResultLocIdInstruction: + return result_loc->source_instruction->child->value.type; + case ResultLocIdField: { + if (result_loc->resolved_loc != nullptr) { + ZigType *ptr_type = result_loc->resolved_loc->value.type; + assert(ptr_type->id == ZigTypeIdPointer); + return ptr_type->data.pointer.child_type; + } + ResultLocField *result_loc_field = reinterpret_cast(result_loc); + ZigType *container_type = ir_resolve_type(ira, result_loc_field->container_type->child); + if (type_is_invalid(container_type)) + return ira->codegen->builtin_types.entry_invalid; + if (container_type->id == ZigTypeIdStruct) { + TypeStructField *field = find_struct_type_field(container_type, result_loc_field->name); + if (field == nullptr) { + return ira->codegen->builtin_types.entry_invalid; + } + return field->type_entry; + } else if (container_type->id == ZigTypeIdUnion) { + zig_panic("TODO"); + } else { + zig_unreachable(); + } + } case ResultLocIdReturn: return ira->explicit_return_type; case ResultLocIdPeer: @@ -14491,7 +14541,10 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s ResultLoc *result_loc, ZigType *value_type, IrInstruction *value) { if (result_loc->resolved_loc != nullptr) { - return result_loc->resolved_loc; + // allow to redo the result location if the value is known and comptime and the previous one isn't + if (value == nullptr || !instr_is_comptime(value) || instr_is_comptime(result_loc->resolved_loc)) { + return result_loc->resolved_loc; + } } result_loc->gen_instruction = value; result_loc->implicit_elem_type = value_type; @@ -14524,7 +14577,7 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s return ira->codegen->invalid_instruction; bool is_comptime = force_comptime || (value != nullptr && value->value.special != ConstValSpecialRuntime && result_loc_var->var->gen_is_const); - if (alloca_src->base.child == nullptr) { + if (alloca_src->base.child == nullptr || is_comptime) { uint32_t align = 0; if (alloca_src->align != nullptr && !ir_resolve_align(ira, alloca_src->align->child, &align)) { return ira->codegen->invalid_instruction; @@ -14539,12 +14592,40 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s alloca_gen = ir_analyze_alloca(ira, result_loc->source_instruction, value_type, align, alloca_src->name_hint, force_comptime); } + if (alloca_src->base.child != nullptr) { + alloca_src->base.child->ref_count = 0; + } alloca_src->base.child = alloca_gen; } result_loc->written = true; result_loc->resolved_loc = is_comptime ? nullptr : alloca_src->base.child; return result_loc->resolved_loc; } + case ResultLocIdInstruction: { + result_loc->written = true; + result_loc->resolved_loc = result_loc->source_instruction->child; + return result_loc->resolved_loc; + } + case ResultLocIdField: { + ResultLocField *result_loc_field = reinterpret_cast(result_loc); + + ZigType *container_type = ir_resolve_type(ira, result_loc_field->container_type->child); + if (type_is_invalid(container_type)) + return ira->codegen->invalid_instruction; + + IrInstruction *parent_result_loc = ir_resolve_result(ira, suspend_source_instr, + result_loc_field->parent, container_type, nullptr); + if (parent_result_loc == nullptr || type_is_invalid(parent_result_loc->value.type) || + parent_result_loc->value.type->id == ZigTypeIdUnreachable) + { + return parent_result_loc; + } + + result_loc->written = true; + result_loc->resolved_loc = ir_analyze_container_field_ptr(ira, result_loc_field->name, + suspend_source_instr, parent_result_loc, container_type); + return result_loc->resolved_loc; + } case ResultLocIdReturn: { bool is_comptime = value != nullptr && value->value.special != ConstValSpecialRuntime; if (is_comptime) return nullptr; @@ -14593,7 +14674,7 @@ static IrInstruction *ir_resolve_result(IrAnalyze *ira, IrInstruction *suspend_s ira->resume_stack.append(opposite_peer->suspend_pos); } } - ZigType *expected_type = ir_result_loc_expected_type(ira, peer_parent->parent); + ZigType *expected_type = ir_result_loc_expected_type(ira, suspend_source_instr, peer_parent->parent); peer_parent->resolved_type = ir_resolve_peer_types(ira, peer_parent->base.source_instruction->source_node, expected_type, instructions, peer_parent->peer_count); @@ -14626,6 +14707,12 @@ static IrInstruction *ir_analyze_instruction_implicit_cast(IrAnalyze *ira, IrIns return ir_implicit_cast(ira, target, dest_type); } +static IrInstruction *ir_analyze_instruction_resolve_result(IrAnalyze *ira, IrInstructionResolveResult *instruction) { + ZigType *ty = ir_resolve_type(ira, instruction->ty->child); + if (type_is_invalid(ty)) + return ira->codegen->invalid_instruction; + return ir_resolve_result(ira, &instruction->base, instruction->result_loc, ty, nullptr); +} static IrInstruction *ir_analyze_async_call(IrAnalyze *ira, IrInstructionCallSrc *call_instruction, ZigFn *fn_entry, ZigType *fn_type, IrInstruction *fn_ref, IrInstruction **casted_args, size_t arg_count, @@ -18330,8 +18417,6 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc AstNode **field_assign_nodes = allocate(actual_field_count); - IrInstructionStructInitField *new_fields = allocate(actual_field_count); - bool is_comptime = ir_should_inline(ira->new_irb.exec, instruction->scope) || type_requires_comptime(ira->codegen, container_type) == ReqCompTimeYes; @@ -18371,9 +18456,6 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc } field_assign_nodes[field_index] = field->source_node; - new_fields[field_index].value = casted_field_value; - new_fields[field_index].type_struct_field = type_field; - if (const_val.special == ConstValSpecialStatic) { if (is_comptime || casted_field_value->value.special != ConstValSpecialRuntime) { ConstExprValue *field_val = ir_resolve_const(ira, casted_field_value, UndefOk); @@ -18416,9 +18498,6 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc IrInstruction *runtime_inst = ir_const(ira, instruction, field->init_val->type); copy_const_val(&runtime_inst->value, field->init_val, true); - new_fields[i].value = runtime_inst; - new_fields[i].type_struct_field = field; - if (const_val.special == ConstValSpecialStatic) { copy_const_val(&const_val.data.x_struct.fields[i], field->init_val, true); } @@ -18451,12 +18530,11 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc return ira->codegen->invalid_instruction; } - IrInstruction *new_instruction = ir_build_struct_init(&ira->new_irb, - instruction->scope, instruction->source_node, - container_type, actual_field_count, new_fields); - new_instruction->value.type = container_type; - ir_add_alloca(ira, new_instruction, container_type); - return new_instruction; + // this instruction should not get to codegen + IrInstruction *result = ir_const(ira, instruction, container_type); + // this is how we signal to EndExpr the value is not comptime known + result->value.special = ConstValSpecialRuntime; + return result; } static IrInstruction *ir_analyze_instruction_container_init_list(IrAnalyze *ira, @@ -23794,7 +23872,18 @@ static IrInstruction *ir_analyze_instruction_end_expr(IrAnalyze *ira, IrInstruct if (type_is_invalid(value->value.type)) return ira->codegen->invalid_instruction; - if (!instruction->result_loc->written) { + bool want_resolve_result = instruction->result_loc->written; + if (instruction->result_loc->written) { + if (instruction->result_loc->scope_elide != nullptr && instr_is_comptime(value)) { + want_resolve_result = true; + instruction->result_loc->scope_elide->activated = true; + } else { + want_resolve_result = false; + } + } else { + want_resolve_result = true; + } + if (want_resolve_result) { IrInstruction *result_loc = ir_resolve_result(ira, &instruction->base, instruction->result_loc, value->value.type, value); if (result_loc != nullptr) { @@ -23815,7 +23904,6 @@ static IrInstruction *ir_analyze_instruction_base(IrAnalyze *ira, IrInstruction switch (instruction->id) { case IrInstructionIdInvalid: case IrInstructionIdWidenOrShorten: - case IrInstructionIdStructInit: case IrInstructionIdUnionInit: case IrInstructionIdStructFieldPtr: case IrInstructionIdUnionFieldPtr: @@ -24036,6 +24124,8 @@ static IrInstruction *ir_analyze_instruction_base(IrAnalyze *ira, IrInstruction return ir_analyze_instruction_align_cast(ira, (IrInstructionAlignCast *)instruction); case IrInstructionIdImplicitCast: return ir_analyze_instruction_implicit_cast(ira, (IrInstructionImplicitCast *)instruction); + case IrInstructionIdResolveResult: + return ir_analyze_instruction_resolve_result(ira, (IrInstructionResolveResult *)instruction); case IrInstructionIdOpaqueType: return ir_analyze_instruction_opaque_type(ira, (IrInstructionOpaqueType *)instruction); case IrInstructionIdSetAlignStack: @@ -24260,7 +24350,6 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdCast: case IrInstructionIdContainerInitList: case IrInstructionIdContainerInitFields: - case IrInstructionIdStructInit: case IrInstructionIdUnionInit: case IrInstructionIdFieldPtr: case IrInstructionIdElemPtr: @@ -24326,6 +24415,7 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdTypeId: case IrInstructionIdAlignCast: case IrInstructionIdImplicitCast: + case IrInstructionIdResolveResult: case IrInstructionIdOpaqueType: case IrInstructionIdArgType: case IrInstructionIdTagType: diff --git a/src/ir_print.cpp b/src/ir_print.cpp index 7d56b157d5..0f80a9b9e3 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -207,6 +207,18 @@ static void ir_print_result_loc_var(IrPrint *irp, ResultLocVar *result_loc_var) fprintf(irp->f, ")"); } +static void ir_print_result_loc_instruction(IrPrint *irp, ResultLocInstruction *result_loc_inst) { + fprintf(irp->f, "inst("); + ir_print_other_instruction(irp, result_loc_inst->base.source_instruction); + fprintf(irp->f, ")"); +} + +static void ir_print_result_loc_field(IrPrint *irp, ResultLocField *result_loc_field) { + fprintf(irp->f, "field(name=%s,type=", buf_ptr(result_loc_field->name)); + ir_print_other_instruction(irp, result_loc_field->container_type); + fprintf(irp->f, ")"); +} + static void ir_print_result_loc_peer(IrPrint *irp, ResultLocPeer *result_loc_peer) { fprintf(irp->f, "peer(next="); ir_print_other_block(irp, result_loc_peer->next_bb); @@ -225,6 +237,10 @@ static void ir_print_result_loc(IrPrint *irp, ResultLoc *result_loc) { return; case ResultLocIdVar: return ir_print_result_loc_var(irp, (ResultLocVar *)result_loc); + case ResultLocIdInstruction: + return ir_print_result_loc_instruction(irp, (ResultLocInstruction *)result_loc); + case ResultLocIdField: + return ir_print_result_loc_field(irp, (ResultLocField *)result_loc); case ResultLocIdPeer: return ir_print_result_loc_peer(irp, (ResultLocPeer *)result_loc); case ResultLocIdPeerParent: @@ -352,18 +368,6 @@ static void ir_print_container_init_fields(IrPrint *irp, IrInstructionContainerI fprintf(irp->f, "} // container init"); } -static void ir_print_struct_init(IrPrint *irp, IrInstructionStructInit *instruction) { - fprintf(irp->f, "%s {", buf_ptr(&instruction->struct_type->name)); - for (size_t i = 0; i < instruction->field_count; i += 1) { - IrInstructionStructInitField *field = &instruction->fields[i]; - Buf *field_name = field->type_struct_field->name; - const char *comma = (i == 0) ? "" : ", "; - fprintf(irp->f, "%s.%s = ", comma, buf_ptr(field_name)); - ir_print_other_instruction(irp, field->value); - } - fprintf(irp->f, "} // struct init"); -} - static void ir_print_union_init(IrPrint *irp, IrInstructionUnionInit *instruction) { Buf *field_name = instruction->field->enum_field->name; @@ -1265,6 +1269,12 @@ static void ir_print_implicit_cast(IrPrint *irp, IrInstructionImplicitCast *inst fprintf(irp->f, ")"); } +static void ir_print_resolve_result(IrPrint *irp, IrInstructionResolveResult *instruction) { + fprintf(irp->f, "ResolveResult("); + ir_print_result_loc(irp, instruction->result_loc); + fprintf(irp->f, ")"); +} + static void ir_print_opaque_type(IrPrint *irp, IrInstructionOpaqueType *instruction) { fprintf(irp->f, "@OpaqueType()"); } @@ -1588,9 +1598,6 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdContainerInitFields: ir_print_container_init_fields(irp, (IrInstructionContainerInitFields *)instruction); break; - case IrInstructionIdStructInit: - ir_print_struct_init(irp, (IrInstructionStructInit *)instruction); - break; case IrInstructionIdUnionInit: ir_print_union_init(irp, (IrInstructionUnionInit *)instruction); break; @@ -1900,6 +1907,9 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { case IrInstructionIdImplicitCast: ir_print_implicit_cast(irp, (IrInstructionImplicitCast *)instruction); break; + case IrInstructionIdResolveResult: + ir_print_resolve_result(irp, (IrInstructionResolveResult *)instruction); + break; case IrInstructionIdOpaqueType: ir_print_opaque_type(irp, (IrInstructionOpaqueType *)instruction); break; -- cgit v1.2.3 From 7411a88d5f8109ced238cf14205ae36575f02f21 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 11 Jun 2019 00:27:10 -0400 Subject: fix comptime function calls --- BRANCH_TODO | 4 ++-- src/analyze.cpp | 28 ++++++++++++++++++++++++++++ src/analyze.hpp | 1 + src/codegen.cpp | 28 ---------------------------- src/ir.cpp | 2 ++ 5 files changed, 33 insertions(+), 30 deletions(-) (limited to 'src/analyze.cpp') diff --git a/BRANCH_TODO b/BRANCH_TODO index f730eb64f5..854b2c0ee7 100644 --- a/BRANCH_TODO +++ b/BRANCH_TODO @@ -1,7 +1,7 @@ Scratch pad for stuff to do before merging master ================================================= +uncomment all the behavior tests + look at all the ir_gen_node ir_gen_node_extra calls and make sure result locations are properly propagated return ir_gen_comptime(irb, scope, node, lval); - -comptime expressions diff --git a/src/analyze.cpp b/src/analyze.cpp index 0168dad6ea..beaa9f1486 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -7293,3 +7293,31 @@ void src_assert(bool ok, AstNode *source_node) { const char *msg = "assertion failed. This is a bug in the Zig compiler."; stage2_panic(msg, strlen(msg)); } + +bool scope_is_elided(Scope *scope) { + for (;;) { + switch (scope->id) { + case ScopeIdElide: + if (reinterpret_cast(scope)->activated) + return true; + // fallthrough + case ScopeIdBlock: + case ScopeIdDefer: + case ScopeIdDeferExpr: + case ScopeIdVarDecl: + case ScopeIdLoop: + case ScopeIdSuspend: + case ScopeIdCoroPrelude: + case ScopeIdRuntime: + scope = scope->parent; + continue; + case ScopeIdFnDef: + case ScopeIdCompTime: + case ScopeIdDecls: + case ScopeIdCImport: + return false; + } + zig_unreachable(); + } +} + diff --git a/src/analyze.hpp b/src/analyze.hpp index 2f3ec663da..2c5250d7e9 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -253,5 +253,6 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa void src_assert(bool ok, AstNode *source_node); bool is_container(ZigType *type_entry); ConstExprValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *type_entry, Buf *type_name); +bool scope_is_elided(Scope *scope); #endif diff --git a/src/codegen.cpp b/src/codegen.cpp index a75ef29169..7ee299aab7 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -5709,34 +5709,6 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable, zig_unreachable(); } -static bool scope_is_elided(Scope *scope) { - for (;;) { - switch (scope->id) { - case ScopeIdDecls: - case ScopeIdCompTime: - case ScopeIdCImport: - zig_unreachable(); - case ScopeIdElide: - if (reinterpret_cast(scope)->activated) - return true; - // fallthrough - case ScopeIdBlock: - case ScopeIdDefer: - case ScopeIdDeferExpr: - case ScopeIdVarDecl: - case ScopeIdLoop: - case ScopeIdSuspend: - case ScopeIdCoroPrelude: - case ScopeIdRuntime: - scope = scope->parent; - continue; - case ScopeIdFnDef: - return false; - } - zig_unreachable(); - } -} - static void ir_render(CodeGen *g, ZigFn *fn_entry) { assert(fn_entry); diff --git a/src/ir.cpp b/src/ir.cpp index 07df62fd02..1ea509745e 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -8503,6 +8503,8 @@ static ConstExprValue *ir_exec_const_result(CodeGen *codegen, IrExecutable *exec IrBasicBlock *bb = exec->basic_block_list.at(0); for (size_t i = 0; i < bb->instruction_list.length; i += 1) { IrInstruction *instruction = bb->instruction_list.at(i); + if (scope_is_elided(instruction->scope)) + continue; if (instruction->id == IrInstructionIdReturn) { IrInstructionReturn *ret_inst = (IrInstructionReturn *)instruction; IrInstruction *value = ret_inst->value; -- cgit v1.2.3 From b025193de5b951734e5108e4762e5dc40359431b Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Mon, 17 Jun 2019 13:31:19 -0400 Subject: inferred comptime values rather than elided scopes because of this example: ```zig export fn entry(b: bool) usize { var runtime = [1]i32{3}; comptime var i: usize = 0; inline while (i < 2) : (i += 1) { const result = if (i == 0) [1]i32{2} else runtime; } comptime { return i; } } ``` The problem is that the concept of "resetting" a result location, introduced in the previous commit, cannot handle elision scopes. This concept is inherently broken with inline loops. --- src/all_types.hpp | 14 +- src/analyze.cpp | 35 +---- src/analyze.hpp | 2 - src/codegen.cpp | 9 +- src/ir.cpp | 383 ++++++++++++++++++++++++++++-------------------------- 5 files changed, 208 insertions(+), 235 deletions(-) (limited to 'src/analyze.cpp') diff --git a/src/all_types.hpp b/src/all_types.hpp index 49b71e1eed..f63d6a902b 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -203,6 +203,9 @@ enum ConstPtrMut { // The pointer points to memory that is known only at runtime. // For example it may point to the initializer value of a variable. ConstPtrMutRuntimeVar, + // The pointer points to memory for which it must be inferred whether the + // value is comptime known or not. + ConstPtrMutInfer, }; struct ConstPtrValue { @@ -1957,7 +1960,6 @@ enum ScopeId { ScopeIdCompTime, ScopeIdCoroPrelude, ScopeIdRuntime, - ScopeIdElide, }; struct Scope { @@ -1971,14 +1973,6 @@ struct Scope { ScopeId id; }; -// This scope, when activated, causes all the instructions in the scope to be omitted -// from the generated code. -struct ScopeElide { - Scope base; - - bool activated; -}; - // This scope comes from global declarations or from // declarations in a container declaration // NodeTypeContainerDecl @@ -2655,6 +2649,7 @@ struct IrInstructionContainerInitFieldsField { IrInstruction *value; AstNode *source_node; TypeStructField *type_struct_field; + IrInstruction *result_loc; }; struct IrInstructionContainerInitFields { @@ -3655,7 +3650,6 @@ struct ResultLoc { IrInstruction *source_instruction; IrInstruction *gen_instruction; // value to store to the result loc ZigType *implicit_elem_type; - ScopeElide *scope_elide; }; struct ResultLocNone { diff --git a/src/analyze.cpp b/src/analyze.cpp index 1f9b1ffbed..b39b1e35ca 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -166,12 +166,6 @@ Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstruct return &scope->base; } -ScopeElide *create_elide_scope(CodeGen *g, AstNode *node, Scope *parent) { - ScopeElide *scope = allocate(1); - init_scope(g, &scope->base, ScopeIdElide, node, parent); - return scope; -} - ScopeSuspend *create_suspend_scope(CodeGen *g, AstNode *node, Scope *parent) { assert(node->type == NodeTypeSuspend); ScopeSuspend *scope = allocate(1); @@ -4187,6 +4181,7 @@ static uint32_t hash_const_val_ptr(ConstExprValue *const_val) { case ConstPtrMutComptimeConst: hash_val += (uint32_t)4214318515; break; + case ConstPtrMutInfer: case ConstPtrMutComptimeVar: hash_val += (uint32_t)1103195694; break; @@ -7286,31 +7281,3 @@ void src_assert(bool ok, AstNode *source_node) { const char *msg = "assertion failed. This is a bug in the Zig compiler."; stage2_panic(msg, strlen(msg)); } - -bool scope_is_elided(Scope *scope) { - for (;;) { - switch (scope->id) { - case ScopeIdElide: - if (reinterpret_cast(scope)->activated) - return true; - // fallthrough - case ScopeIdBlock: - case ScopeIdDefer: - case ScopeIdDeferExpr: - case ScopeIdVarDecl: - case ScopeIdLoop: - case ScopeIdSuspend: - case ScopeIdCoroPrelude: - case ScopeIdRuntime: - scope = scope->parent; - continue; - case ScopeIdFnDef: - case ScopeIdCompTime: - case ScopeIdDecls: - case ScopeIdCImport: - return false; - } - zig_unreachable(); - } -} - diff --git a/src/analyze.hpp b/src/analyze.hpp index c1dd482a7a..8d78ef86e2 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -121,7 +121,6 @@ ScopeFnDef *create_fndef_scope(CodeGen *g, AstNode *node, Scope *parent, ZigFn * Scope *create_comptime_scope(CodeGen *g, AstNode *node, Scope *parent); Scope *create_coro_prelude_scope(CodeGen *g, AstNode *node, Scope *parent); Scope *create_runtime_scope(CodeGen *g, AstNode *node, Scope *parent, IrInstruction *is_comptime); -ScopeElide *create_elide_scope(CodeGen *g, AstNode *node, Scope *parent); void init_const_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str); ConstExprValue *create_const_str_lit(CodeGen *g, Buf *str); @@ -254,6 +253,5 @@ void add_cc_args(CodeGen *g, ZigList &args, const char *out_dep_pa void src_assert(bool ok, AstNode *source_node); bool is_container(ZigType *type_entry); ConstExprValue *analyze_const_value(CodeGen *g, Scope *scope, AstNode *node, ZigType *type_entry, Buf *type_name); -bool scope_is_elided(Scope *scope); #endif diff --git a/src/codegen.cpp b/src/codegen.cpp index 4c212c95ab..547840514a 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -722,7 +722,6 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) { case ScopeIdCompTime: case ScopeIdCoroPrelude: case ScopeIdRuntime: - case ScopeIdElide: return get_di_scope(g, scope->parent); } zig_unreachable(); @@ -5761,12 +5760,10 @@ static void ir_render(CodeGen *g, ZigFn *fn_entry) { if (instruction->ref_count == 0 && !ir_has_side_effects(instruction)) continue; - if (!scope_is_elided(instruction->scope)) { - if (!g->strip_debug_symbols) { - set_debug_location(g, instruction); - } - instruction->llvm_value = ir_render_instruction(g, executable, instruction); + if (!g->strip_debug_symbols) { + set_debug_location(g, instruction); } + instruction->llvm_value = ir_render_instruction(g, executable, instruction); } current_block->llvm_exit_block = LLVMGetInsertBlock(g->builder); } diff --git a/src/ir.cpp b/src/ir.cpp index d48c013caf..32f6b4c22a 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -196,6 +196,8 @@ static IrInstruction *ir_analyze_unwrap_error_payload(IrAnalyze *ira, IrInstruct IrInstruction *base_ptr, bool safety_check_on, bool initializing); static IrInstruction *ir_analyze_unwrap_err_code(IrAnalyze *ira, IrInstruction *source_instr, IrInstruction *base_ptr, bool initializing); +static IrInstruction *ir_analyze_store_ptr(IrAnalyze *ira, IrInstruction *source_instr, + IrInstruction *ptr, IrInstruction *uncasted_value); static ConstExprValue *const_ptr_pointee_unchecked(CodeGen *g, ConstExprValue *const_val) { assert(get_src_ptr_type(const_val->type) != nullptr); @@ -3363,7 +3365,6 @@ static void ir_count_defers(IrBuilder *irb, Scope *inner_scope, Scope *outer_sco case ScopeIdSuspend: case ScopeIdCompTime: case ScopeIdRuntime: - case ScopeIdElide: scope = scope->parent; continue; case ScopeIdDeferExpr: @@ -3420,7 +3421,6 @@ static bool ir_gen_defers_for_block(IrBuilder *irb, Scope *inner_scope, Scope *o case ScopeIdSuspend: case ScopeIdCompTime: case ScopeIdRuntime: - case ScopeIdElide: scope = scope->parent; continue; case ScopeIdDeferExpr: @@ -5758,15 +5758,8 @@ static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, A return irb->codegen->invalid_instruction; } - IrInstruction *container_ptr = nullptr; - if (!ir_should_inline(irb->exec, scope)) { - src_assert(parent_result_loc->scope_elide == nullptr, node); - parent_result_loc->scope_elide = create_elide_scope(irb->codegen, node, scope); - - src_assert(parent_result_loc != nullptr, node); - container_ptr = ir_build_resolve_result(irb, &parent_result_loc->scope_elide->base, - node, parent_result_loc, container_type); - } + IrInstruction *container_ptr = ir_build_resolve_result(irb, scope, node, parent_result_loc, + container_type); size_t field_count = container_init_expr->entries.length; IrInstructionContainerInitFieldsField *fields = allocate(field_count); @@ -5777,27 +5770,22 @@ static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, A Buf *name = entry_node->data.struct_val_field.name; AstNode *expr_node = entry_node->data.struct_val_field.expr; - Scope *val_scope = scope; - ResultLoc *child_result_loc = nullptr; - if (container_ptr != nullptr) { - IrInstruction *field_ptr = ir_build_field_ptr(irb, &parent_result_loc->scope_elide->base, - expr_node, container_ptr, name, true); - ResultLocInstruction *result_loc_inst = allocate(1); - result_loc_inst->base.id = ResultLocIdInstruction; - result_loc_inst->base.source_instruction = field_ptr; - ir_ref_instruction(field_ptr, irb->current_basic_block); - child_result_loc = &result_loc_inst->base; - val_scope = &parent_result_loc->scope_elide->base; - } + IrInstruction *field_ptr = ir_build_field_ptr(irb, scope, expr_node, container_ptr, name, true); + ResultLocInstruction *result_loc_inst = allocate(1); + result_loc_inst->base.id = ResultLocIdInstruction; + result_loc_inst->base.source_instruction = field_ptr; + ir_ref_instruction(field_ptr, irb->current_basic_block); + ir_build_reset_result(irb, scope, expr_node, &result_loc_inst->base); - IrInstruction *expr_value = ir_gen_node_extra(irb, expr_node, val_scope, LValNone, - child_result_loc); + IrInstruction *expr_value = ir_gen_node_extra(irb, expr_node, scope, LValNone, + &result_loc_inst->base); if (expr_value == irb->codegen->invalid_instruction) return expr_value; fields[i].name = name; fields[i].value = expr_value; fields[i].source_node = entry_node; + fields[i].result_loc = field_ptr; } IrInstruction *init_fields = ir_build_container_init_fields(irb, scope, node, container_type, field_count, fields, container_ptr); @@ -5812,36 +5800,23 @@ static IrInstruction *ir_gen_container_init_expr(IrBuilder *irb, Scope *scope, A container_type = ir_build_array_type(irb, scope, node, item_count_inst, elem_type); } - IrInstruction *container_ptr = nullptr; - if (!ir_should_inline(irb->exec, scope)) { - src_assert(parent_result_loc->scope_elide == nullptr, node); - parent_result_loc->scope_elide = create_elide_scope(irb->codegen, node, scope); - - container_ptr = ir_build_resolve_result(irb, &parent_result_loc->scope_elide->base, - node, parent_result_loc, container_type); - } + IrInstruction *container_ptr = ir_build_resolve_result(irb, scope, node, parent_result_loc, + container_type); IrInstruction **values = allocate(item_count); for (size_t i = 0; i < item_count; i += 1) { AstNode *expr_node = container_init_expr->entries.at(i); - ResultLoc *child_result_loc = nullptr; - Scope *val_scope = scope; - if (container_ptr != nullptr) { - IrInstruction *elem_index = ir_build_const_usize(irb, &parent_result_loc->scope_elide->base, - expr_node, i); - IrInstruction *elem_ptr = ir_build_elem_ptr(irb, &parent_result_loc->scope_elide->base, - expr_node, container_ptr, elem_index, false, PtrLenSingle, true); - ResultLocInstruction *result_loc_inst = allocate(1); - result_loc_inst->base.id = ResultLocIdInstruction; - result_loc_inst->base.source_instruction = elem_ptr; - ir_ref_instruction(elem_ptr, irb->current_basic_block); - child_result_loc = &result_loc_inst->base; - val_scope = &parent_result_loc->scope_elide->base; - } + IrInstruction *elem_index = ir_build_const_usize(irb, scope, expr_node, i); + IrInstruction *elem_ptr = ir_build_elem_ptr(irb, scope, expr_node, container_ptr, elem_index, + false, PtrLenSingle, true); + ResultLocInstruction *result_loc_inst = allocate(1); + result_loc_inst->base.id = ResultLocIdInstruction; + result_loc_inst->base.source_instruction = elem_ptr; + ir_ref_instruction(elem_ptr, irb->current_basic_block); - IrInstruction *expr_value = ir_gen_node_extra(irb, expr_node, val_scope, LValNone, - child_result_loc); + IrInstruction *expr_value = ir_gen_node_extra(irb, expr_node, scope, LValNone, + &result_loc_inst->base); if (expr_value == irb->codegen->invalid_instruction) return expr_value; @@ -8651,8 +8626,6 @@ static ConstExprValue *ir_exec_const_result(CodeGen *codegen, IrExecutable *exec IrBasicBlock *bb = exec->basic_block_list.at(0); for (size_t i = 0; i < bb->instruction_list.length; i += 1) { IrInstruction *instruction = bb->instruction_list.at(i); - if (scope_is_elided(instruction->scope)) - continue; if (instruction->id == IrInstructionIdReturn) { IrInstructionReturn *ret_inst = (IrInstructionReturn *)instruction; IrInstruction *value = ret_inst->value; @@ -12745,9 +12718,7 @@ static IrInstruction *ir_get_deref(IrAnalyze *ira, IrInstruction *source_instruc ir_add_error(ira, ptr, buf_sprintf("attempt to dereference undefined value")); return ira->codegen->invalid_instruction; } - if (ptr->value.data.x_ptr.mut == ConstPtrMutComptimeConst || - ptr->value.data.x_ptr.mut == ConstPtrMutComptimeVar) - { + if (ptr->value.data.x_ptr.mut != ConstPtrMutRuntimeVar) { ConstExprValue *pointee = const_ptr_pointee_unchecked(ira->codegen, &ptr->value); if (pointee->special != ConstValSpecialRuntime) { IrInstruction *result = ir_const(ira, source_instruction, child_type); @@ -14487,7 +14458,25 @@ static IrInstruction *ir_analyze_instruction_decl_var(IrAnalyze *ira, } if (init_val != nullptr && init_val->special != ConstValSpecialRuntime) { - if (var->mem_slot_index != SIZE_MAX) { + // Resolve ConstPtrMutInfer + if (var->gen_is_const) { + var_ptr->value.data.x_ptr.mut = ConstPtrMutComptimeConst; + } else if (is_comptime_var) { + var_ptr->value.data.x_ptr.mut = ConstPtrMutComptimeVar; + } else { + // we need a runtime ptr but we have a comptime val. + // since it's a comptime val there are no instructions for it. + // we memcpy the init value here + IrInstruction *deref = ir_get_deref(ira, var_ptr, var_ptr, nullptr); + // If this assertion trips, something is wrong with the IR instructions, because + // we expected the above deref to return a constant value, but it created a runtime + // instruction. + assert(deref->value.special != ConstValSpecialRuntime); + var_ptr->value.special = ConstValSpecialRuntime; + ir_analyze_store_ptr(ira, var_ptr, var_ptr, deref); + } + + if (var_ptr->value.special == ConstValSpecialStatic && var->mem_slot_index != SIZE_MAX) { assert(var->mem_slot_index < ira->exec_context.mem_slot_list.length); ConstExprValue *mem_slot = ira->exec_context.mem_slot_list.at(var->mem_slot_index); copy_const_val(mem_slot, init_val, !is_comptime_var || var->gen_is_const); @@ -14818,9 +14807,9 @@ static IrInstruction *ir_analyze_alloca(IrAnalyze *ira, IrInstruction *source_in pointee->special = ConstValSpecialUndef; IrInstructionAllocaGen *result = ir_create_alloca_gen(ira, source_inst, align, name_hint); - result->base.value.special = force_comptime ? ConstValSpecialStatic : ConstValSpecialRuntime; + result->base.value.special = ConstValSpecialStatic; result->base.value.data.x_ptr.special = ConstPtrSpecialRef; - result->base.value.data.x_ptr.mut = force_comptime ? ConstPtrMutComptimeVar : ConstPtrMutRuntimeVar; + result->base.value.data.x_ptr.mut = force_comptime ? ConstPtrMutComptimeVar : ConstPtrMutInfer; result->base.value.data.x_ptr.data.ref.pointee = pointee; if ((err = type_resolve(ira->codegen, var_type, ResolveStatusZeroBitsKnown))) @@ -15109,7 +15098,10 @@ static IrInstruction *ir_analyze_instruction_resolve_result(IrAnalyze *ira, IrIn ZigType *implicit_elem_type = ir_resolve_type(ira, instruction->ty->child); if (type_is_invalid(implicit_elem_type)) return ira->codegen->invalid_instruction; - return ir_resolve_result(ira, &instruction->base, instruction->result_loc, implicit_elem_type, nullptr); + IrInstruction *result_loc = ir_resolve_result(ira, &instruction->base, instruction->result_loc, implicit_elem_type, nullptr); + if (result_loc != nullptr) + return result_loc; + zig_panic("TODO"); } static void ir_reset_result(ResultLoc *result_loc) { @@ -15431,7 +15423,9 @@ static IrInstruction *ir_analyze_store_ptr(IrAnalyze *ira, IrInstruction *source ir_add_error(ira, source_instr, buf_sprintf("cannot assign to constant")); return ira->codegen->invalid_instruction; } - if (ptr->value.data.x_ptr.mut == ConstPtrMutComptimeVar) { + if (ptr->value.data.x_ptr.mut == ConstPtrMutComptimeVar || + ptr->value.data.x_ptr.mut == ConstPtrMutInfer) + { if (instr_is_comptime(value)) { ConstExprValue *dest_val = const_ptr_pointee(ira, ira->codegen, &ptr->value, source_instr->source_node); if (dest_val == nullptr) @@ -15451,12 +15445,16 @@ static IrInstruction *ir_analyze_store_ptr(IrAnalyze *ira, IrInstruction *source return ir_const_void(ira, source_instr); } } - ir_add_error(ira, source_instr, - buf_sprintf("cannot store runtime value in compile time variable")); - ConstExprValue *dest_val = const_ptr_pointee_unchecked(ira->codegen, &ptr->value); - dest_val->type = ira->codegen->builtin_types.entry_invalid; + if (ptr->value.data.x_ptr.mut == ConstPtrMutInfer) { + ptr->value.special = ConstValSpecialRuntime; + } else { + ir_add_error(ira, source_instr, + buf_sprintf("cannot store runtime value in compile time variable")); + ConstExprValue *dest_val = const_ptr_pointee_unchecked(ira->codegen, &ptr->value); + dest_val->type = ira->codegen->builtin_types.entry_invalid; - return ira->codegen->invalid_instruction; + return ira->codegen->invalid_instruction; + } } } @@ -17091,6 +17089,81 @@ static IrInstruction *ir_analyze_container_member_access_inner(IrAnalyze *ira, return ira->codegen->invalid_instruction; } +static IrInstruction *ir_analyze_struct_field_ptr(IrAnalyze *ira, IrInstruction *source_instr, + TypeStructField *field, IrInstruction *struct_ptr, ZigType *struct_type, bool initializing) +{ + switch (type_has_one_possible_value(ira->codegen, field->type_entry)) { + case OnePossibleValueInvalid: + return ira->codegen->invalid_instruction; + case OnePossibleValueYes: { + IrInstruction *elem = ir_const(ira, source_instr, field->type_entry); + return ir_get_ref(ira, source_instr, elem, false, false); + } + case OnePossibleValueNo: + break; + } + assert(struct_ptr->value.type->id == ZigTypeIdPointer); + bool is_packed = (struct_type->data.structure.layout == ContainerLayoutPacked); + uint32_t align_bytes = is_packed ? 1 : get_abi_alignment(ira->codegen, field->type_entry); + uint32_t ptr_bit_offset = struct_ptr->value.type->data.pointer.bit_offset_in_host; + uint32_t ptr_host_int_bytes = struct_ptr->value.type->data.pointer.host_int_bytes; + uint32_t host_int_bytes_for_result_type = (ptr_host_int_bytes == 0) ? + get_host_int_bytes(ira->codegen, struct_type, field) : ptr_host_int_bytes; + bool is_const = struct_ptr->value.type->data.pointer.is_const; + bool is_volatile = struct_ptr->value.type->data.pointer.is_volatile; + ZigType *ptr_type = get_pointer_to_type_extra(ira->codegen, field->type_entry, + is_const, is_volatile, PtrLenSingle, align_bytes, + (uint32_t)(ptr_bit_offset + field->bit_offset_in_host), + (uint32_t)host_int_bytes_for_result_type, false); + if (instr_is_comptime(struct_ptr)) { + ConstExprValue *ptr_val = ir_resolve_const(ira, struct_ptr, UndefBad); + if (!ptr_val) + return ira->codegen->invalid_instruction; + + if (ptr_val->data.x_ptr.special != ConstPtrSpecialHardCodedAddr) { + ConstExprValue *struct_val = const_ptr_pointee(ira, ira->codegen, ptr_val, source_instr->source_node); + if (struct_val == nullptr) + return ira->codegen->invalid_instruction; + if (type_is_invalid(struct_val->type)) + return ira->codegen->invalid_instruction; + if (struct_val->special == ConstValSpecialUndef && initializing) { + struct_val->data.x_struct.fields = create_const_vals(struct_type->data.structure.src_field_count); + struct_val->special = ConstValSpecialStatic; + for (size_t i = 0; i < struct_type->data.structure.src_field_count; i += 1) { + ConstExprValue *field_val = &struct_val->data.x_struct.fields[i]; + field_val->special = ConstValSpecialUndef; + field_val->type = struct_type->data.structure.fields[i].type_entry; + ConstParent *parent = get_const_val_parent(ira->codegen, field_val); + if (parent != nullptr) { + parent->id = ConstParentIdStruct; + parent->data.p_struct.struct_val = struct_val; + parent->data.p_struct.field_index = i; + } + } + } + IrInstruction *result; + if (ptr_val->data.x_ptr.mut == ConstPtrMutInfer) { + result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, + source_instr->source_node, struct_ptr, field); + result->value.type = ptr_type; + result->value.special = ConstValSpecialStatic; + } else { + result = ir_const(ira, source_instr, ptr_type); + } + ConstExprValue *const_val = &result->value; + const_val->data.x_ptr.special = ConstPtrSpecialBaseStruct; + const_val->data.x_ptr.mut = struct_ptr->value.data.x_ptr.mut; + const_val->data.x_ptr.data.base_struct.struct_val = struct_val; + const_val->data.x_ptr.data.base_struct.field_index = field->src_index; + return result; + } + } + IrInstruction *result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, + struct_ptr, field); + result->value.type = ptr_type; + return result; +} + static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_name, IrInstruction *source_instr, IrInstruction *container_ptr, ZigType *container_type, bool initializing) { @@ -17101,59 +17174,10 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ return ira->codegen->invalid_instruction; assert(container_ptr->value.type->id == ZigTypeIdPointer); - bool is_const = container_ptr->value.type->data.pointer.is_const; - bool is_volatile = container_ptr->value.type->data.pointer.is_volatile; if (bare_type->id == ZigTypeIdStruct) { TypeStructField *field = find_struct_type_field(bare_type, field_name); - if (field) { - switch (type_has_one_possible_value(ira->codegen, field->type_entry)) { - case OnePossibleValueInvalid: - return ira->codegen->invalid_instruction; - case OnePossibleValueYes: { - IrInstruction *elem = ir_const(ira, source_instr, field->type_entry); - return ir_get_ref(ira, source_instr, elem, false, false); - } - case OnePossibleValueNo: - break; - } - bool is_packed = (bare_type->data.structure.layout == ContainerLayoutPacked); - uint32_t align_bytes = is_packed ? 1 : get_abi_alignment(ira->codegen, field->type_entry); - uint32_t ptr_bit_offset = container_ptr->value.type->data.pointer.bit_offset_in_host; - uint32_t ptr_host_int_bytes = container_ptr->value.type->data.pointer.host_int_bytes; - uint32_t host_int_bytes_for_result_type = (ptr_host_int_bytes == 0) ? - get_host_int_bytes(ira->codegen, bare_type, field) : ptr_host_int_bytes; - if (instr_is_comptime(container_ptr)) { - ConstExprValue *ptr_val = ir_resolve_const(ira, container_ptr, UndefBad); - if (!ptr_val) - return ira->codegen->invalid_instruction; - - if (ptr_val->data.x_ptr.special != ConstPtrSpecialHardCodedAddr) { - ConstExprValue *struct_val = const_ptr_pointee(ira, ira->codegen, ptr_val, source_instr->source_node); - if (struct_val == nullptr) - return ira->codegen->invalid_instruction; - if (type_is_invalid(struct_val->type)) - return ira->codegen->invalid_instruction; - ZigType *ptr_type = get_pointer_to_type_extra(ira->codegen, field->type_entry, - is_const, is_volatile, PtrLenSingle, align_bytes, - (uint32_t)(ptr_bit_offset + field->bit_offset_in_host), - (uint32_t)host_int_bytes_for_result_type, false); - IrInstruction *result = ir_const(ira, source_instr, ptr_type); - ConstExprValue *const_val = &result->value; - const_val->data.x_ptr.special = ConstPtrSpecialBaseStruct; - const_val->data.x_ptr.mut = container_ptr->value.data.x_ptr.mut; - const_val->data.x_ptr.data.base_struct.struct_val = struct_val; - const_val->data.x_ptr.data.base_struct.field_index = field->src_index; - return result; - } - } - IrInstruction *result = ir_build_struct_field_ptr(&ira->new_irb, source_instr->scope, source_instr->source_node, - container_ptr, field); - result->value.type = get_pointer_to_type_extra(ira->codegen, field->type_entry, is_const, is_volatile, - PtrLenSingle, - align_bytes, - (uint32_t)(ptr_bit_offset + field->bit_offset_in_host), - host_int_bytes_for_result_type, false); - return result; + if (field != nullptr) { + return ir_analyze_struct_field_ptr(ira, source_instr, field, container_ptr, bare_type, initializing); } else { return ir_analyze_container_member_access_inner(ira, bare_type, field_name, source_instr, container_ptr, container_type); @@ -17162,6 +17186,9 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ return ir_analyze_container_member_access_inner(ira, bare_type, field_name, source_instr, container_ptr, container_type); } else if (bare_type->id == ZigTypeIdUnion) { + bool is_const = container_ptr->value.type->data.pointer.is_const; + bool is_volatile = container_ptr->value.type->data.pointer.is_volatile; + TypeUnionField *field = find_union_type_field(bare_type, field_name); if (field) { if (instr_is_comptime(container_ptr)) { @@ -18849,7 +18876,7 @@ static IrInstruction *ir_analyze_instruction_ref(IrAnalyze *ira, IrInstructionRe static IrInstruction *ir_analyze_container_init_fields_union(IrAnalyze *ira, IrInstruction *instruction, ZigType *container_type, size_t instr_field_count, IrInstructionContainerInitFieldsField *fields, - IrInstruction *old_result_loc) + IrInstruction *result_loc) { Error err; assert(container_type->id == ZigTypeIdUnion); @@ -18905,21 +18932,17 @@ static IrInstruction *ir_analyze_container_init_fields_union(IrAnalyze *ira, IrI return result; } - ir_assert(old_result_loc != nullptr, instruction); - IrInstruction *result_loc = old_result_loc->child; - if (type_is_invalid(result_loc->value.type)) - return result_loc; return ir_get_deref(ira, instruction, result_loc, nullptr); } static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruction *instruction, ZigType *container_type, size_t instr_field_count, IrInstructionContainerInitFieldsField *fields, - IrInstruction *old_result_loc) + IrInstruction *result_loc) { Error err; if (container_type->id == ZigTypeIdUnion) { return ir_analyze_container_init_fields_union(ira, instruction, container_type, instr_field_count, - fields, old_result_loc); + fields, result_loc); } if (container_type->id != ZigTypeIdStruct || is_slice(container_type)) { ir_add_error(ira, instruction, @@ -18936,20 +18959,28 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc IrInstruction *first_non_const_instruction = nullptr; AstNode **field_assign_nodes = allocate(actual_field_count); + ZigList const_ptrs = {}; bool is_comptime = ir_should_inline(ira->new_irb.exec, instruction->scope) || type_requires_comptime(ira->codegen, container_type) == ReqCompTimeYes; - ConstExprValue const_val = {}; - const_val.special = ConstValSpecialStatic; - const_val.type = container_type; - // const_val.global_refs = allocate(1); - const_val.data.x_struct.fields = create_const_vals(actual_field_count); + + // Here we iterate over the fields that have been initialized, and emit + // compile errors for missing fields and duplicate fields. + // It is only now that we find out whether the struct initialization can be a comptime + // value, but we have already emitted runtime instructions for the fields that + // were initialized with runtime values, and have omitted instructions that would have + // initialized fields with comptime values. + // So now we must clean up this situation. If it turns out the struct initialization can + // be a comptime value, overwrite ConstPtrMutInfer with ConstPtrMutComptimeConst. + // Otherwise, we must emit instructions to runtime-initialize the fields that have + // comptime-known values. + for (size_t i = 0; i < instr_field_count; i += 1) { IrInstructionContainerInitFieldsField *field = &fields[i]; - IrInstruction *field_value = field->value->child; - if (type_is_invalid(field_value->value.type)) + IrInstruction *field_result_loc = field->result_loc->child; + if (type_is_invalid(field_result_loc->value.type)) return ira->codegen->invalid_instruction; TypeStructField *type_field = find_struct_type_field(container_type, field->name); @@ -18963,10 +18994,6 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc if (type_is_invalid(type_field->type_entry)) return ira->codegen->invalid_instruction; - IrInstruction *casted_field_value = ir_implicit_cast(ira, field_value, type_field->type_entry); - if (casted_field_value == ira->codegen->invalid_instruction) - return ira->codegen->invalid_instruction; - size_t field_index = type_field->src_index; AstNode *existing_assign_node = field_assign_nodes[field_index]; if (existing_assign_node) { @@ -18976,23 +19003,18 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc } field_assign_nodes[field_index] = field->source_node; - if (const_val.special == ConstValSpecialStatic) { - if (is_comptime || casted_field_value->value.special != ConstValSpecialRuntime) { - ConstExprValue *field_val = ir_resolve_const(ira, casted_field_value, UndefOk); - if (!field_val) - return ira->codegen->invalid_instruction; - - copy_const_val(&const_val.data.x_struct.fields[field_index], field_val, true); - } else { - first_non_const_instruction = casted_field_value; - const_val.special = ConstValSpecialRuntime; - } + if (instr_is_comptime(field_result_loc) && + field_result_loc->value.data.x_ptr.mut != ConstPtrMutRuntimeVar) + { + const_ptrs.append(field_result_loc); + } else { + first_non_const_instruction = field_result_loc; } } bool any_missing = false; for (size_t i = 0; i < actual_field_count; i += 1) { - if (field_assign_nodes[i]) continue; + if (field_assign_nodes[i] != nullptr) continue; // look for a default field value TypeStructField *field = &container_type->data.structure.fields[i]; @@ -19018,44 +19040,41 @@ static IrInstruction *ir_analyze_container_init_fields(IrAnalyze *ira, IrInstruc IrInstruction *runtime_inst = ir_const(ira, instruction, field->init_val->type); copy_const_val(&runtime_inst->value, field->init_val, true); - if (const_val.special == ConstValSpecialStatic) { - copy_const_val(&const_val.data.x_struct.fields[i], field->init_val, true); + IrInstruction *field_ptr = ir_analyze_struct_field_ptr(ira, instruction, field, result_loc, + container_type, true); + ir_analyze_store_ptr(ira, instruction, field_ptr, runtime_inst); + if (instr_is_comptime(field_ptr) && field_ptr->value.data.x_ptr.mut != ConstPtrMutRuntimeVar) { + const_ptrs.append(field_ptr); + } else { + first_non_const_instruction = result_loc; } } if (any_missing) return ira->codegen->invalid_instruction; - if (const_val.special == ConstValSpecialStatic) { - IrInstruction *result = ir_const(ira, instruction, nullptr); - ConstExprValue *out_val = &result->value; - copy_const_val(out_val, &const_val, false); - out_val->type = container_type; - - for (size_t i = 0; i < instr_field_count; i += 1) { - ConstExprValue *field_val = &out_val->data.x_struct.fields[i]; - ConstParent *parent = get_const_val_parent(ira->codegen, field_val); - if (parent != nullptr) { - parent->id = ConstParentIdStruct; - parent->data.p_struct.field_index = i; - parent->data.p_struct.struct_val = out_val; + if (result_loc->value.data.x_ptr.mut == ConstPtrMutInfer) { + if (const_ptrs.length == actual_field_count) { + result_loc->value.data.x_ptr.mut = ConstPtrMutComptimeConst; + } else { + result_loc->value.special = ConstValSpecialRuntime; + for (size_t i = 0; i < const_ptrs.length; i += 1) { + IrInstruction *field_result_loc = const_ptrs.at(i); + IrInstruction *deref = ir_get_deref(ira, field_result_loc, field_result_loc, nullptr); + field_result_loc->value.special = ConstValSpecialRuntime; + ir_analyze_store_ptr(ira, field_result_loc, field_result_loc, deref); } } - - return result; } - if (is_comptime) { + IrInstruction *result = ir_get_deref(ira, instruction, result_loc, nullptr); + + if (is_comptime && !instr_is_comptime(result)) { ir_add_error_node(ira, first_non_const_instruction->source_node, buf_sprintf("unable to evaluate constant expression")); return ira->codegen->invalid_instruction; } - - ir_assert(old_result_loc != nullptr, instruction); - IrInstruction *result_loc = old_result_loc->child; - if (type_is_invalid(result_loc->value.type)) - return result_loc; - return ir_get_deref(ira, instruction, result_loc, nullptr); + return result; } static IrInstruction *ir_analyze_instruction_container_init_list(IrAnalyze *ira, @@ -19074,8 +19093,11 @@ static IrInstruction *ir_analyze_instruction_container_init_list(IrAnalyze *ira, buf_sprintf("expected array type or [_], found slice")); return ira->codegen->invalid_instruction; } else if (container_type->id == ZigTypeIdStruct && !is_slice(container_type) && elem_count == 0) { - return ir_analyze_container_init_fields(ira, &instruction->base, container_type, 0, nullptr, - instruction->result_loc); + ir_assert(instruction->result_loc != nullptr, &instruction->base); + IrInstruction *result_loc = instruction->result_loc->child; + if (type_is_invalid(result_loc->value.type)) + return result_loc; + return ir_analyze_container_init_fields(ira, &instruction->base, container_type, 0, nullptr, result_loc); } else if (container_type->id == ZigTypeIdArray) { // array is same as slice init but we make a compile error if the length is wrong ZigType *child_type; @@ -19199,8 +19221,13 @@ static IrInstruction *ir_analyze_instruction_container_init_fields(IrAnalyze *ir if (type_is_invalid(container_type)) return ira->codegen->invalid_instruction; + ir_assert(instruction->result_loc != nullptr, &instruction->base); + IrInstruction *result_loc = instruction->result_loc->child; + if (type_is_invalid(result_loc->value.type)) + return result_loc; + return ir_analyze_container_init_fields(ira, &instruction->base, container_type, - instruction->field_count, instruction->fields, instruction->result_loc); + instruction->field_count, instruction->fields, result_loc); } static IrInstruction *ir_analyze_instruction_compile_err(IrAnalyze *ira, @@ -24390,17 +24417,7 @@ static IrInstruction *ir_analyze_instruction_end_expr(IrAnalyze *ira, IrInstruct if (type_is_invalid(value->value.type)) return ira->codegen->invalid_instruction; - bool want_resolve_result; - if (instruction->result_loc->written) { - if (instruction->result_loc->scope_elide != nullptr && instr_is_comptime(value)) { - want_resolve_result = true; - instruction->result_loc->scope_elide->activated = true; - } else { - want_resolve_result = false; - } - } else { - want_resolve_result = true; - } + bool want_resolve_result = !instruction->result_loc->written; if (want_resolve_result) { IrInstruction *result_loc = ir_resolve_result(ira, &instruction->base, instruction->result_loc, value->value.type, value); -- cgit v1.2.3 From b588a803bf4493d2fd1892fe172b9ce8cfb0ca30 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Wed, 19 Jun 2019 14:35:59 -0400 Subject: fix comptime modification of const struct field --- src/all_types.hpp | 3 +++ src/analyze.cpp | 2 +- src/codegen.cpp | 2 +- src/ir.cpp | 43 +++++++++++++++++++++++++++---------------- test/stage1/behavior.zig | 2 +- test/stage1/behavior/eval.zig | 16 ++++++++-------- 6 files changed, 41 insertions(+), 27 deletions(-) (limited to 'src/analyze.cpp') diff --git a/src/all_types.hpp b/src/all_types.hpp index 01f084218d..efb74e5ec3 100644 --- a/src/all_types.hpp +++ b/src/all_types.hpp @@ -334,6 +334,9 @@ struct ConstExprValue { RuntimeHintPtr rh_ptr; RuntimeHintSlice rh_slice; } data; + + ConstExprValue(const ConstExprValue &other) = delete; // plz zero initialize with {} + ConstExprValue& operator= (const ConstExprValue &other) = delete; // use copy_const_val }; enum ReturnKnowledge { diff --git a/src/analyze.cpp b/src/analyze.cpp index b39b1e35ca..d048dd9770 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -4711,7 +4711,7 @@ ReqCompTime type_requires_comptime(CodeGen *g, ZigType *type_entry) { void init_const_str_lit(CodeGen *g, ConstExprValue *const_val, Buf *str) { auto entry = g->string_literals_table.maybe_get(str); if (entry != nullptr) { - *const_val = *entry->value; + memcpy(const_val, entry->value, sizeof(ConstExprValue)); return; } diff --git a/src/codegen.cpp b/src/codegen.cpp index dc2a4f55df..8f3a8df451 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -6676,7 +6676,7 @@ static void do_code_gen(CodeGen *g) { zig_panic("TODO debug info for var with ptr casted value"); } ZigType *var_type = g->builtin_types.entry_f128; - ConstExprValue coerced_value; + ConstExprValue coerced_value = {}; coerced_value.special = ConstValSpecialStatic; coerced_value.type = var_type; coerced_value.data.x_f128 = bigfloat_to_f128(&const_val->data.x_bigfloat); diff --git a/src/ir.cpp b/src/ir.cpp index 83199fc0cc..3d125da1a1 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -10624,13 +10624,16 @@ static ZigType *ir_resolve_peer_types(IrAnalyze *ira, AstNode *source_node, ZigT static void copy_const_val(ConstExprValue *dest, ConstExprValue *src, bool same_global_refs) { ConstGlobalRefs *global_refs = dest->global_refs; - assert(!same_global_refs || src->global_refs != nullptr); - *dest = *src; + memcpy(dest, src, sizeof(ConstExprValue)); if (!same_global_refs) { dest->global_refs = global_refs; + if (src->special == ConstValSpecialUndef) + return; if (dest->type->id == ZigTypeIdStruct) { - dest->data.x_struct.fields = allocate_nonzero(dest->type->data.structure.src_field_count); - memcpy(dest->data.x_struct.fields, src->data.x_struct.fields, sizeof(ConstExprValue) * dest->type->data.structure.src_field_count); + dest->data.x_struct.fields = create_const_vals(dest->type->data.structure.src_field_count); + for (size_t i = 0; i < dest->type->data.structure.src_field_count; i += 1) { + copy_const_val(&dest->data.x_struct.fields[i], &src->data.x_struct.fields[i], false); + } } } } @@ -13579,7 +13582,7 @@ static ErrorMsg *ir_eval_math_op_scalar(IrAnalyze *ira, IrInstruction *source_in } } else { float_div_trunc(out_val, op1_val, op2_val); - ConstExprValue remainder; + ConstExprValue remainder = {}; float_rem(&remainder, op1_val, op2_val); if (float_cmp_zero(&remainder) != CmpEQ) { return ir_add_error(ira, source_instr, buf_sprintf("exact division had a remainder")); @@ -13954,8 +13957,8 @@ static IrInstruction *ir_analyze_bin_op_math(IrAnalyze *ira, IrInstructionBinOp // have a remainder function ambiguity problem ok = true; } else { - ConstExprValue rem_result; - ConstExprValue mod_result; + ConstExprValue rem_result = {}; + ConstExprValue mod_result = {}; float_rem(&rem_result, op1_val, op2_val); float_mod(&mod_result, op1_val, op2_val); ok = float_cmp(&rem_result, &mod_result) == CmpEQ; @@ -14178,10 +14181,12 @@ static IrInstruction *ir_analyze_array_cat(IrAnalyze *ira, IrInstructionBinOp *i size_t next_index = 0; for (size_t i = op1_array_index; i < op1_array_end; i += 1, next_index += 1) { - out_array_val->data.x_array.data.s_none.elements[next_index] = op1_array_val->data.x_array.data.s_none.elements[i]; + copy_const_val(&out_array_val->data.x_array.data.s_none.elements[next_index], + &op1_array_val->data.x_array.data.s_none.elements[i], true); } for (size_t i = op2_array_index; i < op2_array_end; i += 1, next_index += 1) { - out_array_val->data.x_array.data.s_none.elements[next_index] = op2_array_val->data.x_array.data.s_none.elements[i]; + copy_const_val(&out_array_val->data.x_array.data.s_none.elements[next_index], + &op2_array_val->data.x_array.data.s_none.elements[i], true); } if (next_index < new_len) { ConstExprValue *null_byte = &out_array_val->data.x_array.data.s_none.elements[next_index]; @@ -14242,7 +14247,8 @@ static IrInstruction *ir_analyze_array_mult(IrAnalyze *ira, IrInstructionBinOp * uint64_t i = 0; for (uint64_t x = 0; x < mult_amt; x += 1) { for (uint64_t y = 0; y < old_array_len; y += 1) { - out_val->data.x_array.data.s_none.elements[i] = array_val->data.x_array.data.s_none.elements[y]; + copy_const_val(&out_val->data.x_array.data.s_none.elements[i], + &array_val->data.x_array.data.s_none.elements[y], true); i += 1; } } @@ -14382,7 +14388,12 @@ static IrInstruction *ir_analyze_instruction_decl_var(IrAnalyze *ira, if (instr_is_comptime(var_ptr) && var_ptr->value.data.x_ptr.mut != ConstPtrMutRuntimeVar) { init_val = const_ptr_pointee(ira, ira->codegen, &var_ptr->value, decl_var_instruction->base.source_node); if (is_comptime_var) { - var->const_value = init_val; + if (var->gen_is_const) { + var->const_value = init_val; + } else { + var->const_value = create_const_vals(1); + copy_const_val(var->const_value, init_val, false); + } } } @@ -15291,7 +15302,7 @@ static bool ir_analyze_fn_call_generic_arg(IrAnalyze *ira, AstNode *fn_proto_nod arg_val = create_const_runtime(casted_arg->value.type); } if (arg_part_of_generic_id) { - generic_id->params[generic_id->param_count] = *arg_val; + copy_const_val(&generic_id->params[generic_id->param_count], arg_val, true); generic_id->param_count += 1; } @@ -15476,7 +15487,7 @@ static IrInstruction *ir_analyze_store_ptr(IrAnalyze *ira, IrInstruction *source // * "string literal used as comptime slice is memoized" // * "comptime modification of const struct field" - except modified to avoid // ConstPtrMutComptimeVar, thus defeating the logic below. - bool same_global_refs = ptr->value.data.x_ptr.mut != ConstPtrMutComptimeVar; + bool same_global_refs = ptr->value.data.x_ptr.mut == ConstPtrMutComptimeConst; copy_const_val(dest_val, &value->value, same_global_refs); if (!ira->new_irb.current_basic_block->must_be_comptime_source_instr) { ira->new_irb.current_basic_block->must_be_comptime_source_instr = source_instr; @@ -15877,7 +15888,7 @@ static IrInstruction *ir_analyze_fn_call(IrAnalyze *ira, IrInstructionCallSrc *c nullptr, nullptr, fn_proto_node->data.fn_proto.align_expr, nullptr, ira->new_irb.exec, nullptr); IrInstructionConst *const_instruction = ir_create_instruction(&ira->new_irb, impl_fn->child_scope, fn_proto_node->data.fn_proto.align_expr); - const_instruction->base.value = *align_result; + copy_const_val(&const_instruction->base.value, align_result, true); uint32_t align_bytes = 0; ir_resolve_align(ira, &const_instruction->base, &align_bytes); @@ -21667,7 +21678,7 @@ static IrInstruction *ir_analyze_instruction_memset(IrAnalyze *ira, IrInstructio ConstExprValue *byte_val = &casted_byte->value; for (size_t i = start; i < end; i += 1) { - dest_elements[i] = *byte_val; + copy_const_val(&dest_elements[i], byte_val, true); } return ir_const_void(ira, &instruction->base); @@ -21835,7 +21846,7 @@ static IrInstruction *ir_analyze_instruction_memcpy(IrAnalyze *ira, IrInstructio // TODO check for noalias violations - this should be generalized to work for any function for (size_t i = 0; i < count; i += 1) { - dest_elements[dest_start + i] = src_elements[src_start + i]; + copy_const_val(&dest_elements[dest_start + i], &src_elements[src_start + i], true); } return ir_const_void(ira, &instruction->base); diff --git a/test/stage1/behavior.zig b/test/stage1/behavior.zig index ccbec6849a..77fc482ccc 100644 --- a/test/stage1/behavior.zig +++ b/test/stage1/behavior.zig @@ -48,7 +48,7 @@ comptime { _ = @import("behavior/enum.zig"); // TODO _ = @import("behavior/enum_with_members.zig"); _ = @import("behavior/error.zig"); // TODO - _ = @import("behavior/eval.zig"); // TODO + _ = @import("behavior/eval.zig"); _ = @import("behavior/field_parent_ptr.zig"); _ = @import("behavior/fn.zig"); _ = @import("behavior/fn_in_struct_in_comptime.zig"); diff --git a/test/stage1/behavior/eval.zig b/test/stage1/behavior/eval.zig index 62cedbc76f..97d3a269cc 100644 --- a/test/stage1/behavior/eval.zig +++ b/test/stage1/behavior/eval.zig @@ -583,14 +583,14 @@ pub const Info = struct { pub const diamond_info = Info{ .version = 0 }; -//test "comptime modification of const struct field" { -// comptime { -// var res = diamond_info; -// res.version = 1; -// expect(diamond_info.version == 0); -// expect(res.version == 1); -// } -//} +test "comptime modification of const struct field" { + comptime { + var res = diamond_info; + res.version = 1; + expect(diamond_info.version == 0); + expect(res.version == 1); + } +} test "pointer to type" { comptime { -- cgit v1.2.3 From ff6d563b0455aea51775e6906f5e7f0dd67b7127 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Fri, 21 Jun 2019 17:49:54 -0400 Subject: fix implicit cast to optional to error union to return result loc --- src/analyze.cpp | 2 ++ src/ir.cpp | 9 ++++----- test/stage1/behavior/error.zig | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 5 deletions(-) (limited to 'src/analyze.cpp') diff --git a/src/analyze.cpp b/src/analyze.cpp index d048dd9770..85e390f2e0 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -4512,6 +4512,8 @@ bool fn_eval_cacheable(Scope *scope, ZigType *return_type) { ScopeVarDecl *var_scope = (ScopeVarDecl *)scope; if (type_is_invalid(var_scope->var->var_type)) return false; + if (var_scope->var->const_value->special == ConstValSpecialUndef) + return false; if (can_mutate_comptime_var_state(var_scope->var->const_value)) return false; } else if (scope->id == ScopeIdFnDef) { diff --git a/src/ir.cpp b/src/ir.cpp index 425c225308..a6ec836a40 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -15092,7 +15092,9 @@ static IrInstruction *ir_resolve_result_raw(IrAnalyze *ira, IrInstruction *suspe ZigType *ptr_return_type = get_pointer_to_type(ira->codegen, ira->explicit_return_type, false); result_loc->written = true; result_loc->resolved_loc = ir_build_return_ptr(ira, result_loc->source_instruction, ptr_return_type); - set_up_result_loc_for_inferred_comptime(result_loc->resolved_loc); + if (ir_should_inline(ira->old_irb.exec, result_loc->source_instruction->scope)) { + set_up_result_loc_for_inferred_comptime(result_loc->resolved_loc); + } return result_loc->resolved_loc; } case ResultLocIdPeer: { @@ -15207,9 +15209,6 @@ static IrInstruction *ir_resolve_result_raw(IrAnalyze *ira, IrInstruction *suspe parent_ptr_type->data.pointer.is_const, parent_ptr_type->data.pointer.is_volatile, PtrLenSingle, parent_ptr_align, 0, 0, parent_ptr_type->data.pointer.allow_zero); - if (value->value.special == ConstValSpecialRuntime) { - parent_result_loc->value.special = ConstValSpecialRuntime; - } result_loc->written = true; result_loc->resolved_loc = ir_analyze_ptr_cast(ira, suspend_source_instr, parent_result_loc, ptr_type, result_bit_cast->base.source_instruction, false); @@ -15388,7 +15387,7 @@ static bool ir_analyze_fn_call_inline_arg(IrAnalyze *ira, AstNode *fn_proto_node casted_arg = arg; } - ConstExprValue *arg_val = ir_resolve_const(ira, casted_arg, UndefBad); + ConstExprValue *arg_val = ir_resolve_const(ira, casted_arg, UndefOk); if (!arg_val) return false; diff --git a/test/stage1/behavior/error.zig b/test/stage1/behavior/error.zig index 82ddc72b7b..264f140c9d 100644 --- a/test/stage1/behavior/error.zig +++ b/test/stage1/behavior/error.zig @@ -357,3 +357,21 @@ test "nested catch" { S.entry(); comptime S.entry(); } + +test "implicit cast to optional to error union to return result loc" { + const S = struct { + fn entry() void { + if (func(undefined)) |opt| { + expect(opt != null); + } else |_| @panic("expected non error"); + } + fn func(f: *Foo) anyerror!?*Foo { + return f; + } + const Foo = struct { + field: i32, + }; + }; + S.entry(); + //comptime S.entry(); TODO +} -- cgit v1.2.3 From c61e0a078cea2a6845ed7b03189409829d2cdf24 Mon Sep 17 00:00:00 2001 From: Andrew Kelley Date: Tue, 25 Jun 2019 11:31:38 -0400 Subject: fix union init with void payload all std lib tests passing now --- src/analyze.cpp | 14 +++----------- src/analyze.hpp | 1 - src/codegen.cpp | 14 +++++++++++++- src/ir.cpp | 18 +++++++----------- std/zig/parser_test.zig | 12 +----------- test/stage1/behavior/union.zig | 20 ++++++++++++++++++++ 6 files changed, 44 insertions(+), 35 deletions(-) (limited to 'src/analyze.cpp') diff --git a/src/analyze.cpp b/src/analyze.cpp index 85e390f2e0..d3a9376c5d 100644 --- a/src/analyze.cpp +++ b/src/analyze.cpp @@ -5001,12 +5001,9 @@ void init_const_undefined(CodeGen *g, ConstExprValue *const_val) { field_val->type = wanted_type->data.structure.fields[i].type_entry; assert(field_val->type); init_const_undefined(g, field_val); - ConstParent *parent = get_const_val_parent(g, field_val); - if (parent != nullptr) { - parent->id = ConstParentIdStruct; - parent->data.p_struct.struct_val = const_val; - parent->data.p_struct.field_index = i; - } + field_val->parent.id = ConstParentIdStruct; + field_val->parent.data.p_struct.struct_val = const_val; + field_val->parent.data.p_struct.field_index = i; } } else { const_val->special = ConstValSpecialUndef; @@ -5842,11 +5839,6 @@ void expand_undef_array(CodeGen *g, ConstExprValue *const_val) { zig_unreachable(); } -// Deprecated. Reference the parent field directly. -ConstParent *get_const_val_parent(CodeGen *g, ConstExprValue *value) { - return &value->parent; -} - static const ZigTypeId all_type_ids[] = { ZigTypeIdMetaType, ZigTypeIdVoid, diff --git a/src/analyze.hpp b/src/analyze.hpp index 8d78ef86e2..a6ad92110e 100644 --- a/src/analyze.hpp +++ b/src/analyze.hpp @@ -180,7 +180,6 @@ void init_const_undefined(CodeGen *g, ConstExprValue *const_val); ConstExprValue *create_const_vals(size_t count); ZigType *make_int_type(CodeGen *g, bool is_signed, uint32_t size_in_bits); -ConstParent *get_const_val_parent(CodeGen *g, ConstExprValue *value); void expand_undef_array(CodeGen *g, ConstExprValue *const_val); void update_compile_var(CodeGen *g, Buf *name, ConstExprValue *value); diff --git a/src/codegen.cpp b/src/codegen.cpp index e12f89756d..2e430a60e0 100644 --- a/src/codegen.cpp +++ b/src/codegen.cpp @@ -3873,8 +3873,20 @@ static LLVMValueRef ir_render_union_field_ptr(CodeGen *g, IrExecutable *executab TypeUnionField *field = instruction->field; - if (!type_has_bits(field->type_entry)) + if (!type_has_bits(field->type_entry)) { + if (union_type->data.unionation.gen_tag_index == SIZE_MAX) { + return nullptr; + } + if (instruction->initializing) { + LLVMValueRef union_ptr = ir_llvm_value(g, instruction->union_ptr); + LLVMValueRef tag_field_ptr = LLVMBuildStructGEP(g->builder, union_ptr, + union_type->data.unionation.gen_tag_index, ""); + LLVMValueRef tag_value = bigint_to_llvm_const(get_llvm_type(g, union_type->data.unionation.tag_type), + &field->enum_field->value); + gen_store_untyped(g, tag_value, tag_field_ptr, 0, false); + } return nullptr; + } LLVMValueRef union_ptr = ir_llvm_value(g, instruction->union_ptr); LLVMTypeRef field_type_ref = LLVMPointerType(get_llvm_type(g, field->type_entry), 0); diff --git a/src/ir.cpp b/src/ir.cpp index 32e3692afd..2991dd5186 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -17425,11 +17425,9 @@ static IrInstruction *ir_analyze_struct_field_ptr(IrAnalyze *ira, IrInstruction ConstExprValue *field_val = &struct_val->data.x_struct.fields[i]; field_val->special = ConstValSpecialUndef; field_val->type = struct_type->data.structure.fields[i].type_entry; - ConstParent *parent = get_const_val_parent(ira->codegen, field_val); - assert(parent != nullptr); - parent->id = ConstParentIdStruct; - parent->data.p_struct.struct_val = struct_val; - parent->data.p_struct.field_index = i; + field_val->parent.id = ConstParentIdStruct; + field_val->parent.data.p_struct.struct_val = struct_val; + field_val->parent.data.p_struct.field_index = i; } } IrInstruction *result; @@ -17507,11 +17505,8 @@ static IrInstruction *ir_analyze_container_field_ptr(IrAnalyze *ira, Buf *field_ ConstExprValue *payload_val = create_const_vals(1); payload_val->special = ConstValSpecialUndef; payload_val->type = field->type_entry; - ConstParent *parent = get_const_val_parent(ira->codegen, payload_val); - if (parent != nullptr) { - parent->id = ConstParentIdUnion; - parent->data.p_union.union_val = union_val; - } + payload_val->parent.id = ConstParentIdUnion; + payload_val->parent.data.p_union.union_val = union_val; union_val->special = ConstValSpecialStatic; bigint_init_bigint(&union_val->data.x_union.tag, &field->enum_field->value); @@ -25289,7 +25284,6 @@ bool ir_has_side_effects(IrInstruction *instruction) { case IrInstructionIdReturnPtr: case IrInstructionIdTypeOf: case IrInstructionIdStructFieldPtr: - case IrInstructionIdUnionFieldPtr: case IrInstructionIdArrayType: case IrInstructionIdPromiseType: case IrInstructionIdSliceType: @@ -25389,6 +25383,8 @@ bool ir_has_side_effects(IrInstruction *instruction) { } case IrInstructionIdUnwrapErrCode: return reinterpret_cast(instruction)->initializing; + case IrInstructionIdUnionFieldPtr: + return reinterpret_cast(instruction)->initializing; case IrInstructionIdErrWrapPayload: return reinterpret_cast(instruction)->result_loc != nullptr; case IrInstructionIdErrWrapCode: diff --git a/std/zig/parser_test.zig b/std/zig/parser_test.zig index 29b70d0a6e..a004089fec 100644 --- a/std/zig/parser_test.zig +++ b/std/zig/parser_test.zig @@ -1,4 +1,4 @@ -// TODO remove `use` keyword eventually +// TODO remove `use` keyword eventually: https://github.com/ziglang/zig/issues/2591 test "zig fmt: change use to usingnamespace" { try testTransform( \\use @import("std"); @@ -105,7 +105,6 @@ test "zig fmt: linksection" { } test "zig fmt: correctly move doc comments on struct fields" { - if (true) return error.SkipZigTest; // TODO try testTransform( \\pub const section_64 = extern struct { \\ sectname: [16]u8, /// name of this section @@ -917,7 +916,6 @@ test "zig fmt: statements with empty line between" { } test "zig fmt: ptr deref operator and unwrap optional operator" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\const a = b.*; \\const a = b.?; @@ -1020,7 +1018,6 @@ test "zig fmt: same-line comment after a statement" { } test "zig fmt: same-line comment after var decl in struct" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\pub const vfs_cap_data = extern struct { \\ const Data = struct {}; // when on disk. @@ -1030,7 +1027,6 @@ test "zig fmt: same-line comment after var decl in struct" { } test "zig fmt: same-line comment after field decl" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\pub const dirent = extern struct { \\ d_name: u8, @@ -1106,7 +1102,6 @@ test "zig fmt: line comments in struct initializer" { } test "zig fmt: first line comment in struct initializer" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\pub async fn acquire(self: *Self) HeldLock { \\ return HeldLock{ @@ -1120,7 +1115,6 @@ test "zig fmt: first line comment in struct initializer" { } test "zig fmt: doc comments before struct field" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\pub const Allocator = struct { \\ /// Allocate byte_count bytes and return them in a slice, with the @@ -1218,7 +1212,6 @@ test "zig fmt: comments before switch prong" { } test "zig fmt: comments before var decl in struct" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\pub const vfs_cap_data = extern struct { \\ // All of these are mandated as little endian @@ -1609,7 +1602,6 @@ test "zig fmt: indexing" { } test "zig fmt: struct declaration" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\const S = struct { \\ const Self = @This(); @@ -1641,7 +1633,6 @@ test "zig fmt: struct declaration" { } test "zig fmt: enum declaration" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\const E = enum { \\ Ok, @@ -1670,7 +1661,6 @@ test "zig fmt: enum declaration" { } test "zig fmt: union declaration" { - if (true) return error.SkipZigTest; // TODO try testCanonical( \\const U = union { \\ Int: u8, diff --git a/test/stage1/behavior/union.zig b/test/stage1/behavior/union.zig index 0e8e9f4eda..410b7e9615 100644 --- a/test/stage1/behavior/union.zig +++ b/test/stage1/behavior/union.zig @@ -402,3 +402,23 @@ test "comptime union field value equality" { expect(a0 != a1); expect(b0 != b1); } + +test "return union init with void payload" { + const S = struct { + fn entry() void { + expect(func().state == State.one); + } + const Outer = union(enum) { + state: State, + }; + const State = union(enum) { + one: void, + two: u32, + }; + fn func() Outer { + return Outer{ .state = State{ .one = {} }}; + } + }; + S.entry(); + comptime S.entry(); +} -- cgit v1.2.3