call.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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/cpp/call.h"
  5. #include "clang/Sema/Sema.h"
  6. #include "toolchain/base/kind_switch.h"
  7. #include "toolchain/check/call.h"
  8. #include "toolchain/check/cpp/import.h"
  9. #include "toolchain/check/cpp/location.h"
  10. #include "toolchain/check/cpp/operators.h"
  11. #include "toolchain/check/cpp/overload_resolution.h"
  12. #include "toolchain/check/cpp/type_mapping.h"
  13. #include "toolchain/check/literal.h"
  14. #include "toolchain/sem_ir/function.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/typed_insts.h"
  17. namespace Carbon::Check {
  18. auto PerformCallToCppFunction(Context& context, SemIR::LocId loc_id,
  19. SemIR::CppOverloadSetId overload_set_id,
  20. SemIR::InstId self_id,
  21. llvm::ArrayRef<SemIR::InstId> arg_ids,
  22. bool is_operator_syntax) -> SemIR::InstId {
  23. SemIR::InstId callee_id = PerformCppOverloadResolution(
  24. context, loc_id, overload_set_id, self_id, arg_ids);
  25. SemIR::Callee callee = GetCallee(context.sem_ir(), callee_id);
  26. CARBON_KIND_SWITCH(callee) {
  27. case CARBON_KIND(SemIR::CalleeError _): {
  28. return SemIR::ErrorInst::InstId;
  29. }
  30. case CARBON_KIND(SemIR::CalleeFunction fn): {
  31. CARBON_CHECK(!fn.self_id.has_value());
  32. if (self_id.has_value()) {
  33. // Preserve the `self` argument from the original callee.
  34. fn.self_id = self_id;
  35. }
  36. return PerformCallToFunction(context, loc_id, callee_id, fn, arg_ids,
  37. is_operator_syntax);
  38. }
  39. case CARBON_KIND(SemIR::CalleeCppOverloadSet _): {
  40. CARBON_FATAL("overloads can't be recursive");
  41. }
  42. case CARBON_KIND(SemIR::CalleeNonFunction _): {
  43. CARBON_FATAL("overloads should produce functions");
  44. }
  45. }
  46. }
  47. // Synthesize a placeholder `void{}` template argument, that will never be a
  48. // valid argument for any template parameter. This is used in order to get Clang
  49. // to diagnose invalid template argument errors for us. The location of the
  50. // Carbon expression is used as the location of the C++ expression, so
  51. // Clang's diagnostics will point into the Carbon code.
  52. //
  53. // TODO: If Clang ever tries to print the type of the expression or to
  54. // pretty-print the expression itself, it would print the wrong thing. Currently
  55. // this doesn't appear to happen, but in principle it could. Ideally we'd add an
  56. // extension point to Clang to represent a "foreign expression" and use it here
  57. // instead of creating a bogus placeholder expression.
  58. static auto MakePlaceholderTemplateArg(Context& context, SemIR::InstId arg_id)
  59. -> clang::TemplateArgumentLoc {
  60. auto arg_loc = GetCppLocation(context, SemIR::LocId(arg_id));
  61. auto void_type = context.ast_context().VoidTy;
  62. auto* arg = new (context.ast_context()) clang::CXXScalarValueInitExpr(
  63. void_type,
  64. context.ast_context().getTrivialTypeSourceInfo(void_type, arg_loc),
  65. arg_loc);
  66. return clang::TemplateArgumentLoc(
  67. clang::TemplateArgument(arg, /*IsCanonical=*/false), arg);
  68. }
  69. // Converts an argument in a call to a C++ template name into a corresponding
  70. // clang template argument, given the template parameter it will be matched
  71. // against.
  72. static auto ConvertArgToTemplateArg(Context& context,
  73. const clang::NamedDecl* param_decl,
  74. SemIR::InstId arg_id)
  75. -> std::optional<clang::TemplateArgumentLoc> {
  76. if (isa<clang::TemplateTypeParmDecl>(param_decl)) {
  77. auto type = ExprAsType(context, SemIR::LocId(arg_id), arg_id);
  78. if (type.type_id == SemIR::ErrorInst::TypeId) {
  79. return std::nullopt;
  80. }
  81. auto clang_type = MapToCppType(context, type.type_id);
  82. if (clang_type.isNull()) {
  83. context.TODO(arg_id, "unsupported type used as template argument");
  84. return std::nullopt;
  85. }
  86. return clang::TemplateArgumentLoc(
  87. clang_type,
  88. context.ast_context().getTrivialTypeSourceInfo(
  89. clang_type, GetCppLocation(context, SemIR::LocId(arg_id))));
  90. }
  91. if (isa<clang::TemplateTemplateParmDecl>(param_decl)) {
  92. auto inst = context.sem_ir().insts().Get(arg_id);
  93. if (auto template_name_type =
  94. context.types().TryGetAs<SemIR::CppTemplateNameType>(
  95. inst.type_id())) {
  96. clang::TemplateName name(cast<clang::TemplateDecl>(
  97. context.clang_decls().Get(template_name_type->decl_id).key.decl));
  98. return clang::TemplateArgumentLoc(
  99. context.ast_context(), clang::TemplateArgument(name),
  100. /*TemplateKWLoc=*/clang::SourceLocation(),
  101. clang::NestedNameSpecifierLoc(),
  102. GetCppLocation(context, SemIR::LocId(arg_id)));
  103. }
  104. // TODO: Eventually we should also support passing Carbon generics as
  105. // template template arguments.
  106. return MakePlaceholderTemplateArg(context, arg_id);
  107. }
  108. if (const auto* non_type =
  109. dyn_cast<clang::NonTypeTemplateParmDecl>(param_decl)) {
  110. auto param_type = non_type->getType();
  111. // Handle integer parameters.
  112. if (param_type->isIntegerType()) {
  113. // Get the Carbon type corresponding to the parameter's Clang type.
  114. const auto type_expr =
  115. ImportCppType(context, SemIR::LocId(arg_id), param_type);
  116. // Try to convert the argument to the parameter type.
  117. const auto converted_inst_id =
  118. Convert(context, SemIR::LocId(arg_id), arg_id,
  119. {
  120. .kind = ConversionTarget::Value,
  121. .type_id = type_expr.type_id,
  122. });
  123. if (converted_inst_id == SemIR::ErrorInst::InstId) {
  124. return std::nullopt;
  125. }
  126. auto const_inst_id =
  127. context.constant_values().GetConstantInstId(converted_inst_id);
  128. if (const_inst_id.has_value()) {
  129. if (auto int_value =
  130. context.insts().TryGetAs<SemIR::IntValue>(const_inst_id)) {
  131. const auto& ap_int = context.ints().Get(int_value->int_id);
  132. const bool is_unsigned =
  133. !param_type->isSignedIntegerOrEnumerationType();
  134. auto aps_int =
  135. llvm::APSInt(ap_int, is_unsigned)
  136. .extOrTrunc(context.ast_context().getIntWidth(param_type));
  137. auto template_arg = clang::TemplateArgument(context.ast_context(),
  138. aps_int, param_type);
  139. // TODO: provide a better location.
  140. auto loc = clang::TemplateArgumentLocInfo();
  141. return clang::TemplateArgumentLoc(template_arg, loc);
  142. }
  143. }
  144. }
  145. // TODO: Support other types.
  146. context.TODO(arg_id,
  147. "unsupported argument type for non-type template parameter");
  148. return std::nullopt;
  149. }
  150. CARBON_FATAL("Unknown declaration kind for template parameter");
  151. }
  152. // Converts a call argument list into a Clang template argument list for a given
  153. // template. Returns true on success, or false if an error was diagnosed.
  154. static auto ConvertArgsToTemplateArgs(Context& context,
  155. clang::TemplateDecl* template_decl,
  156. llvm::ArrayRef<SemIR::InstId> arg_ids,
  157. clang::TemplateArgumentListInfo& arg_list)
  158. -> bool {
  159. for (auto* param_decl : template_decl->getTemplateParameters()->asArray()) {
  160. if (arg_ids.empty()) {
  161. return true;
  162. }
  163. // A parameter pack consumes all remaining arguments; otherwise, it consumes
  164. // a single argument.
  165. // TODO: Handle expanded template parameter packs, which have a known, fixed
  166. // arity.
  167. llvm::ArrayRef<SemIR::InstId> args_for_param =
  168. param_decl->isTemplateParameterPack() ? std::exchange(arg_ids, {})
  169. : arg_ids.consume_front();
  170. for (auto arg_id : args_for_param) {
  171. if (auto arg = ConvertArgToTemplateArg(context, param_decl, arg_id)) {
  172. arg_list.addArgument(*arg);
  173. } else {
  174. return false;
  175. }
  176. }
  177. }
  178. // If there are any remaining arguments, that's an error; convert them to
  179. // placeholder template arguments so that Clang will diagnose it for us.
  180. for (auto arg_id : arg_ids) {
  181. // Synthesize a placeholder `void{}` template argument.
  182. arg_list.addArgument(MakePlaceholderTemplateArg(context, arg_id));
  183. }
  184. return true;
  185. }
  186. // Given a template and an template argument list, builds a Carbon value
  187. // describing the corresponding C++ template-id.
  188. static auto BuildTemplateId(Context& context, SemIR::LocId loc_id,
  189. clang::SourceLocation loc,
  190. clang::TemplateDecl* template_decl,
  191. clang::TemplateArgumentListInfo& arg_list)
  192. -> SemIR::InstId {
  193. if (auto* var_template_decl =
  194. dyn_cast<clang::VarTemplateDecl>(template_decl)) {
  195. auto decl_result = context.clang_sema().CheckVarTemplateId(
  196. var_template_decl, /*TemplateLoc=*/clang::SourceLocation(), loc,
  197. arg_list, /*SetWrittenArgs=*/false);
  198. return decl_result.isInvalid()
  199. ? SemIR::ErrorInst::InstId
  200. : ImportCppDecl(context, loc_id,
  201. SemIR::ClangDeclKey::ForNonFunctionDecl(
  202. decl_result.get()));
  203. }
  204. if (auto* concept_decl = dyn_cast<clang::ConceptDecl>(template_decl)) {
  205. auto expr_result = context.clang_sema().CheckConceptTemplateId(
  206. clang::CXXScopeSpec(), /*TemplateKWLoc=*/clang::SourceLocation(),
  207. clang::DeclarationNameInfo(concept_decl->getDeclName(), loc),
  208. concept_decl, concept_decl, &arg_list);
  209. if (expr_result.isInvalid()) {
  210. return SemIR::ErrorInst::InstId;
  211. }
  212. auto* expr = expr_result.getAs<clang::ConceptSpecializationExpr>();
  213. return MakeBoolLiteral(context, loc_id,
  214. SemIR::BoolValue::From(expr->isSatisfied()));
  215. }
  216. clang::TemplateName template_name(template_decl);
  217. auto clang_type = context.clang_sema().CheckTemplateIdType(
  218. clang::ElaboratedTypeKeyword::None, template_name, loc, arg_list,
  219. /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
  220. if (clang_type.isNull()) {
  221. return SemIR::ErrorInst::InstId;
  222. }
  223. return ImportCppType(context, loc_id, clang_type).inst_id;
  224. }
  225. auto PerformCallToCppTemplateName(Context& context, SemIR::LocId loc_id,
  226. SemIR::ClangDeclId template_decl_id,
  227. llvm::ArrayRef<SemIR::InstId> arg_ids)
  228. -> SemIR::InstId {
  229. auto* template_decl = dyn_cast<clang::TemplateDecl>(
  230. context.clang_decls().Get(template_decl_id).key.decl);
  231. auto loc = GetCppLocation(context, loc_id);
  232. // Form a template argument list for this template.
  233. clang::TemplateArgumentListInfo arg_list(loc, loc);
  234. if (!ConvertArgsToTemplateArgs(context, template_decl, arg_ids, arg_list)) {
  235. return SemIR::ErrorInst::InstId;
  236. }
  237. return BuildTemplateId(context, loc_id, loc, template_decl, arg_list);
  238. }
  239. } // namespace Carbon::Check