call.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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_operator_syntax) -> 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. llvm::SmallVector<SemIR::InstId, 1> return_arg_ids;
  219. for (auto return_pattern_id :
  220. context.inst_blocks().GetOrEmpty(callee.return_patterns_id)) {
  221. Diagnostics::AnnotationScope annotate_diagnostics(
  222. &context.emitter(), [&](auto& builder) {
  223. CARBON_DIAGNOSTIC(IncompleteReturnTypeHere, Note,
  224. "return type declared here");
  225. builder.Note(return_pattern_id, IncompleteReturnTypeHere);
  226. });
  227. auto arg_type_id = CheckFunctionReturnPatternType(
  228. context, loc_id, return_pattern_id, *callee_specific_id);
  229. if (arg_type_id == SemIR::ErrorInst::TypeId) {
  230. return_type_id = SemIR::ErrorInst::TypeId;
  231. }
  232. switch (SemIR::InitRepr::ForType(context.sem_ir(), arg_type_id).kind) {
  233. case SemIR::InitRepr::InPlace:
  234. case SemIR::InitRepr::Dependent:
  235. // Tentatively use storage for a temporary as the return argument.
  236. // This will be replaced if necessary when we perform initialization.
  237. return_arg_ids.push_back(AddInst<SemIR::TemporaryStorage>(
  238. context, loc_id, {.type_id = arg_type_id}));
  239. break;
  240. case SemIR::InitRepr::None:
  241. case SemIR::InitRepr::ByCopy:
  242. case SemIR::InitRepr::Incomplete:
  243. case SemIR::InitRepr::Abstract:
  244. return_arg_ids.push_back(SemIR::InstId::None);
  245. break;
  246. }
  247. }
  248. // Convert the arguments to match the parameters.
  249. auto converted_args_id = ConvertCallArgs(
  250. context, loc_id, callee_function.self_id, arg_ids, return_arg_ids, callee,
  251. *callee_specific_id, is_operator_syntax);
  252. switch (callee.special_function_kind) {
  253. case SemIR::Function::SpecialFunctionKind::Thunk: {
  254. // If we're about to form a direct call to a thunk, inline it.
  255. LoadImportRef(context, callee.thunk_decl_id());
  256. // Name the thunk target within the enclosing scope of the thunk.
  257. auto thunk_ref_id =
  258. BuildNameRef(context, loc_id, callee.name_id, callee.thunk_decl_id(),
  259. callee_function.enclosing_specific_id);
  260. // This recurses back into `PerformCall`. However, we never form a thunk
  261. // to a thunk, so we only recurse once.
  262. return PerformThunkCall(context, loc_id, callee_function.function_id,
  263. context.inst_blocks().Get(converted_args_id),
  264. thunk_ref_id);
  265. }
  266. case SemIR::Function::SpecialFunctionKind::HasCppThunk: {
  267. return PerformCppThunkCall(context, loc_id, callee_function.function_id,
  268. context.inst_blocks().Get(converted_args_id),
  269. callee.cpp_thunk_decl_id());
  270. }
  271. case SemIR::Function::SpecialFunctionKind::None:
  272. case SemIR::Function::SpecialFunctionKind::Builtin: {
  273. return GetOrAddInst<SemIR::Call>(context, loc_id,
  274. {.type_id = return_type_id,
  275. .callee_id = callee_id,
  276. .args_id = converted_args_id});
  277. }
  278. }
  279. }
  280. // Performs a call where the callee is a generic type. If it's not a generic
  281. // type, produces a diagnostic.
  282. static auto PerformCallToNonFunction(Context& context, SemIR::LocId loc_id,
  283. SemIR::InstId callee_id,
  284. llvm::ArrayRef<SemIR::InstId> arg_ids)
  285. -> SemIR::InstId {
  286. auto type_inst =
  287. context.types().GetAsInst(context.insts().Get(callee_id).type_id());
  288. CARBON_KIND_SWITCH(type_inst) {
  289. case CARBON_KIND(SemIR::CppTemplateNameType template_name): {
  290. return PerformCallToCppTemplateName(context, loc_id,
  291. template_name.decl_id, arg_ids);
  292. }
  293. case CARBON_KIND(SemIR::GenericClassType generic_class): {
  294. return PerformCallToGenericClass(context, loc_id, generic_class.class_id,
  295. generic_class.enclosing_specific_id,
  296. arg_ids);
  297. }
  298. case CARBON_KIND(SemIR::GenericInterfaceType generic_interface): {
  299. return PerformCallToGenericInterfaceOrNamedConstaint(
  300. context, loc_id, generic_interface.interface_id,
  301. generic_interface.enclosing_specific_id, arg_ids);
  302. }
  303. case CARBON_KIND(SemIR::GenericNamedConstraintType generic_constraint): {
  304. return PerformCallToGenericInterfaceOrNamedConstaint(
  305. context, loc_id, generic_constraint.named_constraint_id,
  306. generic_constraint.enclosing_specific_id, arg_ids);
  307. }
  308. default: {
  309. CARBON_DIAGNOSTIC(CallToNonCallable, Error,
  310. "value of type {0} is not callable", TypeOfInstId);
  311. context.emitter().Emit(loc_id, CallToNonCallable, callee_id);
  312. return SemIR::ErrorInst::InstId;
  313. }
  314. }
  315. }
  316. auto PerformCall(Context& context, SemIR::LocId loc_id, SemIR::InstId callee_id,
  317. llvm::ArrayRef<SemIR::InstId> arg_ids, bool is_operator_syntax)
  318. -> SemIR::InstId {
  319. // Try treating the callee as a function first.
  320. auto callee = GetCallee(context.sem_ir(), callee_id);
  321. CARBON_KIND_SWITCH(callee) {
  322. case CARBON_KIND(SemIR::CalleeError _): {
  323. return SemIR::ErrorInst::InstId;
  324. }
  325. case CARBON_KIND(SemIR::CalleeFunction fn): {
  326. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids,
  327. is_operator_syntax);
  328. }
  329. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  330. return PerformCallToNonFunction(context, loc_id, callee_id, arg_ids);
  331. }
  332. case CARBON_KIND(SemIR::CalleeCppOverloadSet overload): {
  333. return PerformCallToCppFunction(
  334. context, loc_id, overload.cpp_overload_set_id, overload.self_id,
  335. arg_ids, is_operator_syntax);
  336. }
  337. }
  338. }
  339. } // namespace Carbon::Check