Add return value support to C++ thunks. (#5976)

Based on #5948. A couple of tricky parts:

* When generating the C++ side of the thunk, we are given a pointer to
the location to emplace the return value. The only mechanism C++
provides to perform this emplacement is using placement `operator new`,
which requires a library function in the `<new>` header. We handle this
by declaring that library function ourselves, and rely on Clang not
actually needing a definition for it (which the standard library owns).

* On the Carbon side of the thunk, we want to form an initializing
expression as the result of the call. We don't have a way of expressing
in SemIR that an initializing expression performs its initialization by
storing through a pointer, so this PR adds a new initializing
instruction, `InPlaceInit`, to model an initialization that's performed
opaquely in-place.
This commit is contained in:
Richard Smith
2025-08-26 02:23:38 +00:00
committed by GitHub
parent 1331ade57f
commit d37f1ae6b5
17 changed files with 1039 additions and 96 deletions
+28
View File
@@ -102,6 +102,34 @@ static auto GenerateCppIncludesHeaderCode(
<< "\"\n";
}
}
// Inject a declaration of placement operator new, because the code we
// generate in thunks depends on it for placement new expressions. Clang has
// special-case logic for lowering a new-expression using this, so a
// definition is not required.
// TODO: This is a hack. We should be able to directly generate Clang AST to
// construct objects in-place without this.
// TODO: Once we can rely on libc++ being available, consider including
// `<__new/placement_new_delete.h>` instead.
code_stream << R"(# 1 "<carbon-internal>"
#undef constexpr
#if __cplusplus > 202302L
constexpr
#endif
#undef void
#undef operator
#undef new
void* operator new(__SIZE_TYPE__, void*)
#if __cplusplus < 201103L
#undef throw
throw()
#else
#undef noexcept
noexcept
#endif
;
)";
return code;
}