thunk.cpp 28 KB

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