From 9fd28f7304ebc1e80bb7b13e5d36bdca5234abf4 Mon Sep 17 00:00:00 2001 From: David Blaikie Date: Thu, 8 Oct 2026 19:52:12 +0000 Subject: [PATCH] Lower `return expr;` for value return forms of class type (#7908) A function with a value return form, such as `->? form(val C)`, is lowered to return the value representation of `C`: a pointer for types with a pointer value representation. However, lowering of `ReturnExpr` re-derived the return convention independently of the function's signature, and assumed that any returned value expression was a `returned var`, taking the initializing-return path. For types with an in-place initializing representation, that tried to initialize a nonexistent return slot and crashed. (This only appeared to work for types like `i32`, whose by-copy initializing representation happens to match the value representation.) Fix this by recording how the function returns its result -- `void`, by copy, by reference, in place via an `sret` parameter, or as the entry point's implicit `i32` -- as a `ReturnKind` in `FunctionTypeInfo` and `FunctionInfo` when the signature is lowered, and having the `Return` and `ReturnExpr` handlers switch on it. This keeps the signature and the `return` lowering in agreement by construction, and replaces the `IsEntryPoint` check in `Return` lowering. --- .../check/testdata/return/val_form.carbon | 84 ++++++++++++++++++ toolchain/lower/file_context.cpp | 2 + toolchain/lower/file_context.h | 3 + toolchain/lower/handle.cpp | 88 ++++++++----------- .../lower/testdata/function/call/form.carbon | 37 ++++++++ toolchain/lower/type.cpp | 10 +++ toolchain/lower/type.h | 22 +++++ 7 files changed, 197 insertions(+), 49 deletions(-) create mode 100644 toolchain/check/testdata/return/val_form.carbon diff --git a/toolchain/check/testdata/return/val_form.carbon b/toolchain/check/testdata/return/val_form.carbon new file mode 100644 index 000000000000..078965ce9b88 --- /dev/null +++ b/toolchain/check/testdata/return/val_form.carbon @@ -0,0 +1,84 @@ +// Part of the Carbon Language project, under the Apache License v2.0 with LLVM +// Exceptions. See /LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// INCLUDE-FILE: toolchain/testing/testdata/min_prelude/int.carbon +// EXTRA-ARGS: --dump-sem-ir-ranges=only +// +// AUTOUPDATE +// TIP: To test this file alone, run: +// TIP: bazel test //toolchain/testing:file_test --test_arg=--file_tests=toolchain/check/testdata/return/val_form.carbon +// TIP: To dump output, run: +// TIP: bazel run //toolchain/testing:file_test -- --dump_output --file_tests=toolchain/check/testdata/return/val_form.carbon + +// --- param.carbon +library "[[@TEST_NAME]]"; + +class C { var a: i32; } + +//@dump-sem-ir-begin +fn F(c: C) ->? form(val C) { + return c; +} +//@dump-sem-ir-end + +// --- todo_fail_dangling_local.carbon +library "[[@TEST_NAME]]"; + +class C { var a: i32; } + +// TODO: Reject returning a dangling reference to a local variable. +fn F() ->? form(val C) { + var c: C = {.a = 1}; + return c; +} + +// --- todo_fail_dangling_temporary.carbon +library "[[@TEST_NAME]]"; + +class C { var a: i32; } + +// TODO: Reject returning a dangling reference to a temporary. +fn F() ->? form(val C) { + return {.a = 1}; +} + +// CHECK:STDOUT: --- param.carbon +// CHECK:STDOUT: +// CHECK:STDOUT: constants { +// CHECK:STDOUT: type: type = facet_type [concrete] +// CHECK:STDOUT: %C: type = class_type @C [concrete] +// CHECK:STDOUT: %pattern_type.98b: type = pattern_type %C [concrete] +// CHECK:STDOUT: %c.param_patt: %pattern_type.98b = value_param_pattern [concrete] +// CHECK:STDOUT: %c.patt: %pattern_type.98b = wrapper_binding_pattern c, %c.param_patt [concrete] +// CHECK:STDOUT: %.fbb: Core.Form = value_form %C [concrete] +// CHECK:STDOUT: %.483: %pattern_type.98b = value_return_pattern [concrete] +// CHECK:STDOUT: %return.patt: %pattern_type.98b = return_slot_pattern %.483, %C [concrete] +// CHECK:STDOUT: %F.type: type = fn_type @F [concrete] +// CHECK:STDOUT: %F: %F.type = struct_value () [concrete] +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: file { +// CHECK:STDOUT: %F.decl: %F.type = fn_decl @F [concrete = constants.%F] { +// CHECK:STDOUT: %c.param_patt: %pattern_type.98b = value_param_pattern [concrete = constants.%c.param_patt] +// CHECK:STDOUT: %c.patt: %pattern_type.98b = wrapper_binding_pattern c, %c.param_patt [concrete = constants.%c.patt] +// CHECK:STDOUT: %.loc6_21.1: %pattern_type.98b = value_return_pattern [concrete = constants.%.483] +// CHECK:STDOUT: %return.patt: %pattern_type.98b = return_slot_pattern %.loc6_21.1, %.loc6_21.3 [concrete = constants.%return.patt] +// CHECK:STDOUT: } { +// CHECK:STDOUT: %C.ref.loc6_25: type = name_ref C, file.%C.decl [concrete = constants.%C] +// CHECK:STDOUT: %.loc6_21.2: Core.Form = value_form %C.ref.loc6_25 [concrete = constants.%.fbb] +// CHECK:STDOUT: %.loc6_21.3: type = type_component_of %.loc6_21.2 [concrete = constants.%C] +// CHECK:STDOUT: %c.param: %C = value_param call_param0 +// CHECK:STDOUT: %C.ref.loc6_9: type = name_ref C, file.%C.decl [concrete = constants.%C] +// CHECK:STDOUT: %c: %C = wrapper_binding c, %c.param +// CHECK:STDOUT: %.loc6_21.4: %C = value_return +// CHECK:STDOUT: %return: %C = return_slot %.loc6_21.4 +// CHECK:STDOUT: } +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: fn @F(%c.param: %C) -> val %C { +// CHECK:STDOUT: !entry: +// CHECK:STDOUT: %c.ref: %C = name_ref c, %c +// CHECK:STDOUT: return %c.ref +// CHECK:STDOUT: } +// CHECK:STDOUT: diff --git a/toolchain/lower/file_context.cpp b/toolchain/lower/file_context.cpp index d118c934a0ec..13f160080ab7 100644 --- a/toolchain/lower/file_context.cpp +++ b/toolchain/lower/file_context.cpp @@ -171,6 +171,7 @@ auto FileContext::LowerDefinitions() -> void { .unused_param_indices = std::move(function_type_info.unused_param_indices), .llvm_function = llvm_function, + .return_kind = function_type_info.return_kind, .inexact = function_type_info.inexact}; functions_.Set(global_ctor_id, function_info); @@ -462,6 +463,7 @@ auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id, .unused_param_indices = std::move(function_type_info.unused_param_indices), .llvm_function = llvm_function, + .return_kind = function_type_info.return_kind, .inexact = function_type_info.inexact}}; } diff --git a/toolchain/lower/file_context.h b/toolchain/lower/file_context.h index 71afdac495c6..035baa7eaf90 100644 --- a/toolchain/lower/file_context.h +++ b/toolchain/lower/file_context.h @@ -43,6 +43,9 @@ struct FunctionInfo { // The lowered function declaration. llvm::Function* llvm_function; + // How the lowered function returns its result. + ReturnKind return_kind; + // Whether the function type information is inexact, because some component // type was incomplete. If this is set, the function should not be used to // emit a definition or a call. diff --git a/toolchain/lower/handle.cpp b/toolchain/lower/handle.cpp index 30bd9a405957..8150fe0e15e2 100644 --- a/toolchain/lower/handle.cpp +++ b/toolchain/lower/handle.cpp @@ -13,7 +13,6 @@ #include "llvm/Support/Casting.h" #include "toolchain/lower/function_context.h" #include "toolchain/sem_ir/builtin_function_kind.h" -#include "toolchain/sem_ir/entry_point.h" #include "toolchain/sem_ir/expr_info.h" #include "toolchain/sem_ir/function.h" #include "toolchain/sem_ir/inst.h" @@ -256,14 +255,22 @@ auto HandleInst(FunctionContext& context, SemIR::InstId inst_id, context.SetLocal(inst_id, context.GetValue(inst.storage_id)); } +// Returns how the function being lowered returns its result, as determined +// when its signature was lowered. +static auto GetReturnKind(FunctionContext& context) -> ReturnKind { + const auto& function_info = context.specific_file_context().GetFunctionInfo( + context.specific_sem_ir_function_id(), context.specific_id()); + CARBON_CHECK(function_info, "Lowering body of undeclared function"); + return function_info->return_kind; +} + auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/, SemIR::Return /*inst*/) -> void { // The 'Run()' entry point does not need to specify a return type, but // the C runtime and system ABI expects the entry point to return an `int`. // In this situation we modify the lowered IR to return `0` // with the expected LLVM type that corresponds to the `int` type. - if (SemIR::IsEntryPoint(context.specific_sem_ir(), - context.specific_sem_ir_function_id())) { + if (GetReturnKind(context) == ReturnKind::EntryPointInt32) { context.builder().CreateRet(context.builder().getInt32(0)); return; } @@ -276,63 +283,46 @@ auto HandleInst(FunctionContext& context, SemIR::InstId /*inst_id*/, SemIR::GetExprCategory(context.sem_ir(), inst.expr_id, &context.specific_sem_ir(), context.specific_id()); context.AddEnumToCurrentFingerprint(expr_cat); - switch (expr_cat) { - case SemIR::ExprCategory::EphemeralRef: - case SemIR::ExprCategory::DurableRef: - // Reference return. - context.builder().CreateRet(context.GetValue(inst.expr_id)); - return; - case SemIR::ExprCategory::Value: - // Return of a `returned var`. - case SemIR::ExprCategory::ReprInitializing: - case SemIR::ExprCategory::InPlaceInitializing: - // Initializing return. - break; - - case SemIR::ExprCategory::Mixed: - case SemIR::ExprCategory::RefTagged: - case SemIR::ExprCategory::NotExpr: - case SemIR::ExprCategory::Error: - case SemIR::ExprCategory::Pattern: - case SemIR::ExprCategory::Dependent: - CARBON_FATAL("Unexpected category {0} for `return` expression {1}", - expr_cat, context.sem_ir().insts().Get(inst.expr_id)); - } - - auto result_type = context.GetTypeIdOfInst(inst.expr_id); - switch (context.GetInitRepr(result_type).kind) { - case SemIR::InitRepr::None: + auto return_kind = GetReturnKind(context); + context.AddEnumToCurrentFingerprint(return_kind); + switch (return_kind) { + case ReturnKind::None: // Nothing to return. context.builder().CreateRetVoid(); return; - case SemIR::InitRepr::InPlace: - CARBON_CHECK(context.GetValueRepr(result_type).repr.kind == - SemIR::ValueRepr::Pointer, - "TODO: Add support for ReturnExpr with custom value repr"); - // TODO: find a way to avoid the redundant call to GetInitRepr inside - // InitializeStorage. - context.InitializeStorage(result_type, inst.dest_id, inst.expr_id); - context.builder().CreateRetVoid(); + + case ReturnKind::ByReference: + // Return a pointer: either the address of a reference, or the value + // representation of a value of a type with a pointer (or pointer-like + // custom) value representation. + context.builder().CreateRet(context.GetValue(inst.expr_id)); return; - case SemIR::InitRepr::ByCopy: { + + case ReturnKind::ByCopy: { auto* value = context.GetValue(inst.expr_id); if (expr_cat == SemIR::ExprCategory::InPlaceInitializing) { - value = - context.builder().CreateLoad(context.GetType(result_type), value); + value = context.builder().CreateLoad( + context.GetType(context.GetTypeIdOfInst(inst.expr_id)), value); } context.builder().CreateRet(value); return; } - case SemIR::InitRepr::Abstract: - CARBON_FATAL("Lowering return of abstract type {0}", - result_type.file->types().GetAsInst(result_type.type_id)); - case SemIR::InitRepr::Incomplete: - CARBON_FATAL("Lowering return of incomplete type {0}", - result_type.file->types().GetAsInst(result_type.type_id)); - case SemIR::InitRepr::Dependent: - CARBON_FATAL("Lowering return of dependent type {0}", - result_type.file->types().GetAsInst(result_type.type_id)); + + case ReturnKind::InPlace: { + auto result_type = context.GetTypeIdOfInst(inst.expr_id); + CARBON_CHECK(context.GetValueRepr(result_type).repr.kind == + SemIR::ValueRepr::Pointer, + "TODO: Add support for ReturnExpr with custom value repr"); + context.InitializeStorage(result_type, inst.dest_id, inst.expr_id); + context.builder().CreateRetVoid(); + return; + } + + case ReturnKind::EntryPointInt32: + CARBON_FATAL( + "`return` with expression in entry point without a return " + "type"); } } diff --git a/toolchain/lower/testdata/function/call/form.carbon b/toolchain/lower/testdata/function/call/form.carbon index a7e7b12a2954..e51d09f2c699 100644 --- a/toolchain/lower/testdata/function/call/form.carbon +++ b/toolchain/lower/testdata/function/call/form.carbon @@ -76,6 +76,16 @@ fn G() { let unused x: i32 = F(); } +// --- val_return_form_class_definition.carbon +library "[[@TEST_NAME]]"; + +class C { var a: i32; } + +// Returns a pointer to the caller's argument. +fn F(c: C) ->? form(val C) { + return c; +} + // CHECK:STDOUT: ; --- // CHECK:STDOUT: ; ModuleID = 'ref_form_param.carbon' // CHECK:STDOUT: source_filename = "ref_form_param.carbon" @@ -347,3 +357,30 @@ fn G() { // CHECK:STDOUT: !89 = !DILocation(line: 8, column: 23, scope: !88) // CHECK:STDOUT: !92 = !DILocation(line: 7, column: 1, scope: !88) // CHECK:STDOUT: +// CHECK:STDOUT: ; --- +// CHECK:STDOUT: ; ModuleID = 'val_return_form_class_definition.carbon' +// CHECK:STDOUT: source_filename = "val_return_form_class_definition.carbon" +// CHECK:STDOUT: +// CHECK:STDOUT: ; Function Attrs: nounwind +// CHECK:STDOUT: define ptr @_CF.Main(ptr %c) #0 !dbg !97 { +// CHECK:STDOUT: entry: +// CHECK:STDOUT: ret ptr %c, !dbg !103 +// CHECK:STDOUT: } +// CHECK:STDOUT: +// CHECK:STDOUT: attributes #0 = { nounwind } +// CHECK:STDOUT: +// CHECK:STDOUT: !llvm.dbg.cu = !{!94} +// CHECK:STDOUT: !llvm.module.flags = !{!2, !3} +// CHECK:STDOUT: +// CHECK:STDOUT: !2 = !{i32 7, !"Dwarf Version", i32 5} +// CHECK:STDOUT: !3 = !{i32 2, !"Debug Info Version", i32 3} +// CHECK:STDOUT: !53 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: null, size: 64) +// CHECK:STDOUT: !93 = !DIFile(filename: "val_return_form_class_definition.carbon", directory: "") +// CHECK:STDOUT: !94 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !93, producer: "carbon", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug) +// CHECK:STDOUT: !95 = !{!53, !53} +// CHECK:STDOUT: !96 = !DISubroutineType(types: !95) +// CHECK:STDOUT: !97 = distinct !DISubprogram(name: "F", linkageName: "_CF.Main", scope: null, file: !93, line: 6, type: !96, spFlags: DISPFlagDefinition, unit: !94, retainedNodes: !104) +// CHECK:STDOUT: !98 = !DILocalVariable(arg: 1, scope: !97, type: !53) +// CHECK:STDOUT: !103 = !DILocation(line: 7, column: 3, scope: !97) +// CHECK:STDOUT: !104 = !{!98} +// CHECK:STDOUT: diff --git a/toolchain/lower/type.cpp b/toolchain/lower/type.cpp index d769f3dd529c..fe5cc2d236a4 100644 --- a/toolchain/lower/type.cpp +++ b/toolchain/lower/type.cpp @@ -136,6 +136,8 @@ class FunctionTypeInfoBuilder { auto lowered_return_types = GetLoweredTypes(func_ctx, return_type_id); return_type_ = lowered_return_types.llvm_ir_type; param_di_types_.push_back(lowered_return_types.llvm_di_type); + return_kind_ = + return_type_id.has_value() ? ReturnKind::ByCopy : ReturnKind::None; return true; } @@ -145,6 +147,7 @@ class FunctionTypeInfoBuilder { return_type_ = llvm::Type::getInt32Ty(func_ctx.context->llvm_context()); param_di_types_.push_back(context_->di_builder().createBasicType( "int", 32, llvm::dwarf::DW_ATE_signed)); + return_kind_ = ReturnKind::EntryPointInt32; return true; } @@ -156,6 +159,7 @@ class FunctionTypeInfoBuilder { /*AddressSpace=*/0); // TODO: replace this with a reference type. param_di_types_.push_back(GetPointerDIType(nullptr)); + return_kind_ = ReturnKind::ByReference; return true; } @@ -167,6 +171,7 @@ class FunctionTypeInfoBuilder { sret_type_ = func_ctx.context->GetType(return_type_id); // We don't add to param_di_types_ because that will be handled by the // loop over the SemIR parameters. + return_kind_ = ReturnKind::InPlace; return true; } @@ -271,6 +276,9 @@ class FunctionTypeInfoBuilder { // attribute with this type. llvm::Type* sret_type_ = nullptr; + // How the LLVM function returns its result. + ReturnKind return_kind_ = ReturnKind::None; + // Whether we failed to form an exact description of the function type. This // can happen if a parameter or return type is incomplete. In this case, we // can still sometimes need to emit a declaration of the function, for example @@ -508,6 +516,7 @@ auto FunctionTypeInfoBuilder::Finalize() -> FunctionTypeInfo { .unused_param_indices = std::move(unused_param_indices_), .param_name_ids = std::move(param_name_ids_), .sret_type = sret_type_, + .return_kind = return_kind_, .inexact = inexact_}; } @@ -519,6 +528,7 @@ auto FunctionTypeInfoBuilder::Abort() -> FunctionTypeInfo { param_types_.clear(); param_di_types_.clear(); return_type_ = llvm::Type::getVoidTy(context_->llvm_context()); + return_kind_ = ReturnKind::None; param_di_types_.push_back(nullptr); inexact_ = true; return Finalize(); diff --git a/toolchain/lower/type.h b/toolchain/lower/type.h index 3688f29e2060..7a14d12d2a2a 100644 --- a/toolchain/lower/type.h +++ b/toolchain/lower/type.h @@ -5,6 +5,8 @@ #ifndef CARBON_TOOLCHAIN_LOWER_TYPE_H_ #define CARBON_TOOLCHAIN_LOWER_TYPE_H_ +#include + #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/IR/DebugInfoMetadata.h" @@ -23,6 +25,23 @@ struct FunctionInContext { SemIR::SpecificId specific_id; }; +// How a lowered function returns its result. +enum class ReturnKind : uint8_t { + // The function returns `void`, either because it has no return type or + // because the returned value has no representation. + None, + // The function is the entry point, which returns an `i32` exit code even + // though it has no declared return type. + EntryPointInt32, + // The function returns the result by copy, as an LLVM return value. + ByCopy, + // The function returns a pointer to the result, as an LLVM return value. + ByReference, + // The function initializes the result in a caller-provided `sret` parameter + // and returns `void`. + InPlace, +}; + // Information used to build a FunctionInfo in FileContext. struct FunctionTypeInfo { // The type of the lowered function. @@ -47,6 +66,9 @@ struct FunctionTypeInfo { // should be given an `sret` attribute with this type. llvm::Type* sret_type = nullptr; + // How the lowered function returns its result. + ReturnKind return_kind = ReturnKind::None; + // Whether the function type information is inexact, because some component // type was incomplete. bool inexact;