operators.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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/operators.h"
  5. #include "clang/Sema/Initialization.h"
  6. #include "clang/Sema/Overload.h"
  7. #include "clang/Sema/Sema.h"
  8. #include "toolchain/check/core_identifier.h"
  9. #include "toolchain/check/cpp/import.h"
  10. #include "toolchain/check/cpp/location.h"
  11. #include "toolchain/check/cpp/overload_resolution.h"
  12. #include "toolchain/check/cpp/type_mapping.h"
  13. #include "toolchain/check/inst.h"
  14. #include "toolchain/check/type.h"
  15. #include "toolchain/check/type_completion.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/typed_insts.h"
  18. namespace Carbon::Check {
  19. // Maps Carbon operator interface and operator names to Clang operator kinds.
  20. static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
  21. CoreIdentifier interface_name,
  22. CoreIdentifier op_name)
  23. -> std::optional<clang::OverloadedOperatorKind> {
  24. switch (interface_name) {
  25. // Unary operators.
  26. case CoreIdentifier::Destroy:
  27. case CoreIdentifier::As:
  28. case CoreIdentifier::ImplicitAs:
  29. case CoreIdentifier::UnsafeAs:
  30. case CoreIdentifier::Copy: {
  31. // TODO: Support destructors and conversions.
  32. return std::nullopt;
  33. }
  34. // Increment and decrement.
  35. case CoreIdentifier::Inc: {
  36. CARBON_CHECK(op_name == CoreIdentifier::Op);
  37. return clang::OO_PlusPlus;
  38. }
  39. case CoreIdentifier::Dec: {
  40. CARBON_CHECK(op_name == CoreIdentifier::Op);
  41. return clang::OO_MinusMinus;
  42. }
  43. // Arithmetic.
  44. case CoreIdentifier::Negate: {
  45. CARBON_CHECK(op_name == CoreIdentifier::Op);
  46. return clang::OO_Minus;
  47. }
  48. // Bitwise.
  49. case CoreIdentifier::BitComplement: {
  50. CARBON_CHECK(op_name == CoreIdentifier::Op);
  51. return clang::OO_Tilde;
  52. }
  53. // Binary operators.
  54. // Arithmetic operators.
  55. case CoreIdentifier::AddWith: {
  56. CARBON_CHECK(op_name == CoreIdentifier::Op);
  57. return clang::OO_Plus;
  58. }
  59. case CoreIdentifier::SubWith: {
  60. CARBON_CHECK(op_name == CoreIdentifier::Op);
  61. return clang::OO_Minus;
  62. }
  63. case CoreIdentifier::MulWith: {
  64. CARBON_CHECK(op_name == CoreIdentifier::Op);
  65. return clang::OO_Star;
  66. }
  67. case CoreIdentifier::DivWith: {
  68. CARBON_CHECK(op_name == CoreIdentifier::Op);
  69. return clang::OO_Slash;
  70. }
  71. case CoreIdentifier::ModWith: {
  72. CARBON_CHECK(op_name == CoreIdentifier::Op);
  73. return clang::OO_Percent;
  74. }
  75. // Bitwise operators.
  76. case CoreIdentifier::BitAndWith: {
  77. CARBON_CHECK(op_name == CoreIdentifier::Op);
  78. return clang::OO_Amp;
  79. }
  80. case CoreIdentifier::BitOrWith: {
  81. CARBON_CHECK(op_name == CoreIdentifier::Op);
  82. return clang::OO_Pipe;
  83. }
  84. case CoreIdentifier::BitXorWith: {
  85. CARBON_CHECK(op_name == CoreIdentifier::Op);
  86. return clang::OO_Caret;
  87. }
  88. case CoreIdentifier::LeftShiftWith: {
  89. CARBON_CHECK(op_name == CoreIdentifier::Op);
  90. return clang::OO_LessLess;
  91. }
  92. case CoreIdentifier::RightShiftWith: {
  93. CARBON_CHECK(op_name == CoreIdentifier::Op);
  94. return clang::OO_GreaterGreater;
  95. }
  96. // Assignment.
  97. case CoreIdentifier::AssignWith: {
  98. // TODO: This is not yet reached because we don't use the `AssignWith`
  99. // interface for assignment yet.
  100. CARBON_CHECK(op_name == CoreIdentifier::Op);
  101. return clang::OO_Equal;
  102. }
  103. // Compound assignment arithmetic operators.
  104. case CoreIdentifier::AddAssignWith: {
  105. CARBON_CHECK(op_name == CoreIdentifier::Op);
  106. return clang::OO_PlusEqual;
  107. }
  108. case CoreIdentifier::SubAssignWith: {
  109. CARBON_CHECK(op_name == CoreIdentifier::Op);
  110. return clang::OO_MinusEqual;
  111. }
  112. case CoreIdentifier::MulAssignWith: {
  113. CARBON_CHECK(op_name == CoreIdentifier::Op);
  114. return clang::OO_StarEqual;
  115. }
  116. case CoreIdentifier::DivAssignWith: {
  117. CARBON_CHECK(op_name == CoreIdentifier::Op);
  118. return clang::OO_SlashEqual;
  119. }
  120. case CoreIdentifier::ModAssignWith: {
  121. CARBON_CHECK(op_name == CoreIdentifier::Op);
  122. return clang::OO_PercentEqual;
  123. }
  124. // Compound assignment bitwise operators.
  125. case CoreIdentifier::BitAndAssignWith: {
  126. CARBON_CHECK(op_name == CoreIdentifier::Op);
  127. return clang::OO_AmpEqual;
  128. }
  129. case CoreIdentifier::BitOrAssignWith: {
  130. CARBON_CHECK(op_name == CoreIdentifier::Op);
  131. return clang::OO_PipeEqual;
  132. }
  133. case CoreIdentifier::BitXorAssignWith: {
  134. CARBON_CHECK(op_name == CoreIdentifier::Op);
  135. return clang::OO_CaretEqual;
  136. }
  137. case CoreIdentifier::LeftShiftAssignWith: {
  138. CARBON_CHECK(op_name == CoreIdentifier::Op);
  139. return clang::OO_LessLessEqual;
  140. }
  141. case CoreIdentifier::RightShiftAssignWith: {
  142. CARBON_CHECK(op_name == CoreIdentifier::Op);
  143. return clang::OO_GreaterGreaterEqual;
  144. }
  145. // Relational operators.
  146. case CoreIdentifier::EqWith: {
  147. if (op_name == CoreIdentifier::Equal) {
  148. return clang::OO_EqualEqual;
  149. }
  150. CARBON_CHECK(op_name == CoreIdentifier::NotEqual);
  151. return clang::OO_ExclaimEqual;
  152. }
  153. case CoreIdentifier::OrderedWith: {
  154. switch (op_name) {
  155. case CoreIdentifier::Less:
  156. return clang::OO_Less;
  157. case CoreIdentifier::Greater:
  158. return clang::OO_Greater;
  159. case CoreIdentifier::LessOrEquivalent:
  160. return clang::OO_LessEqual;
  161. case CoreIdentifier::GreaterOrEquivalent:
  162. return clang::OO_GreaterEqual;
  163. default:
  164. CARBON_FATAL("Unexpected OrderedWith op `{0}`", op_name);
  165. }
  166. }
  167. // Array indexing.
  168. case CoreIdentifier::IndexWith: {
  169. CARBON_CHECK(op_name == CoreIdentifier::At);
  170. return clang::OO_Subscript;
  171. }
  172. default: {
  173. context.TODO(loc_id, llvm::formatv("Unsupported operator interface `{0}`",
  174. interface_name));
  175. return std::nullopt;
  176. }
  177. }
  178. }
  179. static auto LookupCppConversion(Context& context, SemIR::LocId loc_id,
  180. SemIR::InstId source_id,
  181. SemIR::TypeId dest_type_id, bool allow_explicit)
  182. -> SemIR::InstId {
  183. auto dest_type = MapToCppType(context, dest_type_id);
  184. if (dest_type.isNull()) {
  185. return SemIR::InstId::None;
  186. }
  187. auto* arg_expr = InventClangArg(context, source_id);
  188. // If we can't map the argument, we can't perform the conversion.
  189. if (!arg_expr) {
  190. return SemIR::InstId::None;
  191. }
  192. auto loc = GetCppLocation(context, loc_id);
  193. // Form a Clang initialization sequence.
  194. auto& sema = context.clang_sema();
  195. clang::InitializedEntity entity =
  196. clang::InitializedEntity::InitializeTemporary(dest_type);
  197. clang::InitializationKind kind =
  198. allow_explicit ? clang::InitializationKind::CreateDirect(
  199. loc, /*LParenLoc=*/clang::SourceLocation(),
  200. /*RParenLoc=*/clang::SourceLocation())
  201. : clang::InitializationKind::CreateCopy(
  202. loc, /*EqualLoc=*/clang::SourceLocation());
  203. clang::MultiExprArg args(arg_expr);
  204. // `(a, b) as T` uses `T{a, b}`, not `T({a, b})`. The latter would introduce
  205. // a redundant extra copy.
  206. // TODO: We need to communicate this back to the caller so they know to call
  207. // the constructor with an exploded argument list somehow.
  208. if (allow_explicit && isa<clang::InitListExpr>(arg_expr)) {
  209. kind = clang::InitializationKind::CreateDirectList(loc);
  210. }
  211. clang::InitializationSequence init(sema, entity, kind, args);
  212. if (init.Failed()) {
  213. // TODO: Are there initialization failures that we should translate into
  214. // errors rather than a missing conversion?
  215. return SemIR::InstId::None;
  216. }
  217. // Scan the steps looking for user-defined conversions. For now we just find
  218. // and return the first such conversion function. We skip over standard
  219. // conversions; we'll perform those using the Carbon rules as part of calling
  220. // the C++ conversion function.
  221. for (const auto& step : init.steps()) {
  222. switch (step.Kind) {
  223. case clang::InitializationSequence::SK_UserConversion:
  224. case clang::InitializationSequence::SK_ConstructorInitialization: {
  225. if (auto* ctor =
  226. dyn_cast<clang::CXXConstructorDecl>(step.Function.Function);
  227. ctor && ctor->isCopyOrMoveConstructor()) {
  228. // Skip copy / move constructor calls. They shouldn't be performed
  229. // this way because they're not considered conversions in Carbon, and
  230. // will frequently lead to infinite recursion because we'll end up
  231. // back here when attempting to convert the argument.
  232. continue;
  233. }
  234. if (sema.DiagnoseUseOfOverloadedDecl(step.Function.Function, loc)) {
  235. return SemIR::ErrorInst::InstId;
  236. }
  237. sema.MarkFunctionReferenced(loc, step.Function.Function);
  238. auto result_id = ImportCppFunctionDecl(
  239. context, loc_id, step.Function.Function,
  240. // If this is a constructor, the source is passed as an argument;
  241. // otherwise, this is a conversion function and the source is passed
  242. // as `self`.
  243. isa<clang::CXXConstructorDecl>(step.Function.Function) ? 1 : 0);
  244. if (auto fn_decl = context.insts().TryGetAsWithId<SemIR::FunctionDecl>(
  245. result_id)) {
  246. CheckCppOverloadAccess(context, loc_id, step.Function.FoundDecl,
  247. fn_decl->inst_id);
  248. } else {
  249. CARBON_CHECK(result_id == SemIR::ErrorInst::InstId);
  250. }
  251. // TODO: There may be other conversions later in the sequence that we
  252. // need to model; we've only applied the first one here.
  253. return result_id;
  254. }
  255. case clang::InitializationSequence::SK_ConversionSequence:
  256. case clang::InitializationSequence::SK_ConversionSequenceNoNarrowing: {
  257. // Implicit conversions are handled by the normal Carbon conversion
  258. // logic, so we ignore them here.
  259. continue;
  260. }
  261. default: {
  262. // TODO: Handle other kinds of initialization steps. For now we assume
  263. // they will be handled by our function call logic and we can skip them.
  264. RawStringOstream os;
  265. os << "Unsupported initialization sequence:\n";
  266. init.dump(os);
  267. context.TODO(loc_id, os.TakeStr());
  268. return SemIR::ErrorInst::InstId;
  269. }
  270. }
  271. }
  272. return SemIR::InstId::None;
  273. }
  274. auto LookupCppOperator(Context& context, SemIR::LocId loc_id, Operator op,
  275. llvm::ArrayRef<SemIR::InstId> arg_ids) -> SemIR::InstId {
  276. // Register an annotation scope to flush any Clang diagnostics when we return.
  277. // This is important to ensure that Clang diagnostics are properly interleaved
  278. // with Carbon diagnostics.
  279. Diagnostics::AnnotationScope annotate_diagnostics(&context.emitter(),
  280. [](auto& /*builder*/) {});
  281. // Handle `ImplicitAs` and `As`.
  282. if (op.interface_name == CoreIdentifier::ImplicitAs ||
  283. op.interface_name == CoreIdentifier::As) {
  284. if (op.interface_args_ref.size() != 1 || arg_ids.size() != 1) {
  285. return SemIR::InstId::None;
  286. }
  287. // The argument is the destination type for both interfaces.
  288. auto dest_const_id =
  289. context.constant_values().Get(op.interface_args_ref[0]);
  290. auto dest_type_id =
  291. context.types().TryGetTypeIdForTypeConstantId(dest_const_id);
  292. if (!dest_type_id.has_value()) {
  293. return SemIR::InstId::None;
  294. }
  295. return LookupCppConversion(
  296. context, loc_id, arg_ids[0], dest_type_id,
  297. /*allow_explicit=*/op.interface_name == CoreIdentifier::As);
  298. }
  299. auto op_kind =
  300. GetClangOperatorKind(context, loc_id, op.interface_name, op.op_name);
  301. if (!op_kind) {
  302. return SemIR::InstId::None;
  303. }
  304. // Make sure all operands are complete before lookup.
  305. for (SemIR::InstId arg_id : arg_ids) {
  306. SemIR::TypeId arg_type_id = context.insts().Get(arg_id).type_id();
  307. if (!RequireCompleteType(context, arg_type_id, loc_id, [&] {
  308. CARBON_DIAGNOSTIC(
  309. IncompleteOperandTypeInCppOperatorLookup, Error,
  310. "looking up a C++ operator with incomplete operand type {0}",
  311. SemIR::TypeId);
  312. return context.emitter().Build(
  313. loc_id, IncompleteOperandTypeInCppOperatorLookup, arg_type_id);
  314. })) {
  315. return SemIR::ErrorInst::InstId;
  316. }
  317. }
  318. auto maybe_arg_exprs = InventClangArgs(context, arg_ids);
  319. if (!maybe_arg_exprs.has_value()) {
  320. return SemIR::ErrorInst::InstId;
  321. }
  322. auto& arg_exprs = *maybe_arg_exprs;
  323. clang::SourceLocation loc = GetCppLocation(context, loc_id);
  324. clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info(
  325. *op_kind, loc, /*AllowRewritten=*/true);
  326. clang::OverloadCandidateSet candidate_set(
  327. loc, clang::OverloadCandidateSet::CSK_Operator, operator_rewrite_info);
  328. clang::Sema& sema = context.clang_sema();
  329. // This works for both unary and binary operators.
  330. sema.LookupOverloadedBinOp(candidate_set, *op_kind, clang::UnresolvedSet<0>{},
  331. arg_exprs);
  332. clang::OverloadCandidateSet::iterator best_viable_fn;
  333. switch (candidate_set.BestViableFunction(sema, loc, best_viable_fn)) {
  334. case clang::OverloadingResult::OR_Success: {
  335. if (!best_viable_fn->Function) {
  336. // The best viable candidate was a builtin. Let the Carbon operator
  337. // machinery handle that.
  338. return SemIR::InstId::None;
  339. }
  340. if (best_viable_fn->RewriteKind) {
  341. context.TODO(
  342. loc_id,
  343. llvm::formatv("Rewriting operator{0} using {1} is not supported",
  344. clang::getOperatorSpelling(
  345. candidate_set.getRewriteInfo().OriginalOperator),
  346. best_viable_fn->Function->getNameAsString()));
  347. return SemIR::ErrorInst::InstId;
  348. }
  349. sema.MarkFunctionReferenced(loc, best_viable_fn->Function);
  350. auto result_id = ImportCppFunctionDecl(
  351. context, loc_id, best_viable_fn->Function,
  352. // If this is an operator method, the first arg will be used as self.
  353. arg_ids.size() -
  354. (isa<clang::CXXMethodDecl>(best_viable_fn->Function) ? 1 : 0));
  355. if (result_id != SemIR::ErrorInst::InstId) {
  356. CheckCppOverloadAccess(
  357. context, loc_id, best_viable_fn->FoundDecl,
  358. context.insts().GetAsKnownInstId<SemIR::FunctionDecl>(result_id));
  359. }
  360. return result_id;
  361. }
  362. case clang::OverloadingResult::OR_No_Viable_Function: {
  363. // OK, didn't find a viable C++ candidate, but this is not an error, as
  364. // there might be a Carbon candidate.
  365. return SemIR::InstId::None;
  366. }
  367. case clang::OverloadingResult::OR_Ambiguous: {
  368. const char* spelling = clang::getOperatorSpelling(*op_kind);
  369. candidate_set.NoteCandidates(
  370. clang::PartialDiagnosticAt(
  371. loc, sema.PDiag(clang::diag::err_ovl_ambiguous_oper_binary)
  372. << spelling << arg_exprs[0]->getType()
  373. << arg_exprs[1]->getType()),
  374. sema, clang::OCD_AmbiguousCandidates, arg_exprs, spelling, loc);
  375. return SemIR::ErrorInst::InstId;
  376. }
  377. case clang::OverloadingResult::OR_Deleted:
  378. const char* spelling = clang::getOperatorSpelling(*op_kind);
  379. auto* message = best_viable_fn->Function->getDeletedMessage();
  380. // The best viable function might be a different operator if the best
  381. // candidate is a rewritten candidate, so use the operator kind of the
  382. // candidate itself in the diagnostic.
  383. candidate_set.NoteCandidates(
  384. clang::PartialDiagnosticAt(
  385. loc, sema.PDiag(clang::diag::err_ovl_deleted_oper)
  386. << clang::getOperatorSpelling(
  387. best_viable_fn->Function->getOverloadedOperator())
  388. << (message != nullptr)
  389. << (message ? message->getString() : llvm::StringRef())),
  390. sema, clang::OCD_AllCandidates, arg_exprs, spelling, loc);
  391. return SemIR::ErrorInst::InstId;
  392. }
  393. }
  394. auto IsCppOperatorMethodDecl(clang::Decl* decl) -> bool {
  395. auto* clang_method_decl = dyn_cast<clang::CXXMethodDecl>(decl);
  396. return clang_method_decl &&
  397. (clang_method_decl->isOverloadedOperator() ||
  398. isa<clang::CXXConversionDecl>(clang_method_decl));
  399. }
  400. static auto GetAsCppFunctionDecl(Context& context, SemIR::InstId inst_id)
  401. -> clang::FunctionDecl* {
  402. auto function_type = context.types().TryGetAs<SemIR::FunctionType>(
  403. context.insts().Get(inst_id).type_id());
  404. if (!function_type) {
  405. return nullptr;
  406. }
  407. SemIR::ClangDeclId clang_decl_id =
  408. context.functions().Get(function_type->function_id).clang_decl_id;
  409. return clang_decl_id.has_value()
  410. ? dyn_cast<clang::FunctionDecl>(
  411. context.clang_decls().Get(clang_decl_id).key.decl)
  412. : nullptr;
  413. }
  414. auto IsCppOperatorMethod(Context& context, SemIR::InstId inst_id) -> bool {
  415. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  416. return function_decl && IsCppOperatorMethodDecl(function_decl);
  417. }
  418. auto IsCppConstructorOrNonMethodOperator(Context& context,
  419. SemIR::InstId inst_id) -> bool {
  420. auto* function_decl = GetAsCppFunctionDecl(context, inst_id);
  421. if (!function_decl) {
  422. return false;
  423. }
  424. if (isa<clang::CXXConstructorDecl>(function_decl)) {
  425. return true;
  426. }
  427. return !isa<clang::CXXMethodDecl>(function_decl) &&
  428. function_decl->isOverloadedOperator();
  429. }
  430. } // namespace Carbon::Check