thunk.cpp 19 KB

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