thunk.cpp 27 KB

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