thunk.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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/thunk.h"
  5. #include <utility>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/call.h"
  8. #include "toolchain/check/convert.h"
  9. #include "toolchain/check/cpp/operators.h"
  10. #include "toolchain/check/deferred_definition_worklist.h"
  11. #include "toolchain/check/diagnostic_helpers.h"
  12. #include "toolchain/check/function.h"
  13. #include "toolchain/check/generic.h"
  14. #include "toolchain/check/inst.h"
  15. #include "toolchain/check/member_access.h"
  16. #include "toolchain/check/name_ref.h"
  17. #include "toolchain/check/pattern.h"
  18. #include "toolchain/check/pattern_match.h"
  19. #include "toolchain/check/pointer_dereference.h"
  20. #include "toolchain/check/return.h"
  21. #include "toolchain/check/type.h"
  22. #include "toolchain/diagnostics/diagnostic.h"
  23. #include "toolchain/sem_ir/function.h"
  24. #include "toolchain/sem_ir/generic.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/pattern.h"
  28. #include "toolchain/sem_ir/typed_insts.h"
  29. namespace Carbon::Check {
  30. // Adds a pattern instruction for a thunk, copying the location from an existing
  31. // instruction.
  32. static auto RebuildPatternInst(Context& context, SemIR::InstId orig_inst_id,
  33. SemIR::Inst new_inst) -> SemIR::InstId {
  34. // Ensure we built the same kind of instruction. In particular, this ensures
  35. // that the location of the old instruction can be reused for the new one.
  36. CARBON_CHECK(context.insts().Get(orig_inst_id).kind() == new_inst.kind(),
  37. "Rebuilt pattern with the wrong kind: {0} -> {1}",
  38. context.insts().Get(orig_inst_id), new_inst);
  39. return AddPatternInst(context, SemIR::LocIdAndInst::UncheckedLoc(
  40. SemIR::LocId(orig_inst_id), new_inst));
  41. }
  42. // Wrapper to allow the type to be specified as a template argument for API
  43. // consistency with `AddInst`.
  44. template <typename InstT>
  45. static auto RebuildPatternInst(Context& context, SemIR::InstId orig_inst_id,
  46. InstT new_inst) -> SemIR::InstId {
  47. return RebuildPatternInst(context, orig_inst_id, SemIR::Inst(new_inst));
  48. }
  49. // Makes a copy of the given binding pattern, with its type adjusted to be
  50. // `new_pattern_type_id`.
  51. static auto CloneBindingPattern(Context& context, SemIR::InstId pattern_id,
  52. SemIR::AnyBindingPattern pattern,
  53. SemIR::TypeId new_pattern_type_id)
  54. -> SemIR::InstId {
  55. auto entity_name = context.entity_names().Get(pattern.entity_name_id);
  56. CARBON_CHECK((pattern.kind == SemIR::SymbolicBindingPattern::Kind) ==
  57. entity_name.bind_index().has_value());
  58. // Get the transformed type of the binding.
  59. if (new_pattern_type_id == SemIR::ErrorInst::TypeId) {
  60. return SemIR::ErrorInst::InstId;
  61. }
  62. auto type_inst_id = context.types()
  63. .GetAs<SemIR::PatternType>(new_pattern_type_id)
  64. .scrutinee_type_inst_id;
  65. auto type_id = context.types().GetTypeIdForTypeInstId(type_inst_id);
  66. auto type_expr_region_id = context.sem_ir().expr_regions().Add(
  67. {.block_ids = {SemIR::InstBlockId::Empty}, .result_id = type_inst_id});
  68. // Rebuild the binding pattern.
  69. return AddBindingPattern(context, SemIR::LocId(pattern_id),
  70. entity_name.name_id, type_id, type_expr_region_id,
  71. pattern.kind, entity_name.is_template)
  72. .pattern_id;
  73. }
  74. // Makes a copy of the given pattern instruction, substituting values from a
  75. // specific as needed. The resulting pattern behaves like a newly-created
  76. // pattern, so is suitable for running `CalleePatternMatch` against.
  77. static auto ClonePattern(Context& context, SemIR::SpecificId specific_id,
  78. SemIR::InstId pattern_id) -> SemIR::InstId {
  79. if (!pattern_id.has_value()) {
  80. return SemIR::InstId::None;
  81. }
  82. auto get_type = [&](SemIR::InstId inst_id) -> SemIR::TypeId {
  83. return SemIR::GetTypeOfInstInSpecific(context.sem_ir(), specific_id,
  84. inst_id);
  85. };
  86. auto pattern = context.insts().Get(pattern_id);
  87. // Decompose the pattern. The forms we allow for patterns in a function
  88. // parameter list are currently fairly restrictive.
  89. // Optional parameter pattern.
  90. auto [param, param_id] = context.insts().TryUnwrap(
  91. pattern, pattern_id, &SemIR::AnyParamPattern::subpattern_id);
  92. // Finally, either a binding pattern or a return slot pattern.
  93. auto new_pattern_id = SemIR::InstId::None;
  94. if (auto binding = pattern.TryAs<SemIR::AnyBindingPattern>()) {
  95. new_pattern_id = CloneBindingPattern(context, pattern_id, *binding,
  96. get_type(pattern_id));
  97. } else if (auto return_slot = pattern.TryAs<SemIR::ReturnSlotPattern>()) {
  98. new_pattern_id = RebuildPatternInst<SemIR::ReturnSlotPattern>(
  99. context, pattern_id,
  100. {.type_id = get_type(pattern_id),
  101. .type_inst_id = SemIR::TypeInstId::None});
  102. } else {
  103. CARBON_CHECK(pattern.Is<SemIR::ErrorInst>(),
  104. "Unexpected pattern {0} in function signature", pattern);
  105. return SemIR::ErrorInst::InstId;
  106. }
  107. // Rebuild parameter.
  108. if (param) {
  109. new_pattern_id = RebuildPatternInst<SemIR::AnyParamPattern>(
  110. context, param_id,
  111. {.kind = param->kind,
  112. .type_id = get_type(param_id),
  113. .subpattern_id = new_pattern_id,
  114. .index = param->index});
  115. }
  116. return new_pattern_id;
  117. }
  118. static auto ClonePatternBlock(Context& context, SemIR::SpecificId specific_id,
  119. SemIR::InstBlockId inst_block_id)
  120. -> SemIR::InstBlockId {
  121. if (!inst_block_id.has_value()) {
  122. return SemIR::InstBlockId::None;
  123. }
  124. return context.inst_blocks().Transform(
  125. inst_block_id, [&](SemIR::InstId inst_id) {
  126. return ClonePattern(context, specific_id, inst_id);
  127. });
  128. }
  129. static auto CloneTypeInstId(Context& context, SemIR::SpecificId specific_id,
  130. SemIR::TypeInstId inst_id) -> SemIR::TypeInstId {
  131. if (!inst_id.has_value()) {
  132. return SemIR::TypeInstId::None;
  133. }
  134. return context.types().GetAsTypeInstId(
  135. GetOrAddInst<SemIR::SpecificConstant>(context, SemIR::LocId(inst_id),
  136. {.type_id = SemIR::TypeType::TypeId,
  137. .inst_id = inst_id,
  138. .specific_id = specific_id}));
  139. }
  140. static auto CloneFunctionDecl(Context& context, SemIR::LocId loc_id,
  141. SemIR::FunctionId signature_id,
  142. SemIR::SpecificId signature_specific_id,
  143. SemIR::FunctionId callee_id)
  144. -> std::pair<SemIR::FunctionId, SemIR::InstId> {
  145. StartGenericDecl(context);
  146. const auto& signature = context.functions().Get(signature_id);
  147. // Clone the signature.
  148. context.pattern_block_stack().Push();
  149. auto implicit_param_patterns_id = ClonePatternBlock(
  150. context, signature_specific_id, signature.implicit_param_patterns_id);
  151. auto param_patterns_id = ClonePatternBlock(context, signature_specific_id,
  152. signature.param_patterns_id);
  153. auto return_patterns_id = ClonePatternBlock(context, signature_specific_id,
  154. signature.return_patterns_id);
  155. auto return_type_inst_id = CloneTypeInstId(context, signature_specific_id,
  156. signature.return_type_inst_id);
  157. auto self_param_id = FindSelfPattern(context, implicit_param_patterns_id);
  158. auto pattern_block_id = context.pattern_block_stack().Pop();
  159. // Perform callee-side pattern matching to rebuild the parameter list.
  160. context.inst_block_stack().Push();
  161. auto call_params_id =
  162. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  163. return_patterns_id);
  164. auto decl_block_id = context.inst_block_stack().Pop();
  165. // Create the `FunctionDecl` instruction.
  166. SemIR::FunctionDecl function_decl = {SemIR::TypeId::None,
  167. SemIR::FunctionId::None, decl_block_id};
  168. auto decl_id = AddPlaceholderInst(
  169. context, SemIR::LocIdAndInst::UncheckedLoc(loc_id, function_decl));
  170. auto generic_id = BuildGenericDecl(context, decl_id);
  171. // Create the `Function` object.
  172. auto& callee = context.functions().Get(callee_id);
  173. function_decl.function_id = context.functions().Add(
  174. SemIR::Function{{.name_id = signature.name_id,
  175. .parent_scope_id = callee.parent_scope_id,
  176. .generic_id = generic_id,
  177. .first_param_node_id = signature.first_param_node_id,
  178. .last_param_node_id = signature.last_param_node_id,
  179. .pattern_block_id = pattern_block_id,
  180. .implicit_param_patterns_id = implicit_param_patterns_id,
  181. .param_patterns_id = param_patterns_id,
  182. .is_extern = false,
  183. .extern_library_id = SemIR::LibraryNameId::None,
  184. .non_owning_decl_id = SemIR::InstId::None,
  185. .first_owning_decl_id = decl_id,
  186. .definition_id = decl_id},
  187. {.call_params_id = call_params_id,
  188. .return_type_inst_id = return_type_inst_id,
  189. .return_patterns_id = return_patterns_id,
  190. .virtual_modifier = callee.virtual_modifier,
  191. .virtual_index = callee.virtual_index,
  192. .self_param_id = self_param_id}});
  193. function_decl.type_id =
  194. GetFunctionType(context, function_decl.function_id,
  195. context.scope_stack().PeekSpecificId());
  196. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  197. return {function_decl.function_id, decl_id};
  198. }
  199. static auto HasDeclaredReturnType(Context& context,
  200. SemIR::FunctionId function_id) -> bool {
  201. return context.functions().Get(function_id).return_type_inst_id.has_value();
  202. }
  203. // Build an expression that names the value matched by a pattern.
  204. static auto BuildPatternRef(Context& context,
  205. llvm::ArrayRef<SemIR::InstId> arg_ids,
  206. SemIR::InstId pattern_id) -> SemIR::InstId {
  207. auto pattern = context.insts().Get(pattern_id);
  208. auto pattern_ref_id = SemIR::InstId::None;
  209. if (auto value_param = pattern.TryAs<SemIR::AnyParamPattern>();
  210. value_param.has_value() &&
  211. value_param->kind != SemIR::OutParamPattern::Kind) {
  212. pattern_ref_id = arg_ids[value_param->index.index];
  213. } else {
  214. if (pattern_id != SemIR::ErrorInst::InstId) {
  215. context.TODO(
  216. pattern_id,
  217. "don't know how to build reference to this pattern in thunk");
  218. }
  219. return SemIR::ErrorInst::InstId;
  220. }
  221. return pattern_ref_id;
  222. }
  223. auto PerformThunkCall(Context& context, SemIR::LocId loc_id,
  224. SemIR::FunctionId function_id,
  225. llvm::ArrayRef<SemIR::InstId> call_arg_ids,
  226. SemIR::InstId callee_id) -> SemIR::InstId {
  227. auto& function = context.functions().Get(function_id);
  228. llvm::SmallVector<SemIR::InstId> args;
  229. // If we have a self parameter, form `self.<callee_id>`.
  230. if (function.self_param_id.has_value()) {
  231. auto self_arg_id =
  232. BuildPatternRef(context, call_arg_ids, function.self_param_id);
  233. if (IsCppConstructorOrNonMethodOperator(context, callee_id)) {
  234. // When calling a C++ constructor to implement `Copy`, or calling a C++
  235. // non-method operator to implement a Carbon operator, the interface has a
  236. // `self` parameter but C++ models that parameter as an explicit argument
  237. // instead, so add the `self` to the argument list instead in that case.
  238. args.push_back(self_arg_id);
  239. } else {
  240. callee_id =
  241. PerformCompoundMemberAccess(context, loc_id, self_arg_id, callee_id);
  242. }
  243. }
  244. // Form an argument list.
  245. for (auto pattern_id :
  246. context.inst_blocks().Get(function.param_patterns_id)) {
  247. args.push_back(BuildPatternRef(context, call_arg_ids, pattern_id));
  248. }
  249. return PerformCall(context, loc_id, callee_id, args);
  250. }
  251. // Build a call to a function that forwards the arguments of the enclosing
  252. // function, for use when constructing a thunk.
  253. static auto BuildThunkCall(Context& context, SemIR::FunctionId function_id,
  254. SemIR::InstId callee_id) -> SemIR::InstId {
  255. auto& function = context.functions().Get(function_id);
  256. // Build a `NameRef` naming the callee, and a `SpecificConstant` if needed.
  257. auto loc_id = SemIR::LocId(callee_id);
  258. auto callee_type = context.types().GetAs<SemIR::FunctionType>(
  259. context.insts().Get(callee_id).type_id());
  260. callee_id = BuildNameRef(context, loc_id, function.name_id, callee_id,
  261. callee_type.specific_id);
  262. // Build a reference to each parameter for use as call arguments.
  263. llvm::SmallVector<SemIR::InstId> call_args;
  264. auto call_params = context.inst_blocks().Get(function.call_params_id);
  265. call_args.reserve(call_params.size());
  266. for (auto call_param_id : call_params) {
  267. // Use a pretty name for the `name_ref`. While it's suspicious to use a
  268. // pretty name in the IR like this, the only reason we include a name at all
  269. // here is to make the formatted SemIR more readable.
  270. auto call_param = context.insts().GetAs<SemIR::AnyParam>(call_param_id);
  271. call_args.push_back(BuildNameRef(context, SemIR::LocId(call_param_id),
  272. call_param.pretty_name_id, call_param_id,
  273. SemIR::SpecificId::None));
  274. }
  275. return PerformThunkCall(context, loc_id, function_id, call_args, callee_id);
  276. }
  277. // Given a declaration of a thunk and the function that it should call, build
  278. // the thunk body.
  279. static auto BuildThunkDefinition(Context& context,
  280. SemIR::FunctionId signature_id,
  281. SemIR::FunctionId function_id,
  282. SemIR::InstId thunk_id,
  283. SemIR::InstId callee_id) {
  284. // TODO: Improve the diagnostics produced here. Specifically, it would likely
  285. // be better for the primary error message to be that we tried to produce a
  286. // thunk because of a type mismatch, but couldn't, with notes explaining
  287. // why, rather than the primary error message being whatever went wrong
  288. // building the thunk.
  289. {
  290. // The check below produces diagnostics referring to the signature, so also
  291. // note the callee.
  292. Diagnostics::AnnotationScope annot_scope(
  293. &context.emitter(), [&](DiagnosticBuilder& builder) {
  294. CARBON_DIAGNOSTIC(ThunkCallee, Note,
  295. "while building thunk calling this function");
  296. builder.Note(callee_id, ThunkCallee);
  297. });
  298. CheckFunctionDefinitionSignature(context, function_id);
  299. }
  300. // TODO: This duplicates much of the handling for FunctionDefinitionStart and
  301. // FunctionDefinition parse nodes. Consider refactoring.
  302. context.scope_stack().PushForFunctionBody(thunk_id);
  303. context.inst_block_stack().Push();
  304. context.region_stack().PushRegion(context.inst_block_stack().PeekOrAdd());
  305. StartGenericDefinition(context,
  306. context.functions().Get(function_id).generic_id);
  307. // The checks below produce diagnostics pointing at the callee, so also note
  308. // the signature.
  309. Diagnostics::AnnotationScope annot_scope(
  310. &context.emitter(), [&](DiagnosticBuilder& builder) {
  311. CARBON_DIAGNOSTIC(
  312. ThunkSignature, Note,
  313. "while building thunk to match the signature of this function");
  314. builder.Note(context.functions().Get(signature_id).first_owning_decl_id,
  315. ThunkSignature);
  316. });
  317. auto call_id = BuildThunkCall(context, function_id, callee_id);
  318. if (HasDeclaredReturnType(context, function_id)) {
  319. BuildReturnWithExpr(context, SemIR::LocId(callee_id), call_id);
  320. } else {
  321. DiscardExpr(context, call_id);
  322. BuildReturnWithNoExpr(context, SemIR::LocId(callee_id));
  323. }
  324. context.inst_block_stack().Pop();
  325. context.scope_stack().Pop();
  326. auto& function = context.functions().Get(function_id);
  327. function.body_block_ids = context.region_stack().PopRegion();
  328. FinishGenericDefinition(context, function.generic_id);
  329. }
  330. auto BuildThunkDefinition(Context& context,
  331. DeferredDefinitionWorklist::DefineThunk&& task)
  332. -> void {
  333. context.scope_stack().Restore(std::move(task.scope));
  334. BuildThunkDefinition(context, task.info.signature_id, task.info.function_id,
  335. task.info.decl_id, task.info.callee_id);
  336. context.scope_stack().Pop();
  337. }
  338. auto BuildThunk(Context& context, SemIR::FunctionId signature_id,
  339. SemIR::SpecificId signature_specific_id,
  340. SemIR::InstId callee_id, bool defer_definition)
  341. -> SemIR::InstId {
  342. auto callee = SemIR::GetCalleeAsFunction(context.sem_ir(), callee_id);
  343. // Check whether we can use the given function without a thunk.
  344. // TODO: For virtual functions, we want different rules for checking `self`.
  345. // TODO: This is too strict; for example, we should not compare parameter
  346. // names here.
  347. if (CheckFunctionTypeMatches(
  348. context, context.functions().Get(callee.function_id),
  349. context.functions().Get(signature_id), signature_specific_id,
  350. /*check_syntax=*/false, /*check_self=*/true, /*diagnose=*/false)) {
  351. return callee_id;
  352. }
  353. // From P3763:
  354. // If the function in the interface does not have a return type, the
  355. // program is invalid if the function in the impl specifies a return type.
  356. //
  357. // Call into the redeclaration checking logic to produce a suitable error.
  358. //
  359. // TODO: Consider a different rule: always use an explicit return type for the
  360. // thunk, and always convert the result of the wrapped call to the return type
  361. // of the thunk.
  362. if (!HasDeclaredReturnType(context, signature_id) &&
  363. HasDeclaredReturnType(context, callee.function_id)) {
  364. bool success = CheckFunctionReturnTypeMatches(
  365. context, context.functions().Get(callee.function_id),
  366. context.functions().Get(signature_id), signature_specific_id);
  367. CARBON_CHECK(!success, "Return type unexpectedly matches");
  368. return SemIR::ErrorInst::InstId;
  369. }
  370. // Create a scope for the function's parameters and generic parameters.
  371. context.scope_stack().PushForDeclName();
  372. // We can't use the function directly. Build a thunk.
  373. // TODO: Check for and diagnose obvious reasons why this will fail, such as
  374. // arity mismatch, before trying to build the thunk.
  375. auto [function_id, thunk_id] =
  376. CloneFunctionDecl(context, SemIR::LocId(callee_id), signature_id,
  377. signature_specific_id, callee.function_id);
  378. // Track that this function is a thunk.
  379. context.functions().Get(function_id).SetThunk(callee_id);
  380. if (defer_definition) {
  381. // Register the thunk to be defined when we reach the end of the enclosing
  382. // deferred definition scope, for example an `impl` or `class` definition,
  383. // as if the thunk's body were written inline in this location.
  384. context.deferred_definition_worklist().SuspendThunkAndPush(
  385. context, {
  386. .signature_id = signature_id,
  387. .function_id = function_id,
  388. .decl_id = thunk_id,
  389. .callee_id = callee_id,
  390. });
  391. } else {
  392. BuildThunkDefinition(context, signature_id, function_id, thunk_id,
  393. callee_id);
  394. context.scope_stack().Pop();
  395. }
  396. return thunk_id;
  397. }
  398. } // namespace Carbon::Check