call.cpp 13 KB

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