thunk.cpp 29 KB

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