call.cpp 16 KB

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