thunk.cpp 26 KB

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