call.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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/call.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. GenericNamedConstraint = 3,
  35. };
  36. } // namespace
  37. // Resolves the callee expression in a call to a specific callee, or diagnoses
  38. // if no specific callee can be identified. This verifies the arity of the
  39. // callee and determines any compile-time arguments, but doesn't check that the
  40. // runtime arguments are convertible to the parameter types.
  41. //
  42. // `self_id` and `arg_ids` are the self argument and explicit arguments in the
  43. // call.
  44. //
  45. // Returns a `SpecificId` for the specific callee, `SpecificId::None` if the
  46. // callee is not generic, or `nullopt` if an error has been diagnosed.
  47. static auto ResolveCalleeInCall(Context& context, SemIR::LocId loc_id,
  48. const SemIR::EntityWithParamsBase& entity,
  49. EntityKind entity_kind_for_diagnostic,
  50. SemIR::SpecificId enclosing_specific_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 "
  60. "interface|=3:generic constraint}"
  61. " expecting {2} argument{2:s}",
  62. Diagnostics::IntAsSelect, Diagnostics::IntAsSelect,
  63. Diagnostics::IntAsSelect);
  64. CARBON_DIAGNOSTIC(InCallToEntity, Note,
  65. "calling {0:=0:function|=1:generic class|=2:generic "
  66. "interface|=3:generic constraint}"
  67. " declared here",
  68. Diagnostics::IntAsSelect);
  69. context.emitter()
  70. .Build(loc_id, CallArgCountMismatch, arg_ids.size(),
  71. static_cast<int>(entity_kind_for_diagnostic), params.size())
  72. .Note(entity.latest_decl_id(), InCallToEntity,
  73. static_cast<int>(entity_kind_for_diagnostic))
  74. .Emit();
  75. return std::nullopt;
  76. }
  77. // Perform argument deduction.
  78. auto specific_id = SemIR::SpecificId::None;
  79. if (entity.generic_id.has_value()) {
  80. specific_id = DeduceGenericCallArguments(
  81. context, loc_id, entity.generic_id, enclosing_specific_id,
  82. entity.implicit_param_patterns_id, entity.param_patterns_id, self_id,
  83. arg_ids);
  84. if (!specific_id.has_value()) {
  85. return std::nullopt;
  86. }
  87. }
  88. return specific_id;
  89. }
  90. // Performs a call where the callee is the name of a generic class, such as
  91. // `Vector(i32)`.
  92. static auto PerformCallToGenericClass(Context& context, SemIR::LocId loc_id,
  93. SemIR::ClassId class_id,
  94. SemIR::SpecificId enclosing_specific_id,
  95. llvm::ArrayRef<SemIR::InstId> arg_ids)
  96. -> SemIR::InstId {
  97. const auto& generic_class = context.classes().Get(class_id);
  98. auto callee_specific_id =
  99. ResolveCalleeInCall(context, loc_id, generic_class,
  100. EntityKind::GenericClass, enclosing_specific_id,
  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. static auto EntityFromInterfaceOrNamedConstraint(
  111. Context& context, SemIR::InterfaceId interface_id)
  112. -> const SemIR::EntityWithParamsBase& {
  113. return context.interfaces().Get(interface_id);
  114. }
  115. static auto EntityFromInterfaceOrNamedConstraint(
  116. Context& context, SemIR::NamedConstraintId named_constraint_id)
  117. -> const SemIR::EntityWithParamsBase& {
  118. return context.named_constraints().Get(named_constraint_id);
  119. }
  120. // Performs a call where the callee is the name of a generic interface or named
  121. // constraint, such as `AddWith(i32)`.
  122. template <typename IdT>
  123. requires SameAsOneOf<IdT, SemIR::InterfaceId, SemIR::NamedConstraintId>
  124. static auto PerformCallToGenericInterfaceOrNamedConstaint(
  125. Context& context, SemIR::LocId loc_id, IdT id,
  126. SemIR::SpecificId enclosing_specific_id,
  127. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  128. const auto& entity = EntityFromInterfaceOrNamedConstraint(context, id);
  129. auto entity_kind_for_diagnostic = EntityKind::GenericInterface;
  130. if constexpr (std::same_as<IdT, SemIR::NamedConstraintId>) {
  131. entity_kind_for_diagnostic = EntityKind::GenericNamedConstraint;
  132. }
  133. auto callee_specific_id =
  134. ResolveCalleeInCall(context, loc_id, entity, entity_kind_for_diagnostic,
  135. enclosing_specific_id,
  136. /*self_id=*/SemIR::InstId::None, arg_ids);
  137. if (!callee_specific_id) {
  138. return SemIR::ErrorInst::InstId;
  139. }
  140. std::optional<SemIR::FacetType> facet_type;
  141. if constexpr (std::same_as<IdT, SemIR::InterfaceId>) {
  142. facet_type = FacetTypeFromInterface(context, id, *callee_specific_id);
  143. } else {
  144. facet_type = FacetTypeFromNamedConstraint(context, id, *callee_specific_id);
  145. }
  146. return GetOrAddInst(context, loc_id, *facet_type);
  147. }
  148. // Builds an appropriate specific function for the callee, also handling
  149. // instance binding.
  150. static auto BuildCalleeSpecificFunction(
  151. Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  152. SemIR::InstId callee_function_self_type_id,
  153. SemIR::SpecificId callee_specific_id) -> SemIR::InstId {
  154. auto generic_callee_id = callee_id;
  155. // Strip off a bound_method so that we can form a constant specific callee.
  156. auto bound_method = context.insts().TryGetAs<SemIR::BoundMethod>(callee_id);
  157. if (bound_method) {
  158. generic_callee_id = bound_method->function_decl_id;
  159. }
  160. // Form a specific callee.
  161. if (callee_function_self_type_id.has_value()) {
  162. // This is an associated function in an interface; the callee is the
  163. // specific function in the impl that corresponds to the specific function
  164. // we deduced.
  165. callee_id =
  166. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  167. SemIR::SpecificImplFunction{
  168. .type_id = GetSingletonType(
  169. context, SemIR::SpecificFunctionType::TypeInstId),
  170. .callee_id = generic_callee_id,
  171. .specific_id = callee_specific_id});
  172. } else {
  173. // This is a regular generic function. The callee is the specific function
  174. // we deduced.
  175. callee_id =
  176. GetOrAddInst(context, SemIR::LocId(generic_callee_id),
  177. SemIR::SpecificFunction{
  178. .type_id = GetSingletonType(
  179. context, SemIR::SpecificFunctionType::TypeInstId),
  180. .callee_id = generic_callee_id,
  181. .specific_id = callee_specific_id});
  182. }
  183. // Add the `self` argument back if there was one.
  184. if (bound_method) {
  185. callee_id =
  186. GetOrAddInst<SemIR::BoundMethod>(context, loc_id,
  187. {.type_id = bound_method->type_id,
  188. .object_id = bound_method->object_id,
  189. .function_decl_id = callee_id});
  190. }
  191. return callee_id;
  192. }
  193. auto PerformCallToFunction(Context& context, SemIR::LocId loc_id,
  194. SemIR::InstId callee_id,
  195. const SemIR::CalleeFunction& callee_function,
  196. llvm::ArrayRef<SemIR::InstId> arg_ids,
  197. bool is_desugared) -> SemIR::InstId {
  198. // If the callee is a generic function, determine the generic argument values
  199. // for the call.
  200. auto callee_specific_id = ResolveCalleeInCall(
  201. context, loc_id, context.functions().Get(callee_function.function_id),
  202. EntityKind::Function, callee_function.enclosing_specific_id,
  203. callee_function.self_id, arg_ids);
  204. if (!callee_specific_id) {
  205. return SemIR::ErrorInst::InstId;
  206. }
  207. if (callee_specific_id->has_value()) {
  208. callee_id = BuildCalleeSpecificFunction(context, loc_id, callee_id,
  209. callee_function.self_type_id,
  210. *callee_specific_id);
  211. }
  212. auto& callee = context.functions().Get(callee_function.function_id);
  213. auto return_type_id =
  214. callee.GetDeclaredReturnType(context.sem_ir(), *callee_specific_id);
  215. if (!return_type_id.has_value()) {
  216. return_type_id = GetTupleType(context, {});
  217. }
  218. auto return_arg_id = SemIR::InstId::None;
  219. if (callee.return_pattern_id.has_value()) {
  220. Diagnostics::AnnotationScope annotate_diagnostics(
  221. &context.emitter(), [&](auto& builder) {
  222. CARBON_DIAGNOSTIC(IncompleteReturnTypeHere, Note,
  223. "return type declared here");
  224. builder.Note(callee.return_pattern_id, IncompleteReturnTypeHere);
  225. });
  226. auto arg_type_id = CheckFunctionReturnPatternType(
  227. context, loc_id, callee.return_pattern_id, *callee_specific_id);
  228. if (arg_type_id == SemIR::ErrorInst::TypeId) {
  229. return_type_id = SemIR::ErrorInst::TypeId;
  230. }
  231. switch (SemIR::InitRepr::ForType(context.sem_ir(), arg_type_id).kind) {
  232. case SemIR::InitRepr::InPlace:
  233. case SemIR::InitRepr::Dependent:
  234. // Tentatively use storage for a temporary as the return argument.
  235. // This will be replaced if necessary when we perform initialization.
  236. return_arg_id = AddInst<SemIR::TemporaryStorage>(
  237. context, loc_id, {.type_id = arg_type_id});
  238. break;
  239. case SemIR::InitRepr::None:
  240. case SemIR::InitRepr::ByCopy:
  241. case SemIR::InitRepr::Incomplete:
  242. case SemIR::InitRepr::Abstract:
  243. return_arg_id = SemIR::InstId::None;
  244. break;
  245. }
  246. }
  247. // Convert the arguments to match the parameters.
  248. auto converted_args_id =
  249. ConvertCallArgs(context, loc_id, callee_function.self_id, arg_ids,
  250. return_arg_id, callee, *callee_specific_id, is_desugared);
  251. switch (callee.special_function_kind) {
  252. case SemIR::Function::SpecialFunctionKind::Thunk: {
  253. // If we're about to form a direct call to a thunk, inline it.
  254. LoadImportRef(context, callee.thunk_decl_id());
  255. // Name the thunk target within the enclosing scope of the thunk.
  256. auto thunk_ref_id =
  257. BuildNameRef(context, loc_id, callee.name_id, callee.thunk_decl_id(),
  258. callee_function.enclosing_specific_id);
  259. auto param_pattern_ids =
  260. context.inst_blocks().Get(context.functions()
  261. .Get(callee_function.function_id)
  262. .param_patterns_id);
  263. // This recurses back into `PerformCall`. However, we never form a thunk
  264. // to a thunk, so we only recurse once.
  265. return PerformThunkCall(
  266. context, loc_id, callee_function.function_id, param_pattern_ids,
  267. context.inst_blocks().Get(converted_args_id), thunk_ref_id);
  268. }
  269. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  270. return PerformCppThunkCall(context, loc_id, callee_function.function_id,
  271. context.inst_blocks().Get(converted_args_id),
  272. callee.cpp_thunk_decl_id());
  273. }
  274. case SemIR::Function::SpecialFunctionKind::None:
  275. case SemIR::Function::SpecialFunctionKind::Builtin:
  276. case SemIR::Function::SpecialFunctionKind::CoreWitness:
  277. case SemIR::Function::SpecialFunctionKind::CppThunk: {
  278. return GetOrAddInst<SemIR::Call>(context, loc_id,
  279. {.type_id = return_type_id,
  280. .callee_id = callee_id,
  281. .args_id = converted_args_id});
  282. }
  283. }
  284. }
  285. // Performs a call where the callee is a generic type. If it's not a generic
  286. // type, produces a diagnostic.
  287. static auto PerformCallToNonFunction(Context& context, SemIR::LocId loc_id,
  288. SemIR::InstId callee_id,
  289. llvm::ArrayRef<SemIR::InstId> arg_ids)
  290. -> SemIR::InstId {
  291. auto type_inst =
  292. context.types().GetAsInst(context.insts().Get(callee_id).type_id());
  293. CARBON_KIND_SWITCH(type_inst) {
  294. case CARBON_KIND(SemIR::CppTemplateNameType template_name): {
  295. return PerformCallToCppTemplateName(context, loc_id,
  296. template_name.decl_id, arg_ids);
  297. }
  298. case CARBON_KIND(SemIR::GenericClassType generic_class): {
  299. return PerformCallToGenericClass(context, loc_id, generic_class.class_id,
  300. generic_class.enclosing_specific_id,
  301. arg_ids);
  302. }
  303. case CARBON_KIND(SemIR::GenericInterfaceType generic_interface): {
  304. return PerformCallToGenericInterfaceOrNamedConstaint(
  305. context, loc_id, generic_interface.interface_id,
  306. generic_interface.enclosing_specific_id, arg_ids);
  307. }
  308. case CARBON_KIND(SemIR::GenericNamedConstraintType generic_constraint): {
  309. return PerformCallToGenericInterfaceOrNamedConstaint(
  310. context, loc_id, generic_constraint.named_constraint_id,
  311. generic_constraint.enclosing_specific_id, arg_ids);
  312. }
  313. default: {
  314. CARBON_DIAGNOSTIC(CallToNonCallable, Error,
  315. "value of type {0} is not callable", TypeOfInstId);
  316. context.emitter().Emit(loc_id, CallToNonCallable, callee_id);
  317. return SemIR::ErrorInst::InstId;
  318. }
  319. }
  320. }
  321. auto PerformCall(Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  322. llvm::ArrayRef<SemIR::InstId> arg_ids, bool is_desugared)
  323. -> SemIR::InstId {
  324. // Try treating the callee as a function first.
  325. auto callee = GetCallee(context.sem_ir(), callee_id);
  326. CARBON_KIND_SWITCH(callee) {
  327. case CARBON_KIND(SemIR::CalleeError _): {
  328. return SemIR::ErrorInst::InstId;
  329. }
  330. case CARBON_KIND(SemIR::CalleeFunction fn): {
  331. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids,
  332. is_desugared);
  333. }
  334. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  335. return PerformCallToNonFunction(context, loc_id, callee_id, arg_ids);
  336. }
  337. case CARBON_KIND(SemIR::CalleeCppOverloadSet overload): {
  338. return PerformCallToCppFunction(context, loc_id,
  339. overload.cpp_overload_set_id,
  340. overload.self_id, arg_ids, is_desugared);
  341. }
  342. }
  343. }
  344. } // namespace Carbon::Check