thunk.cpp 33 KB

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