thunk.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. break;
  98. }
  99. }
  100. }
  101. SemIR::TypeId return_type_id =
  102. function.GetDeclaredReturnType(context.sem_ir());
  103. if (return_type_id.has_value()) {
  104. if (return_type_id == SemIR::ErrorInst::TypeId) {
  105. return false;
  106. }
  107. thunk_required =
  108. thunk_required || IsThunkRequiredForType(context, return_type_id);
  109. }
  110. for (auto param_id :
  111. context.inst_blocks().GetOrEmpty(function.call_params_id)) {
  112. if (param_id == SemIR::ErrorInst::InstId) {
  113. return false;
  114. }
  115. thunk_required =
  116. thunk_required ||
  117. IsThunkRequiredForType(
  118. context, context.insts().GetAs<SemIR::AnyParam>(param_id).type_id);
  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 a type, returns the corresponding _Nonnull-qualified pointer type,
  209. // ignoring references.
  210. static auto GetNonNullablePointerType(clang::ASTContext& ast_context,
  211. clang::QualType type) {
  212. return GetNonnullType(ast_context,
  213. ast_context.getPointerType(type.getNonReferenceType()));
  214. }
  215. // Given the type of a callee parameter, returns the type to use for the
  216. // corresponding thunk parameter.
  217. static auto GetThunkParameterType(clang::ASTContext& ast_context,
  218. clang::QualType callee_type)
  219. -> clang::QualType {
  220. if (IsSimpleAbiType(ast_context, callee_type)) {
  221. return callee_type;
  222. }
  223. return GetNonNullablePointerType(ast_context, callee_type);
  224. }
  225. // Creates the thunk parameter types given the callee function.
  226. static auto BuildThunkParameterTypes(clang::ASTContext& ast_context,
  227. CalleeFunctionInfo callee_info)
  228. -> llvm::SmallVector<clang::QualType> {
  229. llvm::SmallVector<clang::QualType> thunk_param_types;
  230. thunk_param_types.reserve(callee_info.num_thunk_params());
  231. if (callee_info.has_implicit_object_parameter()) {
  232. thunk_param_types.push_back(
  233. GetNonnullType(ast_context, callee_info.implicit_this_type));
  234. }
  235. const auto* function_type =
  236. callee_info.decl->getType()->castAs<clang::FunctionProtoType>();
  237. for (int i : llvm::seq(callee_info.num_params)) {
  238. thunk_param_types.push_back(
  239. GetThunkParameterType(ast_context, function_type->getParamType(i)));
  240. }
  241. if (!callee_info.has_simple_return_type) {
  242. thunk_param_types.push_back(GetNonNullablePointerType(
  243. ast_context, callee_info.effective_return_type));
  244. }
  245. CARBON_CHECK(thunk_param_types.size() == callee_info.num_thunk_params());
  246. return thunk_param_types;
  247. }
  248. // Returns the thunk parameters using the callee function parameter identifiers.
  249. static auto BuildThunkParameters(clang::ASTContext& ast_context,
  250. CalleeFunctionInfo callee_info,
  251. clang::FunctionDecl* thunk_function_decl)
  252. -> llvm::SmallVector<clang::ParmVarDecl*> {
  253. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  254. const auto* thunk_function_proto_type =
  255. thunk_function_decl->getType()->castAs<clang::FunctionProtoType>();
  256. llvm::SmallVector<clang::ParmVarDecl*> thunk_params;
  257. unsigned num_thunk_params = thunk_function_decl->getNumParams();
  258. thunk_params.reserve(num_thunk_params);
  259. if (callee_info.has_implicit_object_parameter()) {
  260. clang::ParmVarDecl* thunk_param =
  261. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  262. clang_loc, &ast_context.Idents.get("this"),
  263. thunk_function_proto_type->getParamType(0),
  264. nullptr, clang::SC_None, nullptr);
  265. thunk_params.push_back(thunk_param);
  266. }
  267. for (int i : llvm::seq(callee_info.num_params)) {
  268. clang::ParmVarDecl* thunk_param = clang::ParmVarDecl::Create(
  269. ast_context, thunk_function_decl, clang_loc, clang_loc,
  270. callee_info.decl->getParamDecl(i)->getIdentifier(),
  271. thunk_function_proto_type->getParamType(
  272. callee_info.GetThunkParamIndex(i)),
  273. nullptr, clang::SC_None, nullptr);
  274. thunk_params.push_back(thunk_param);
  275. }
  276. if (!callee_info.has_simple_return_type) {
  277. clang::ParmVarDecl* thunk_param =
  278. clang::ParmVarDecl::Create(ast_context, thunk_function_decl, clang_loc,
  279. clang_loc, &ast_context.Idents.get("return"),
  280. thunk_function_proto_type->getParamType(
  281. callee_info.GetThunkReturnParamIndex()),
  282. nullptr, clang::SC_None, nullptr);
  283. thunk_params.push_back(thunk_param);
  284. }
  285. CARBON_CHECK(thunk_params.size() == num_thunk_params);
  286. return thunk_params;
  287. }
  288. // Returns the thunk function declaration given the callee function and the
  289. // thunk parameter types.
  290. static auto CreateThunkFunctionDecl(
  291. Context& context, CalleeFunctionInfo callee_info,
  292. llvm::ArrayRef<clang::QualType> thunk_param_types) -> clang::FunctionDecl* {
  293. clang::ASTContext& ast_context = context.ast_context();
  294. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  295. clang::IdentifierInfo& identifier_info = ast_context.Idents.get(
  296. callee_info.decl->getNameAsString() + "__carbon_thunk");
  297. auto ext_proto_info = clang::FunctionProtoType::ExtProtoInfo();
  298. clang::QualType thunk_function_type = ast_context.getFunctionType(
  299. callee_info.has_simple_return_type ? callee_info.effective_return_type
  300. : ast_context.VoidTy,
  301. thunk_param_types, ext_proto_info);
  302. clang::DeclContext* decl_context = ast_context.getTranslationUnitDecl();
  303. // TODO: Thunks should not have external linkage, consider using `SC_Static`.
  304. clang::FunctionDecl* thunk_function_decl = clang::FunctionDecl::Create(
  305. ast_context, decl_context, clang_loc, clang_loc,
  306. clang::DeclarationName(&identifier_info), thunk_function_type,
  307. /*TInfo=*/nullptr, clang::SC_Extern);
  308. decl_context->addDecl(thunk_function_decl);
  309. thunk_function_decl->setParams(
  310. BuildThunkParameters(ast_context, callee_info, thunk_function_decl));
  311. // Set always_inline.
  312. thunk_function_decl->addAttr(
  313. clang::AlwaysInlineAttr::CreateImplicit(ast_context));
  314. // Set asm("<callee function mangled name>.carbon_thunk").
  315. thunk_function_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
  316. ast_context,
  317. GenerateThunkMangledName(
  318. *context.sem_ir().clang_mangle_context(), *callee_info.decl,
  319. callee_info.num_params - callee_info.has_explicit_object_parameter()),
  320. clang_loc));
  321. // Set function declaration type source info.
  322. thunk_function_decl->setTypeSourceInfo(ast_context.getTrivialTypeSourceInfo(
  323. thunk_function_decl->getType(), clang_loc));
  324. return thunk_function_decl;
  325. }
  326. // Builds a reference to the given parameter thunk. If `type` is specified, that
  327. // is the callee parameter type that's being held by the parameter, and
  328. // conversions will be performed as necessary to recover a value of that type.
  329. static auto BuildThunkParamRef(clang::Sema& sema,
  330. clang::FunctionDecl* thunk_function_decl,
  331. unsigned thunk_index,
  332. clang::QualType type = clang::QualType())
  333. -> clang::Expr* {
  334. clang::ParmVarDecl* thunk_param =
  335. thunk_function_decl->getParamDecl(thunk_index);
  336. clang::SourceLocation clang_loc = thunk_param->getLocation();
  337. clang::Expr* call_arg = sema.BuildDeclRefExpr(
  338. thunk_param, thunk_param->getType().getNonReferenceType(),
  339. clang::VK_LValue, clang_loc);
  340. if (!type.isNull() && thunk_param->getType() != type) {
  341. clang::ExprResult deref_result =
  342. sema.BuildUnaryOp(nullptr, clang_loc, clang::UO_Deref, call_arg);
  343. CARBON_CHECK(deref_result.isUsable());
  344. // Cast to an rvalue when initializing an rvalue reference. The validity of
  345. // the initialization of the reference should be validated by the caller of
  346. // the thunk.
  347. //
  348. // TODO: Consider inserting a cast to an rvalue in more cases. Note that we
  349. // currently pass pointers to non-temporary objects as the argument when
  350. // calling a thunk, so we'll need to either change that or generate
  351. // different thunks depending on whether we're moving from each parameter.
  352. if (type->isRValueReferenceType()) {
  353. deref_result = clang::ImplicitCastExpr::Create(
  354. sema.getASTContext(), deref_result.get()->getType(), clang::CK_NoOp,
  355. deref_result.get(), nullptr, clang::ExprValueKind::VK_XValue,
  356. clang::FPOptionsOverride());
  357. }
  358. call_arg = deref_result.get();
  359. }
  360. return call_arg;
  361. }
  362. // Builds a reference to the parameter thunk parameter corresponding to the
  363. // given callee parameter index.
  364. static auto BuildParamRefForCalleeArg(clang::Sema& sema,
  365. clang::FunctionDecl* thunk_function_decl,
  366. CalleeFunctionInfo callee_info,
  367. unsigned callee_index) -> clang::Expr* {
  368. unsigned thunk_index = callee_info.GetThunkParamIndex(callee_index);
  369. return BuildThunkParamRef(
  370. sema, thunk_function_decl, thunk_index,
  371. callee_info.decl->getParamDecl(callee_index)->getType());
  372. }
  373. // Builds an argument list for the callee function by creating suitable uses of
  374. // the corresponding thunk parameters.
  375. static auto BuildCalleeArgs(clang::Sema& sema,
  376. clang::FunctionDecl* thunk_function_decl,
  377. CalleeFunctionInfo callee_info)
  378. -> llvm::SmallVector<clang::Expr*> {
  379. llvm::SmallVector<clang::Expr*> call_args;
  380. // The object parameter is always passed as `self`, not in the callee argument
  381. // list, so the first argument corresponds to the second parameter if there is
  382. // an explicit object parameter and the first parameter otherwise.
  383. int first_param = callee_info.has_explicit_object_parameter();
  384. call_args.reserve(callee_info.num_params - first_param);
  385. for (unsigned callee_index : llvm::seq(first_param, callee_info.num_params)) {
  386. call_args.push_back(BuildParamRefForCalleeArg(sema, thunk_function_decl,
  387. callee_info, callee_index));
  388. }
  389. return call_args;
  390. }
  391. // Builds the thunk function body which calls the callee function using the call
  392. // args and returns the callee function return value. Returns nullptr on
  393. // failure.
  394. static auto BuildThunkBody(clang::Sema& sema,
  395. clang::FunctionDecl* thunk_function_decl,
  396. CalleeFunctionInfo callee_info)
  397. -> clang::StmtResult {
  398. // TODO: Consider building a CompoundStmt holding our created statement to
  399. // make our result more closely resemble a real C++ function.
  400. clang::SourceLocation clang_loc = callee_info.decl->getLocation();
  401. // If the callee has an object parameter, build a member access expression as
  402. // the callee. Otherwise, build a regular reference to the function.
  403. clang::ExprResult callee;
  404. if (callee_info.has_object_parameter) {
  405. auto* object_param_ref =
  406. BuildThunkParamRef(sema, thunk_function_decl, 0,
  407. callee_info.has_explicit_object_parameter()
  408. ? callee_info.decl->getParamDecl(0)->getType()
  409. : clang::QualType());
  410. bool is_arrow = callee_info.has_implicit_object_parameter();
  411. auto object =
  412. sema.PerformMemberExprBaseConversion(object_param_ref, is_arrow);
  413. if (object.isInvalid()) {
  414. return clang::StmtError();
  415. }
  416. callee = sema.BuildMemberExpr(
  417. object.get(), is_arrow, clang_loc, clang::NestedNameSpecifierLoc(),
  418. clang::SourceLocation(), callee_info.decl,
  419. clang::DeclAccessPair::make(callee_info.decl, clang::AS_public),
  420. /*HadMultipleCandidates=*/false, clang::DeclarationNameInfo(),
  421. sema.getASTContext().BoundMemberTy, clang::VK_PRValue,
  422. clang::OK_Ordinary);
  423. } else if (!isa<clang::CXXConstructorDecl>(callee_info.decl)) {
  424. callee =
  425. sema.BuildDeclRefExpr(callee_info.decl, callee_info.decl->getType(),
  426. clang::VK_PRValue, clang_loc);
  427. }
  428. if (callee.isInvalid()) {
  429. return clang::StmtError();
  430. }
  431. // Build the argument list.
  432. llvm::SmallVector<clang::Expr*> call_args =
  433. BuildCalleeArgs(sema, thunk_function_decl, callee_info);
  434. clang::ExprResult call;
  435. if (auto info = clang::getConstructorInfo(callee_info.decl);
  436. info.Constructor) {
  437. // In C++, there are no direct calls to constructors, only initialization,
  438. // so we need to type-check and build the call ourselves.
  439. auto type = sema.Context.getCanonicalTagType(
  440. cast<clang::CXXRecordDecl>(callee_info.decl->getParent()));
  441. llvm::SmallVector<clang::Expr*> converted_args;
  442. converted_args.reserve(call_args.size());
  443. if (sema.CompleteConstructorCall(info.Constructor, type, call_args,
  444. clang_loc, converted_args)) {
  445. return clang::StmtError();
  446. }
  447. call = sema.BuildCXXConstructExpr(
  448. clang_loc, type, callee_info.decl, info.Constructor, converted_args,
  449. false, false, false, false, clang::CXXConstructionKind::Complete,
  450. clang_loc);
  451. } else {
  452. call = sema.BuildCallExpr(nullptr, callee.get(), clang_loc, call_args,
  453. clang_loc);
  454. }
  455. if (!call.isUsable()) {
  456. return clang::StmtError();
  457. }
  458. if (callee_info.has_simple_return_type) {
  459. return sema.BuildReturnStmt(clang_loc, call.get());
  460. }
  461. auto* return_object_addr = BuildThunkParamRef(
  462. sema, thunk_function_decl, callee_info.GetThunkReturnParamIndex());
  463. auto return_type = callee_info.effective_return_type.getNonReferenceType();
  464. auto* return_type_info =
  465. sema.Context.getTrivialTypeSourceInfo(return_type, clang_loc);
  466. auto placement_new = sema.BuildCXXNew(
  467. clang_loc, /*UseGlobal=*/true, clang_loc, {return_object_addr}, clang_loc,
  468. /*TypeIdParens=*/clang::SourceRange(), return_type, return_type_info,
  469. /*ArraySize=*/std::nullopt, clang_loc, call.get());
  470. return sema.ActOnExprStmt(placement_new, /*DiscardedValue=*/true);
  471. }
  472. auto BuildCppThunk(Context& context, const SemIR::Function& callee_function)
  473. -> clang::FunctionDecl* {
  474. clang::FunctionDecl* callee_function_decl =
  475. context.clang_decls()
  476. .Get(callee_function.clang_decl_id)
  477. .key.decl->getAsFunction();
  478. CARBON_CHECK(callee_function_decl);
  479. CalleeFunctionInfo callee_info(
  480. callee_function_decl,
  481. context.inst_blocks().Get(callee_function.param_patterns_id).size());
  482. // Build the thunk function declaration.
  483. auto thunk_param_types =
  484. BuildThunkParameterTypes(context.ast_context(), callee_info);
  485. clang::FunctionDecl* thunk_function_decl =
  486. CreateThunkFunctionDecl(context, callee_info, thunk_param_types);
  487. // Build the thunk function body.
  488. clang::Sema& sema = context.clang_sema();
  489. clang::Sema::ContextRAII context_raii(sema, thunk_function_decl);
  490. sema.ActOnStartOfFunctionDef(nullptr, thunk_function_decl);
  491. clang::StmtResult body =
  492. BuildThunkBody(sema, thunk_function_decl, callee_info);
  493. sema.ActOnFinishFunctionBody(thunk_function_decl, body.get());
  494. if (body.isInvalid()) {
  495. return nullptr;
  496. }
  497. return thunk_function_decl;
  498. }
  499. auto PerformCppThunkCall(Context& context, SemIR::LocId loc_id,
  500. SemIR::FunctionId callee_function_id,
  501. llvm::ArrayRef<SemIR::InstId> callee_arg_ids,
  502. SemIR::InstId thunk_callee_id) -> SemIR::InstId {
  503. auto& callee_function = context.functions().Get(callee_function_id);
  504. auto callee_function_params =
  505. context.inst_blocks().Get(callee_function.call_params_id);
  506. auto thunk_callee = GetCalleeAsFunction(context.sem_ir(), thunk_callee_id);
  507. auto& thunk_function = context.functions().Get(thunk_callee.function_id);
  508. auto thunk_function_params =
  509. context.inst_blocks().Get(thunk_function.call_params_id);
  510. // Whether we need to pass a return address to the thunk as a final argument.
  511. bool thunk_takes_return_address =
  512. callee_function.return_slot_pattern_id.has_value() &&
  513. !thunk_function.return_slot_pattern_id.has_value();
  514. // The number of arguments we should be acquiring in order to call the thunk.
  515. // This includes the return address parameter, if any.
  516. unsigned num_thunk_args =
  517. context.inst_blocks().Get(thunk_function.param_patterns_id).size();
  518. // The corresponding number of arguments that would be provided in a syntactic
  519. // call to the callee. This excludes the return slot.
  520. unsigned num_callee_args = num_thunk_args - thunk_takes_return_address;
  521. // Grab the return slot argument, if we were given one.
  522. auto return_slot_id = SemIR::InstId::None;
  523. if (callee_arg_ids.size() == num_callee_args + 1) {
  524. return_slot_id = callee_arg_ids.consume_back();
  525. }
  526. // If there's a return slot pattern, drop the corresponding parameter.
  527. // TODO: The parameter should probably only be created if the return pattern
  528. // actually needs a return address to be passed in.
  529. if (thunk_function.return_slot_pattern_id.has_value()) {
  530. thunk_function_params.consume_back();
  531. }
  532. if (callee_function.return_slot_pattern_id.has_value()) {
  533. callee_function_params.consume_back();
  534. }
  535. // We assume that the call parameters exactly match the parameter patterns for
  536. // both the thunk and the callee. This is currently guaranteed because we only
  537. // create trivial *ParamPatterns when importing a C++ function.
  538. CARBON_CHECK(num_callee_args == callee_function_params.size(), "{0} != {1}",
  539. num_callee_args, callee_function_params.size());
  540. CARBON_CHECK(num_callee_args == callee_arg_ids.size());
  541. CARBON_CHECK(num_thunk_args == thunk_function_params.size());
  542. // Build the thunk arguments by converting the callee arguments as needed.
  543. llvm::SmallVector<SemIR::InstId> thunk_arg_ids;
  544. thunk_arg_ids.reserve(num_thunk_args);
  545. for (auto [callee_param_inst_id, thunk_param_inst_id, callee_arg_id] :
  546. llvm::zip(callee_function_params, thunk_function_params,
  547. callee_arg_ids)) {
  548. SemIR::TypeId callee_param_type_id =
  549. context.insts().GetAs<SemIR::AnyParam>(callee_param_inst_id).type_id;
  550. SemIR::TypeId thunk_param_type_id =
  551. context.insts().GetAs<SemIR::AnyParam>(thunk_param_inst_id).type_id;
  552. SemIR::InstId arg_id = callee_arg_id;
  553. if (callee_param_type_id != thunk_param_type_id) {
  554. arg_id = Convert(context, loc_id, arg_id,
  555. {.kind = ConversionTarget::CppThunkRef,
  556. .type_id = callee_param_type_id});
  557. arg_id = AddInst<SemIR::AddrOf>(
  558. context, loc_id,
  559. {.type_id = GetPointerType(
  560. context, context.types().GetInstId(callee_param_type_id)),
  561. .lvalue_id = arg_id});
  562. arg_id =
  563. ConvertToValueOfType(context, loc_id, arg_id, thunk_param_type_id);
  564. }
  565. thunk_arg_ids.push_back(arg_id);
  566. }
  567. // Add an argument to hold the result of the call, if necessary.
  568. auto return_type_id = callee_function.GetDeclaredReturnType(context.sem_ir());
  569. if (thunk_takes_return_address) {
  570. // Create a temporary if the caller didn't provide a return slot.
  571. if (!return_slot_id.has_value()) {
  572. return_slot_id = AddInst<SemIR::TemporaryStorage>(
  573. context, loc_id, {.type_id = return_type_id});
  574. }
  575. auto arg_id = AddInst<SemIR::AddrOf>(
  576. context, loc_id,
  577. {.type_id = GetPointerType(
  578. context, context.types().GetInstId(
  579. context.insts().Get(return_slot_id).type_id())),
  580. .lvalue_id = return_slot_id});
  581. thunk_arg_ids.push_back(arg_id);
  582. }
  583. auto result_id = PerformCall(context, loc_id, thunk_callee_id, thunk_arg_ids);
  584. // Produce the result of the call, taking the value from the return storage.
  585. if (thunk_takes_return_address) {
  586. result_id = AddInst<SemIR::InPlaceInit>(context, loc_id,
  587. {.type_id = return_type_id,
  588. .src_id = result_id,
  589. .dest_id = return_slot_id});
  590. }
  591. return result_id;
  592. }
  593. } // namespace Carbon::Check