thunk.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/cpp/thunk.h"
  5. #include "clang/AST/ASTConsumer.h"
  6. #include "clang/AST/GlobalDecl.h"
  7. #include "clang/AST/Mangle.h"
  8. #include "clang/Sema/Lookup.h"
  9. #include "clang/Sema/Overload.h"
  10. #include "clang/Sema/Sema.h"
  11. #include "toolchain/check/call.h"
  12. #include "toolchain/check/context.h"
  13. #include "toolchain/check/control_flow.h"
  14. #include "toolchain/check/convert.h"
  15. #include "toolchain/check/literal.h"
  16. #include "toolchain/check/type.h"
  17. #include "toolchain/check/type_completion.h"
  18. #include "toolchain/sem_ir/function.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/typed_insts.h"
  21. namespace Carbon::Check {
  22. // Returns the GlobalDecl to use to represent the given function declaration.
  23. // TODO: Refactor with `Lower::CreateGlobalDecl`.
  24. static auto GetGlobalDecl(const clang::FunctionDecl* decl)
  25. -> clang::GlobalDecl {
  26. if (const auto* ctor = dyn_cast<clang::CXXConstructorDecl>(decl)) {
  27. return clang::GlobalDecl(ctor, clang::CXXCtorType::Ctor_Complete);
  28. }
  29. if (const auto* dtor = dyn_cast<clang::CXXDestructorDecl>(decl)) {
  30. return clang::GlobalDecl(dtor, clang::CXXDtorType::Dtor_Complete);
  31. }
  32. return clang::GlobalDecl(decl);
  33. }
  34. // Returns the C++ thunk mangled name given the callee function.
  35. static auto GenerateThunkMangledName(
  36. clang::MangleContext& mangle_context,
  37. const clang::FunctionDecl& callee_function_decl, int num_params)
  38. -> std::string {
  39. RawStringOstream mangled_name_stream;
  40. mangle_context.mangleName(GetGlobalDecl(&callee_function_decl),
  41. mangled_name_stream);
  42. mangled_name_stream << ".carbon_thunk";
  43. if (num_params !=
  44. static_cast<int>(callee_function_decl.getNumNonObjectParams())) {
  45. mangled_name_stream << num_params;
  46. }
  47. return mangled_name_stream.TakeStr();
  48. }
  49. // Returns whether the Carbon lowering for a parameter or return of this type is
  50. // known to match the C++ lowering.
  51. static auto IsSimpleAbiType(clang::ASTContext& ast_context,
  52. clang::QualType type, bool for_parameter) -> bool {
  53. if (type->isVoidType() || type->isPointerType()) {
  54. return true;
  55. }
  56. if (type->isReferenceType()) {
  57. if (for_parameter) {
  58. // A reference parameter has a simple ABI if it's a non-const lvalue
  59. // reference. Otherwise, we map it to pass-by-value, and it's only simple
  60. // if the type uses a pointer value representation.
  61. //
  62. // TODO: Check whether the pointee type maps to a Carbon type that uses a
  63. // pointer value representation, and treat it as simple if so.
  64. return type->isLValueReferenceType() &&
  65. !type->getPointeeType().isConstQualified();
  66. }
  67. // A reference return type is always mapped to a Carbon pointer, which uses
  68. // the same ABI rule as a C++ reference.
  69. return true;
  70. }
  71. if (const auto* enum_decl = type->getAsEnumDecl()) {
  72. // An enum type has a simple ABI if its underlying type does.
  73. type = enum_decl->getIntegerType();
  74. if (type.isNull()) {
  75. return false;
  76. }
  77. }
  78. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  79. if (builtin_type->isIntegerType()) {
  80. uint64_t type_size = ast_context.getIntWidth(type);
  81. return type_size == 32 || type_size == 64;
  82. }
  83. }
  84. return false;
  85. }
  86. namespace {
  87. // Information about the callee of a thunk.
  88. struct CalleeFunctionInfo {
  89. explicit CalleeFunctionInfo(clang::FunctionDecl* decl, int num_params)
  90. : decl(decl),
  91. num_params(num_params + decl->hasCXXExplicitFunctionObjectParameter()) {
  92. auto& ast_context = decl->getASTContext();
  93. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(decl);
  94. bool is_ctor = isa<clang::CXXConstructorDecl>(decl);
  95. has_object_parameter = method_decl && !method_decl->isStatic() && !is_ctor;
  96. if (has_object_parameter && method_decl->isImplicitObjectMemberFunction()) {
  97. implicit_object_parameter_type =
  98. method_decl->getFunctionObjectParameterReferenceType();
  99. }
  100. effective_return_type =
  101. is_ctor ? ast_context.getCanonicalTagType(method_decl->getParent())
  102. : decl->getReturnType();
  103. has_simple_return_type = IsSimpleAbiType(ast_context, effective_return_type,
  104. /*for_parameter=*/false);
  105. }
  106. // Returns whether this callee has an implicit `this` parameter.
  107. auto has_implicit_object_parameter() const -> bool {
  108. return !implicit_object_parameter_type.isNull();
  109. }
  110. // Returns whether this callee has an explicit `this` parameter.
  111. auto has_explicit_object_parameter() const -> bool {
  112. return has_object_parameter && !has_implicit_object_parameter();
  113. }
  114. // Returns the number of parameters the thunk should have.
  115. auto num_thunk_params() const -> unsigned {
  116. return has_implicit_object_parameter() + num_params +
  117. !has_simple_return_type;
  118. }
  119. // Returns the thunk parameter index corresponding to a given callee parameter
  120. // index.
  121. auto GetThunkParamIndex(unsigned callee_param_index) const -> unsigned {
  122. return has_implicit_object_parameter() + callee_param_index;
  123. }
  124. // Returns the thunk parameter index corresponding to the parameter that holds
  125. // the address of the return value.
  126. auto GetThunkReturnParamIndex() const -> unsigned {
  127. CARBON_CHECK(!has_simple_return_type);
  128. return has_implicit_object_parameter() + num_params;
  129. }
  130. // The callee function.
  131. clang::FunctionDecl* decl;
  132. // The number of explicit parameters to import. This may be less than the
  133. // number of parameters that the function has if default arguments are being
  134. // used.
  135. int num_params;
  136. // Whether the callee has an object parameter, which might be explicit or
  137. // implicit.
  138. bool has_object_parameter;
  139. // If the callee has an implicit object parameter, the type of that parameter,
  140. // which will always be a reference type. Otherwise a null type.
  141. clang::QualType implicit_object_parameter_type;
  142. // The return type that the callee has when viewed from Carbon. This is the
  143. // C++ return type, except that constructors return the class type in Carbon
  144. // and return void in Clang's AST.
  145. clang::QualType effective_return_type;
  146. // Whether the callee has a simple return type, that we can return directly.
  147. // If not, we'll return through an out parameter instead.
  148. bool has_simple_return_type;
  149. };
  150. } // namespace
  151. auto IsCppThunkRequired(Context& context, const SemIR::Function& function)
  152. -> bool {
  153. if (!function.clang_decl_id.has_value()) {
  154. return false;
  155. }
  156. const auto& decl_info = context.clang_decls().Get(function.clang_decl_id);
  157. auto* decl = cast<clang::FunctionDecl>(decl_info.key.decl);
  158. if (decl_info.key.num_params !=
  159. static_cast<int>(decl->getNumNonObjectParams())) {
  160. // We require a thunk if the number of parameters we want isn't all of them.
  161. // This happens if default arguments are in use, or (eventually) when
  162. // calling a varargs function.
  163. return true;
  164. }
  165. CalleeFunctionInfo callee_info(decl, decl_info.key.num_params);
  166. if (!callee_info.has_simple_return_type) {
  167. return true;
  168. }
  169. auto& ast_context = context.ast_context();
  170. if (callee_info.has_implicit_object_parameter() &&
  171. !IsSimpleAbiType(ast_context, callee_info.implicit_object_parameter_type,
  172. /*for_parameter=*/true)) {
  173. return true;
  174. }
  175. const auto* function_type =
  176. decl->getType()->castAs<clang::FunctionProtoType>();
  177. for (int i : llvm::seq(decl->getNumParams())) {
  178. if (!IsSimpleAbiType(ast_context, function_type->getParamType(i),
  179. /*for_parameter=*/true)) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. }
  185. // Given a pointer type, returns the corresponding _Nonnull-qualified pointer
  186. // type.
  187. static auto GetNonnullType(clang::ASTContext& ast_context,
  188. clang::QualType pointer_type) -> clang::QualType {
  189. return ast_context.getAttributedType(clang::NullabilityKind::NonNull,
  190. pointer_type, pointer_type);
  191. }
  192. // Given a type, returns the corresponding _Nonnull-qualified pointer type,
  193. // ignoring references.
  194. static auto GetNonNullablePointerType(clang::ASTContext& ast_context,
  195. clang::QualType type) {
  196. return GetNonnullType(ast_context,
  197. ast_context.getPointerType(type.getNonReferenceType()));
  198. }
  199. // Given the type of a callee parameter, returns the type to use for the
  200. // corresponding thunk parameter.
  201. static auto GetThunkParameterType(clang::ASTContext& ast_context,
  202. clang::QualType callee_type)
  203. -> clang::QualType {
  204. if (IsSimpleAbiType(ast_context, callee_type, /*for_parameter=*/true)) {
  205. return callee_type;
  206. }
  207. return GetNonNullablePointerType(ast_context, callee_type);
  208. }
  209. // Creates the thunk parameter types given the callee function.
  210. static auto BuildThunkParameterTypes(clang::ASTContext& ast_context,
  211. CalleeFunctionInfo callee_info)
  212. -> llvm::SmallVector<clang::QualType> {
  213. llvm::SmallVector<clang::QualType> thunk_param_types;
  214. thunk_param_types.reserve(callee_info.num_thunk_params());
  215. if (callee_info.has_implicit_object_parameter()) {
  216. thunk_param_types.push_back(callee_info.implicit_object_parameter_type);
  217. }
  218. const auto* function_type =
  219. callee_info.decl->getType()->castAs<clang::FunctionProtoType>();
  220. for (int i : llvm::seq(callee_info.num_params)) {
  221. thunk_param_types.push_back(
  222. GetThunkParameterType(ast_context, function_type->getParamType(i)));
  223. }
  224. if (!callee_info.has_simple_return_type) {
  225. thunk_param_types.push_back(GetNonNullablePointerType(
  226. ast_context, callee_info.effective_return_type));
  227. }
  228. CARBON_CHECK(thunk_param_types.size() == callee_info.num_thunk_params());
  229. return thunk_param_types;
  230. }
  231. // Returns the thunk parameters using the callee function parameter identifiers.
  232. static auto BuildThunkParameters(clang::ASTContext& ast_context,
  233. CalleeFunctionInfo callee_info,
  234. clang::FunctionDecl* thunk_function_decl)
  235. -> llvm::SmallVector<clang::ParmVarDecl*> {
  236. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  237. const auto* thunk_function_proto_type =
  238. thunk_function_decl->getType()->castAs<clang::FunctionProtoType>();
  239. llvm::SmallVector<clang::ParmVarDecl*> thunk_params;
  240. unsigned num_thunk_params = thunk_function_decl->getNumParams();
  241. thunk_params.reserve(num_thunk_params);
  242. if (callee_info.has_implicit_object_parameter()) {
  243. clang::ParmVarDecl* thunk_param =
  244. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  245. clang_loc, &ast_context.Idents.get("this"),
  246. thunk_function_proto_type->getParamType(0),
  247. nullptr, clang::SC_None, nullptr);
  248. thunk_params.push_back(thunk_param);
  249. }
  250. for (int i : llvm::seq(callee_info.num_params)) {
  251. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  252. ast_context, thunk_function_decl, clang_loc, clang_loc,
  253. callee_info.decl->getParamDecl(i)->getIdentifier(),
  254. thunk_function_proto_type->getParamType(
  255. callee_info.GetThunkParamIndex(i)),
  256. nullptr, clang::SC_None, nullptr);
  257. thunk_params.push_back(thunk_param);
  258. }
  259. if (!callee_info.has_simple_return_type) {
  260. clang::ParmVarDecl* thunk_param =
  261. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  262. clang_loc, &ast_context.Idents.get("return"),
  263. thunk_function_proto_type->getParamType(
  264. callee_info.GetThunkReturnParamIndex()),
  265. nullptr, clang::SC_None, nullptr);
  266. thunk_params.push_back(thunk_param);
  267. }
  268. CARBON_CHECK(thunk_params.size() == num_thunk_params);
  269. return thunk_params;
  270. }
  271. // Returns the thunk function declaration given the callee function and the
  272. // thunk parameter types.
  273. static auto CreateThunkFunctionDecl(
  274. Context& context, CalleeFunctionInfo callee_info,
  275. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  276. clang::ASTContext& ast_context = context.ast_context();
  277. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  278. clang::IdentifierInfo& identifier_info = ast_context.Idents.get(
  279. callee_info.decl->getNameAsString() + "__carbon_thunk");
  280. auto ext_proto_info = clang::FunctionProtoType::ExtProtoInfo();
  281. clang::QualType thunk_function_type = ast_context.getFunctionType(
  282. callee_info.has_simple_return_type ? callee_info.effective_return_type
  283. : ast_context.VoidTy,
  284. thunk_param_types, ext_proto_info);
  285. clang::DeclContext* decl_context = ast_context.getTranslationUnitDecl();
  286. // TODO: Thunks should not have external linkage, consider using `SC_Static`.
  287. clang::FunctionDecl* thunk_function_decl = clang::FunctionDecl::Create(
  288. ast_context, decl_context, clang_loc, clang_loc,
  289. clang::DeclarationName(&identifier_info), thunk_function_type,
  290. /*TInfo=*/nullptr, clang::SC_Extern);
  291. decl_context->addDecl(thunk_function_decl);
  292. thunk_function_decl->setParams(
  293. BuildThunkParameters(ast_context, callee_info, thunk_function_decl));
  294. // Set always_inline.
  295. thunk_function_decl->addAttr(
  296. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  297. // Set asm("<callee function mangled name>.carbon_thunk").
  298. thunk_function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
  299. ast_context,
  300. GenerateThunkMangledName(
  301. *context.sem_ir().clang_mangle_context(), *callee_info.decl,
  302. callee_info.num_params - callee_info.has_explicit_object_parameter()),
  303. clang_loc));
  304. // Set function declaration type source info.
  305. thunk_function_decl->setTypeSourceInfo(ast_context.getTrivialTypeSourceInfo(
  306. thunk_function_decl->getType(), clang_loc));
  307. return thunk_function_decl;
  308. }
  309. // Builds a reference to the given parameter thunk. If `type` is specified, that
  310. // is the callee parameter type that's being held by the parameter, and
  311. // conversions will be performed as necessary to recover a value of that type.
  312. static auto BuildThunkParamRef(clang::Sema& sema,
  313. clang::FunctionDecl* thunk_function_decl,
  314. unsigned thunk_index,
  315. clang::QualType type = clang::QualType())
  316. -> clang::Expr* {
  317. clang::ParmVarDecl* thunk_param =
  318. thunk_function_decl->getParamDecl(thunk_index);
  319. clang::SourceLocation clang_loc = thunk_param->getLocation();
  320. clang::Expr* call_arg = sema.BuildDeclRefExpr(
  321. thunk_param, thunk_param->getType().getNonReferenceType(),
  322. clang::VK_LValue, clang_loc);
  323. if (!type.isNull() && thunk_param->getType() != type) {
  324. clang::ExprResult deref_result =
  325. sema.BuildUnaryOp(nullptr, clang_loc, clang::UO_Deref, call_arg);
  326. CARBON_CHECK(deref_result.isUsable());
  327. call_arg = deref_result.get();
  328. }
  329. // Cast to an rvalue when initializing an rvalue reference. The validity of
  330. // the initialization of the reference should be validated by the caller of
  331. // the thunk.
  332. //
  333. // TODO: Consider inserting a cast to an rvalue in more cases. Note that we
  334. // currently pass pointers to non-temporary objects as the argument when
  335. // calling a thunk, so we'll need to either change that or generate
  336. // different thunks depending on whether we're moving from each parameter.
  337. if (!type.isNull() && type->isRValueReferenceType()) {
  338. call_arg = clang::ImplicitCastExpr::Create(
  339. sema.getASTContext(), call_arg->getType(), clang::CK_NoOp, call_arg,
  340. nullptr, clang::ExprValueKind::VK_XValue, clang::FPOptionsOverride());
  341. }
  342. return call_arg;
  343. }
  344. // Builds a reference to the parameter thunk parameter corresponding to the
  345. // given callee parameter index.
  346. static auto BuildParamRefForCalleeArg(clang::Sema& sema,
  347. clang::FunctionDecl* thunk_function_decl,
  348. CalleeFunctionInfo callee_info,
  349. unsigned callee_index) -> clang::Expr* {
  350. unsigned thunk_index = callee_info.GetThunkParamIndex(callee_index);
  351. return BuildThunkParamRef(
  352. sema, thunk_function_decl, thunk_index,
  353. callee_info.decl->getParamDecl(callee_index)->getType());
  354. }
  355. // Builds an argument list for the callee function by creating suitable uses of
  356. // the corresponding thunk parameters.
  357. static auto BuildCalleeArgs(clang::Sema& sema,
  358. clang::FunctionDecl* thunk_function_decl,
  359. CalleeFunctionInfo callee_info)
  360. -> llvm::SmallVector<clang::Expr*> {
  361. llvm::SmallVector<clang::Expr*> call_args;
  362. // The object parameter is always passed as `self`, not in the callee argument
  363. // list, so the first argument corresponds to the second parameter if there is
  364. // an explicit object parameter and the first parameter otherwise.
  365. int first_param = callee_info.has_explicit_object_parameter();
  366. call_args.reserve(callee_info.num_params - first_param);
  367. for (unsigned callee_index : llvm::seq(first_param, callee_info.num_params)) {
  368. call_args.push_back(BuildParamRefForCalleeArg(sema, thunk_function_decl,
  369. callee_info, callee_index));
  370. }
  371. return call_args;
  372. }
  373. // Builds the thunk function body which calls the callee function using the call
  374. // args and returns the callee function return value. Returns nullptr on
  375. // failure.
  376. static auto BuildThunkBody(clang::Sema& sema,
  377. clang::FunctionDecl* thunk_function_decl,
  378. CalleeFunctionInfo callee_info)
  379. -> clang::StmtResult {
  380. // TODO: Consider building a CompoundStmt holding our created statement to
  381. // make our result more closely resemble a real C++ function.
  382. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  383. // If the callee has an object parameter, build a member access expression as
  384. // the callee. Otherwise, build a regular reference to the function.
  385. clang::ExprResult callee;
  386. if (callee_info.has_object_parameter) {
  387. auto* object_param_ref =
  388. BuildThunkParamRef(sema, thunk_function_decl, 0,
  389. callee_info.has_explicit_object_parameter()
  390. ? callee_info.decl->getParamDecl(0)->getType()
  391. : clang::QualType());
  392. constexpr bool IsArrow = false;
  393. auto object =
  394. sema.PerformMemberExprBaseConversion(object_param_ref, IsArrow);
  395. if (object.isInvalid()) {
  396. return clang::StmtError();
  397. }
  398. callee = sema.BuildMemberExpr(
  399. object.get(), IsArrow, clang_loc, clang::NestedNameSpecifierLoc(),
  400. clang::SourceLocation(), callee_info.decl,
  401. clang::DeclAccessPair::make(callee_info.decl, clang::AS_public),
  402. /*HadMultipleCandidates=*/false, clang::DeclarationNameInfo(),
  403. sema.getASTContext().BoundMemberTy, clang::VK_PRValue,
  404. clang::OK_Ordinary);
  405. } else if (!isa<clang::CXXConstructorDecl>(callee_info.decl)) {
  406. callee =
  407. sema.BuildDeclRefExpr(callee_info.decl, callee_info.decl->getType(),
  408. clang::VK_PRValue, clang_loc);
  409. }
  410. if (callee.isInvalid()) {
  411. return clang::StmtError();
  412. }
  413. // Build the argument list.
  414. llvm::SmallVector<clang::Expr*> call_args =
  415. BuildCalleeArgs(sema, thunk_function_decl, callee_info);
  416. clang::ExprResult call;
  417. if (auto info = clang::getConstructorInfo(callee_info.decl);
  418. info.Constructor) {
  419. // In C++, there are no direct calls to constructors, only initialization,
  420. // so we need to type-check and build the call ourselves.
  421. auto type = sema.Context.getCanonicalTagType(
  422. cast<clang::CXXRecordDecl>(callee_info.decl->getParent()));
  423. llvm::SmallVector<clang::Expr*> converted_args;
  424. converted_args.reserve(call_args.size());
  425. if (sema.CompleteConstructorCall(info.Constructor, type, call_args,
  426. clang_loc, converted_args)) {
  427. return clang::StmtError();
  428. }
  429. call = sema.BuildCXXConstructExpr(
  430. clang_loc, type, callee_info.decl, info.Constructor, converted_args,
  431. false, false, false, false, clang::CXXConstructionKind::Complete,
  432. clang_loc);
  433. } else {
  434. call = sema.BuildCallExpr(nullptr, callee.get(), clang_loc, call_args,
  435. clang_loc);
  436. }
  437. if (!call.isUsable()) {
  438. return clang::StmtError();
  439. }
  440. if (callee_info.has_simple_return_type) {
  441. return sema.BuildReturnStmt(clang_loc, call.get());
  442. }
  443. auto* return_object_addr = BuildThunkParamRef(
  444. sema, thunk_function_decl, callee_info.GetThunkReturnParamIndex());
  445. auto return_type = callee_info.effective_return_type.getNonReferenceType();
  446. auto* return_type_info =
  447. sema.Context.getTrivialTypeSourceInfo(return_type, clang_loc);
  448. auto placement_new = sema.BuildCXXNew(
  449. clang_loc, /*UseGlobal=*/true, clang_loc, {return_object_addr}, clang_loc,
  450. /*TypeIdParens=*/clang::SourceRange(), return_type, return_type_info,
  451. /*ArraySize=*/std::nullopt, clang_loc, call.get());
  452. return sema.ActOnExprStmt(placement_new, /*DiscardedValue=*/true);
  453. }
  454. auto BuildCppThunk(Context& context, const SemIR::Function& callee_function)
  455. -> clang::FunctionDecl* {
  456. clang::FunctionDecl* callee_function_decl =
  457. context.clang_decls()
  458. .Get(callee_function.clang_decl_id)
  459. .key.decl->getAsFunction();
  460. CARBON_CHECK(callee_function_decl);
  461. CalleeFunctionInfo callee_info(
  462. callee_function_decl,
  463. context.inst_blocks().Get(callee_function.param_patterns_id).size());
  464. // Build the thunk function declaration.
  465. auto thunk_param_types =
  466. BuildThunkParameterTypes(context.ast_context(), callee_info);
  467. clang::FunctionDecl* thunk_function_decl =
  468. CreateThunkFunctionDecl(context, callee_info, thunk_param_types);
  469. // Build the thunk function body.
  470. clang::Sema& sema = context.clang_sema();
  471. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  472. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  473. clang::StmtResult body =
  474. BuildThunkBody(sema, thunk_function_decl, callee_info);
  475. sema.ActOnFinishFunctionBody(thunk_function_decl, body.get());
  476. if (body.isInvalid()) {
  477. return nullptr;
  478. }
  479. context.clang_sema().getASTConsumer().HandleTopLevelDecl(
  480. clang::DeclGroupRef(thunk_function_decl));
  481. return thunk_function_decl;
  482. }
  483. auto PerformCppThunkCall(Context& context, SemIR::LocId loc_id,
  484. SemIR::FunctionId callee_function_id,
  485. llvm::ArrayRef<SemIR::InstId> callee_arg_ids,
  486. SemIR::InstId thunk_callee_id) -> SemIR::InstId {
  487. auto& callee_function = context.functions().Get(callee_function_id);
  488. auto callee_function_params =
  489. context.inst_blocks().Get(callee_function.call_params_id);
  490. auto thunk_callee = GetCalleeAsFunction(context.sem_ir(), thunk_callee_id);
  491. auto& thunk_function = context.functions().Get(thunk_callee.function_id);
  492. auto thunk_function_params =
  493. context.inst_blocks().Get(thunk_function.call_params_id);
  494. // Whether we need to pass a return address to the thunk as a final argument.
  495. bool thunk_takes_return_address =
  496. callee_function.return_slot_pattern_id.has_value() &&
  497. !thunk_function.return_slot_pattern_id.has_value();
  498. // The number of arguments we should be acquiring in order to call the thunk.
  499. // This includes the return address parameter, if any.
  500. unsigned num_thunk_args =
  501. context.inst_blocks().Get(thunk_function.param_patterns_id).size();
  502. // The corresponding number of arguments that would be provided in a syntactic
  503. // call to the callee. This excludes the return slot.
  504. unsigned num_callee_args = num_thunk_args - thunk_takes_return_address;
  505. // Grab the return slot argument, if we were given one.
  506. auto return_slot_id = SemIR::InstId::None;
  507. if (callee_arg_ids.size() == num_callee_args + 1) {
  508. return_slot_id = callee_arg_ids.consume_back();
  509. }
  510. // If there's a return slot pattern, drop the corresponding parameter.
  511. // TODO: The parameter should probably only be created if the return pattern
  512. // actually needs a return address to be passed in.
  513. if (thunk_function.return_slot_pattern_id.has_value()) {
  514. thunk_function_params.consume_back();
  515. }
  516. if (callee_function.return_slot_pattern_id.has_value()) {
  517. callee_function_params.consume_back();
  518. }
  519. // We assume that the call parameters exactly match the parameter patterns for
  520. // both the thunk and the callee. This is currently guaranteed because we only
  521. // create trivial *ParamPatterns when importing a C++ function.
  522. CARBON_CHECK(num_callee_args == callee_function_params.size(), "{0} != {1}",
  523. num_callee_args, callee_function_params.size());
  524. CARBON_CHECK(num_callee_args == callee_arg_ids.size());
  525. CARBON_CHECK(num_thunk_args == thunk_function_params.size());
  526. // Build the thunk arguments by converting the callee arguments as needed.
  527. llvm::SmallVector<SemIR::InstId> thunk_arg_ids;
  528. thunk_arg_ids.reserve(num_thunk_args);
  529. for (auto [callee_param_inst_id, thunk_param_inst_id, callee_arg_id] :
  530. llvm::zip(callee_function_params, thunk_function_params,
  531. callee_arg_ids)) {
  532. SemIR::TypeId callee_param_type_id =
  533. context.insts().GetAs<SemIR::AnyParam>(callee_param_inst_id).type_id;
  534. SemIR::TypeId thunk_param_type_id =
  535. context.insts().GetAs<SemIR::AnyParam>(thunk_param_inst_id).type_id;
  536. SemIR::InstId arg_id = callee_arg_id;
  537. if (callee_param_type_id != thunk_param_type_id) {
  538. arg_id = Convert(context, loc_id, arg_id,
  539. {.kind = ConversionTarget::CppThunkRef,
  540. .type_id = callee_param_type_id});
  541. arg_id = AddInst<SemIR::AddrOf>(
  542. context, loc_id,
  543. {.type_id = GetPointerType(
  544. context, context.types().GetInstId(callee_param_type_id)),
  545. .lvalue_id = arg_id});
  546. arg_id =
  547. ConvertToValueOfType(context, loc_id, arg_id, thunk_param_type_id);
  548. }
  549. thunk_arg_ids.push_back(arg_id);
  550. }
  551. // Add an argument to hold the result of the call, if necessary.
  552. auto return_type_id = callee_function.GetDeclaredReturnType(context.sem_ir());
  553. if (thunk_takes_return_address) {
  554. // Create a temporary if the caller didn't provide a return slot.
  555. if (!return_slot_id.has_value()) {
  556. return_slot_id = AddInst<SemIR::TemporaryStorage>(
  557. context, loc_id, {.type_id = return_type_id});
  558. }
  559. auto arg_id = AddInst<SemIR::AddrOf>(
  560. context, loc_id,
  561. {.type_id = GetPointerType(
  562. context, context.types().GetInstId(
  563. context.insts().Get(return_slot_id).type_id())),
  564. .lvalue_id = return_slot_id});
  565. thunk_arg_ids.push_back(arg_id);
  566. } else if (return_slot_id.has_value()) {
  567. thunk_arg_ids.push_back(return_slot_id);
  568. }
  569. // Compute the return type of the call to the thunk.
  570. auto thunk_return_type_id =
  571. thunk_function.GetDeclaredReturnType(context.sem_ir());
  572. if (!thunk_return_type_id.has_value()) {
  573. CARBON_CHECK(thunk_takes_return_address || !return_type_id.has_value());
  574. thunk_return_type_id = GetTupleType(context, {});
  575. } else {
  576. CARBON_CHECK(thunk_return_type_id == return_type_id);
  577. }
  578. auto result_id = GetOrAddInst<SemIR::Call>(
  579. context, loc_id,
  580. {.type_id = thunk_return_type_id,
  581. .callee_id = thunk_callee_id,
  582. .args_id = context.inst_blocks().Add(thunk_arg_ids)});
  583. // Produce the result of the call, taking the value from the return storage.
  584. if (thunk_takes_return_address) {
  585. result_id = AddInst<SemIR::InPlaceInit>(context, loc_id,
  586. {.type_id = return_type_id,
  587. .src_id = result_id,
  588. .dest_id = return_slot_id});
  589. }
  590. return result_id;
  591. }
  592. } // namespace Carbon::Check