call.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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/call.h"
  5. #include <optional>
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/context.h"
  8. #include "toolchain/check/control_flow.h"
  9. #include "toolchain/check/convert.h"
  10. #include "toolchain/check/cpp/overload_resolution.h"
  11. #include "toolchain/check/cpp/thunk.h"
  12. #include "toolchain/check/deduce.h"
  13. #include "toolchain/check/facet_type.h"
  14. #include "toolchain/check/function.h"
  15. #include "toolchain/check/import_ref.h"
  16. #include "toolchain/check/inst.h"
  17. #include "toolchain/check/name_ref.h"
  18. #include "toolchain/check/thunk.h"
  19. #include "toolchain/check/type.h"
  20. #include "toolchain/diagnostics/format_providers.h"
  21. #include "toolchain/sem_ir/builtin_function_kind.h"
  22. #include "toolchain/sem_ir/entity_with_params_base.h"
  23. #include "toolchain/sem_ir/function.h"
  24. #include "toolchain/sem_ir/ids.h"
  25. #include "toolchain/sem_ir/inst.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::Check {
  28. namespace {
  29. // Entity kinds, for diagnostics. Converted to an int for a select.
  30. enum class EntityKind : uint8_t {
  31. Function = 0,
  32. GenericClass = 1,
  33. GenericInterface = 2,
  34. };
  35. } // namespace
  36. // Resolves the callee expression in a call to a specific callee, or diagnoses
  37. // if no specific callee can be identified. This verifies the arity of the
  38. // callee and determines any compile-time arguments, but doesn't check that the
  39. // runtime arguments are convertible to the parameter types.
  40. //
  41. // `self_id` and `arg_ids` are the self argument and explicit arguments in the
  42. // call.
  43. //
  44. // Returns a `SpecificId` for the specific callee, `SpecificId::None` if the
  45. // callee is not generic, or `nullopt` if an error has been diagnosed.
  46. static auto ResolveCalleeInCall(Context& context, SemIR::LocId loc_id,
  47. const SemIR::EntityWithParamsBase& entity,
  48. EntityKind entity_kind_for_diagnostic,
  49. SemIR::SpecificId enclosing_specific_id,
  50. SemIR::InstId self_type_id,
  51. SemIR::InstId self_id,
  52. llvm::ArrayRef<SemIR::InstId> arg_ids)
  53. -> std::optional<SemIR::SpecificId> {
  54. // Check that the arity matches.
  55. auto params = context.inst_blocks().GetOrEmpty(entity.param_patterns_id);
  56. if (arg_ids.size() != params.size()) {
  57. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  58. "{0} argument{0:s} passed to "
  59. "{1:=0:function|=1:generic class|=2:generic interface}"
  60. " expecting {2} argument{2:s}",
  61. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect,
  62. Diagnostics::IntAsSelect);
  63. CARBON_DIAGNOSTIC(
  64. InCallToEntity, Note,
  65. "calling {0:=0:function|=1:generic class|=2:generic interface}"
  66. " declared here",
  67. Diagnostics::IntAsSelect);
  68. context.emitter()
  69. .Build(loc_id, CallArgCountMismatch, arg_ids.size(),
  70. static_cast<int>(entity_kind_for_diagnostic), params.size())
  71. .Note(entity.latest_decl_id(), InCallToEntity,
  72. static_cast<int>(entity_kind_for_diagnostic))
  73. .Emit();
  74. return std::nullopt;
  75. }
  76. // Perform argument deduction.
  77. auto specific_id = SemIR::SpecificId::None;
  78. if (entity.generic_id.has_value()) {
  79. specific_id = DeduceGenericCallArguments(
  80. context, loc_id, entity.generic_id, enclosing_specific_id, self_type_id,
  81. entity.implicit_param_patterns_id, entity.param_patterns_id, self_id,
  82. arg_ids);
  83. if (!specific_id.has_value()) {
  84. return std::nullopt;
  85. }
  86. }
  87. return specific_id;
  88. }
  89. // Performs a call where the callee is the name of a generic class, such as
  90. // `Vector(i32)`.
  91. static auto PerformCallToGenericClass(Context& context, SemIR::LocId loc_id,
  92. SemIR::ClassId class_id,
  93. SemIR::SpecificId enclosing_specific_id,
  94. llvm::ArrayRef<SemIR::InstId> arg_ids)
  95. -> SemIR::InstId {
  96. const auto& generic_class = context.classes().Get(class_id);
  97. auto callee_specific_id =
  98. ResolveCalleeInCall(context, loc_id, generic_class,
  99. EntityKind::GenericClass, enclosing_specific_id,
  100. /*self_type_id=*/SemIR::InstId::None,
  101. /*self_id=*/SemIR::InstId::None, arg_ids);
  102. if (!callee_specific_id) {
  103. return SemIR::ErrorInst::InstId;
  104. }
  105. return GetOrAddInst<SemIR::ClassType>(context, loc_id,
  106. {.type_id = SemIR::TypeType::TypeId,
  107. .class_id = class_id,
  108. .specific_id = *callee_specific_id});
  109. }
  110. // Performs a call where the callee is the name of a generic interface, such as
  111. // `AddWith(i32)`.
  112. static auto PerformCallToGenericInterface(
  113. Context& context, SemIR::LocId loc_id, SemIR::InterfaceId interface_id,
  114. SemIR::SpecificId enclosing_specific_id,
  115. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  116. const auto& interface = context.interfaces().Get(interface_id);
  117. auto callee_specific_id =
  118. ResolveCalleeInCall(context, loc_id, interface,
  119. EntityKind::GenericInterface, enclosing_specific_id,
  120. /*self_type_id=*/SemIR::InstId::None,
  121. /*self_id=*/SemIR::InstId::None, arg_ids);
  122. if (!callee_specific_id) {
  123. return SemIR::ErrorInst::InstId;
  124. }
  125. return GetOrAddInst(
  126. context, loc_id,
  127. FacetTypeFromInterface(context, interface_id, *callee_specific_id));
  128. }
  129. // Builds an appropriate specific function for the callee, also handling
  130. // instance binding.
  131. static auto BuildCalleeSpecificFunction(
  132. Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  133. SemIR::InstId callee_function_self_type_id,
  134. SemIR::SpecificId callee_specific_id) -> SemIR::InstId {
  135. auto generic_callee_id = callee_id;
  136. // Strip off a bound_method so that we can form a constant specific callee.
  137. auto bound_method = context.insts().TryGetAs<SemIR::BoundMethod>(callee_id);
  138. if (bound_method) {
  139. generic_callee_id = bound_method->function_decl_id;
  140. }
  141. // Form a specific callee.
  142. if (callee_function_self_type_id.has_value()) {
  143. // This is an associated function in an interface; the callee is the
  144. // specific function in the impl that corresponds to the specific function
  145. // we deduced.
  146. callee_id =
  147. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  148. SemIR::SpecificImplFunction{
  149. .type_id = GetSingletonType(
  150. context, SemIR::SpecificFunctionType::TypeInstId),
  151. .callee_id = generic_callee_id,
  152. .specific_id = callee_specific_id});
  153. } else {
  154. // This is a regular generic function. The callee is the specific function
  155. // we deduced.
  156. callee_id =
  157. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  158. SemIR::SpecificFunction{
  159. .type_id = GetSingletonType(
  160. context, SemIR::SpecificFunctionType::TypeInstId),
  161. .callee_id = generic_callee_id,
  162. .specific_id = callee_specific_id});
  163. }
  164. // Add the `self` argument back if there was one.
  165. if (bound_method) {
  166. callee_id =
  167. GetOrAddInst<SemIR::BoundMethod>(context, loc_id,
  168. {.type_id = bound_method->type_id,
  169. .object_id = bound_method->object_id,
  170. .function_decl_id = callee_id});
  171. }
  172. return callee_id;
  173. }
  174. // Returns the return type, with a scoped annotation for any diagnostics.
  175. static auto CheckCalleeFunctionReturnType(Context& context, SemIR::LocId loc_id,
  176. SemIR::FunctionId callee_function_id,
  177. SemIR::SpecificId callee_specific_id)
  178. -> SemIR::ReturnTypeInfo {
  179. auto& function = context.functions().Get(callee_function_id);
  180. Diagnostics::AnnotationScope annotate_diagnostics(
  181. &context.emitter(), [&](auto& builder) {
  182. CARBON_DIAGNOSTIC(IncompleteReturnTypeHere, Note,
  183. "return type declared here");
  184. builder.Note(function.return_slot_pattern_id, IncompleteReturnTypeHere);
  185. });
  186. return CheckFunctionReturnType(context, loc_id, function, callee_specific_id);
  187. }
  188. // Performs a call where the callee is a function.
  189. static auto PerformCallToFunction(Context& context, SemIR::LocId loc_id,
  190. SemIR::InstId callee_id,
  191. const SemIR::CalleeFunction& callee_function,
  192. llvm::ArrayRef<SemIR::InstId> arg_ids)
  193. -> SemIR::InstId {
  194. // If the callee is a generic function, determine the generic argument values
  195. // for the call.
  196. auto callee_specific_id = ResolveCalleeInCall(
  197. context, loc_id, context.functions().Get(callee_function.function_id),
  198. EntityKind::Function, callee_function.enclosing_specific_id,
  199. callee_function.self_type_id, callee_function.self_id, arg_ids);
  200. if (!callee_specific_id) {
  201. return SemIR::ErrorInst::InstId;
  202. }
  203. if (callee_specific_id->has_value()) {
  204. callee_id = BuildCalleeSpecificFunction(context, loc_id, callee_id,
  205. callee_function.self_type_id,
  206. *callee_specific_id);
  207. }
  208. // If there is a return slot, build storage for the result.
  209. SemIR::ReturnTypeInfo return_info = CheckCalleeFunctionReturnType(
  210. context, loc_id, callee_function.function_id, *callee_specific_id);
  211. SemIR::InstId return_slot_arg_id = SemIR::InstId::None;
  212. switch (return_info.init_repr.kind) {
  213. case SemIR::InitRepr::InPlace:
  214. case SemIR::InitRepr::Dependent:
  215. // Tentatively put storage for a temporary in the function's return slot.
  216. // This will be replaced if necessary when we perform initialization.
  217. return_slot_arg_id = AddInst<SemIR::TemporaryStorage>(
  218. context, loc_id, {.type_id = return_info.type_id});
  219. break;
  220. case SemIR::InitRepr::None:
  221. // For functions with an implicit return type, the return type is the
  222. // empty tuple type.
  223. if (!return_info.type_id.has_value()) {
  224. return_info.type_id = GetTupleType(context, {});
  225. }
  226. break;
  227. case SemIR::InitRepr::ByCopy:
  228. break;
  229. case SemIR::InitRepr::Incomplete:
  230. // Don't form an initializing expression with an incomplete type.
  231. // CheckFunctionReturnType will have diagnosed this for us if needed.
  232. return_info.type_id = SemIR::ErrorInst::TypeId;
  233. break;
  234. }
  235. auto& callee = context.functions().Get(callee_function.function_id);
  236. // Convert the arguments to match the parameters.
  237. auto converted_args_id =
  238. ConvertCallArgs(context, loc_id, callee_function.self_id, arg_ids,
  239. return_slot_arg_id, callee, *callee_specific_id);
  240. switch (callee.special_function_kind) {
  241. case SemIR::Function::SpecialFunctionKind::Thunk: {
  242. // If we're about to form a direct call to a thunk, inline it.
  243. LoadImportRef(context, callee.thunk_decl_id());
  244. // Name the thunk target within the enclosing scope of the thunk.
  245. auto thunk_ref_id =
  246. BuildNameRef(context, loc_id, callee.name_id, callee.thunk_decl_id(),
  247. callee_function.enclosing_specific_id);
  248. // This recurses back into `PerformCall`. However, we never form a thunk
  249. // to a thunk, so we only recurse once.
  250. return PerformThunkCall(context, loc_id, callee_function.function_id,
  251. context.inst_blocks().Get(converted_args_id),
  252. thunk_ref_id);
  253. }
  254. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  255. // This recurses back into `PerformCall`. However, we never form a C++
  256. // thunk to a C++ thunk, so we only recurse once.
  257. return PerformCppThunkCall(context, loc_id, callee_function.function_id,
  258. context.inst_blocks().Get(converted_args_id),
  259. callee.cpp_thunk_decl_id());
  260. }
  261. case SemIR::Function::SpecialFunctionKind::None:
  262. case SemIR::Function::SpecialFunctionKind::Builtin: {
  263. return GetOrAddInst<SemIR::Call>(context, loc_id,
  264. {.type_id = return_info.type_id,
  265. .callee_id = callee_id,
  266. .args_id = converted_args_id});
  267. }
  268. }
  269. }
  270. // Performs a call where the callee is a generic type. If it's not a generic
  271. // type, produces a diagnostic.
  272. static auto PerformCallToNonFunction(Context& context, SemIR::LocId loc_id,
  273. SemIR::InstId callee_id,
  274. llvm::ArrayRef<SemIR::InstId> arg_ids)
  275. -> SemIR::InstId {
  276. auto type_inst =
  277. context.types().GetAsInst(context.insts().Get(callee_id).type_id());
  278. CARBON_KIND_SWITCH(type_inst) {
  279. case CARBON_KIND(SemIR::GenericClassType generic_class): {
  280. return PerformCallToGenericClass(context, loc_id, generic_class.class_id,
  281. generic_class.enclosing_specific_id,
  282. arg_ids);
  283. }
  284. case CARBON_KIND(SemIR::GenericInterfaceType generic_interface): {
  285. return PerformCallToGenericInterface(
  286. context, loc_id, generic_interface.interface_id,
  287. generic_interface.enclosing_specific_id, arg_ids);
  288. }
  289. default: {
  290. CARBON_DIAGNOSTIC(CallToNonCallable, Error,
  291. "value of type {0} is not callable", TypeOfInstId);
  292. context.emitter().Emit(loc_id, CallToNonCallable, callee_id);
  293. return SemIR::ErrorInst::InstId;
  294. }
  295. }
  296. }
  297. auto PerformCall(Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  298. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  299. // Try treating the callee as a function first.
  300. auto callee = GetCallee(context.sem_ir(), callee_id);
  301. CARBON_KIND_SWITCH(callee) {
  302. case CARBON_KIND(SemIR::CalleeError _): {
  303. return SemIR::ErrorInst::InstId;
  304. }
  305. case CARBON_KIND(SemIR::CalleeFunction fn): {
  306. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids);
  307. }
  308. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  309. return PerformCallToNonFunction(context, loc_id, callee_id, arg_ids);
  310. }
  311. case CARBON_KIND(SemIR::CalleeCppOverloadSet overload): {
  312. callee_id = PerformCppOverloadResolution(context, loc_id,
  313. overload.cpp_overload_set_id,
  314. overload.self_id, arg_ids);
  315. auto overload_result = GetCallee(context.sem_ir(), callee_id);
  316. CARBON_KIND_SWITCH(overload_result) {
  317. case CARBON_KIND(SemIR::CalleeError _): {
  318. return SemIR::ErrorInst::InstId;
  319. }
  320. case CARBON_KIND(SemIR::CalleeFunction fn): {
  321. // Preserve the `self` argument from the original callee.
  322. CARBON_CHECK(!fn.self_id.has_value());
  323. fn.self_id = overload.self_id;
  324. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids);
  325. }
  326. case CARBON_KIND(SemIR::CalleeCppOverloadSet _): {
  327. CARBON_FATAL("overloads can't be recursive");
  328. }
  329. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  330. CARBON_FATAL("overloads should produce functions");
  331. }
  332. }
  333. }
  334. }
  335. }
  336. } // namespace Carbon::Check