convert.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  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/convert.h"
  5. #include <string>
  6. #include <utility>
  7. #include "common/check.h"
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "toolchain/check/context.h"
  10. #include "toolchain/diagnostics/diagnostic_kind.h"
  11. #include "toolchain/parse/node_kind.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/node.h"
  14. #include "toolchain/sem_ir/node_kind.h"
  15. namespace Carbon::Check {
  16. // Given an initializing expression, find its return slot. Returns `Invalid` if
  17. // there is no return slot, because the initialization is not performed in
  18. // place.
  19. static auto FindReturnSlotForInitializer(SemIR::File& semantics_ir,
  20. SemIR::NodeId init_id)
  21. -> SemIR::NodeId {
  22. SemIR::Node init = semantics_ir.GetNode(init_id);
  23. switch (init.kind()) {
  24. default:
  25. CARBON_FATAL() << "Initialization from unexpected node " << init;
  26. case SemIR::NodeKind::StructInit:
  27. case SemIR::NodeKind::TupleInit:
  28. // TODO: Track a return slot for these initializers.
  29. CARBON_FATAL() << init
  30. << " should be created with its return slot already "
  31. "filled in properly";
  32. case SemIR::NodeKind::InitializeFrom: {
  33. auto [src_id, dest_id] = init.GetAsInitializeFrom();
  34. return dest_id;
  35. }
  36. case SemIR::NodeKind::Call: {
  37. auto [refs_id, callee_id] = init.GetAsCall();
  38. if (!semantics_ir.GetFunction(callee_id).return_slot_id.is_valid()) {
  39. return SemIR::NodeId::Invalid;
  40. }
  41. return semantics_ir.GetNodeBlock(refs_id).back();
  42. }
  43. case SemIR::NodeKind::ArrayInit: {
  44. auto [src_id, refs_id] = init.GetAsArrayInit();
  45. return semantics_ir.GetNodeBlock(refs_id).back();
  46. }
  47. }
  48. }
  49. // Marks the initializer `init_id` as initializing `target_id`.
  50. static auto MarkInitializerFor(SemIR::File& semantics_ir, SemIR::NodeId init_id,
  51. SemIR::NodeId target_id,
  52. PendingBlock& target_block) -> void {
  53. auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id);
  54. if (return_slot_id.is_valid()) {
  55. // Replace the temporary in the return slot with a reference to our target.
  56. CARBON_CHECK(semantics_ir.GetNode(return_slot_id).kind() ==
  57. SemIR::NodeKind::TemporaryStorage)
  58. << "Return slot for initializer does not contain a temporary; "
  59. << "initialized multiple times? Have "
  60. << semantics_ir.GetNode(return_slot_id);
  61. target_block.MergeReplacing(return_slot_id, target_id);
  62. }
  63. }
  64. // Commits to using a temporary to store the result of the initializing
  65. // expression described by `init_id`, and returns the location of the
  66. // temporary. If `discarded` is `true`, the result is discarded, and no
  67. // temporary will be created if possible; if no temporary is created, the
  68. // return value will be `SemIR::NodeId::Invalid`.
  69. static auto FinalizeTemporary(Context& context, SemIR::NodeId init_id,
  70. bool discarded) -> SemIR::NodeId {
  71. auto& semantics_ir = context.semantics_ir();
  72. auto return_slot_id = FindReturnSlotForInitializer(semantics_ir, init_id);
  73. if (return_slot_id.is_valid()) {
  74. // The return slot should already have a materialized temporary in it.
  75. CARBON_CHECK(semantics_ir.GetNode(return_slot_id).kind() ==
  76. SemIR::NodeKind::TemporaryStorage)
  77. << "Return slot for initializer does not contain a temporary; "
  78. << "initialized multiple times? Have "
  79. << semantics_ir.GetNode(return_slot_id);
  80. auto init = semantics_ir.GetNode(init_id);
  81. return context.AddNode(SemIR::Node::Temporary::Make(
  82. init.parse_node(), init.type_id(), return_slot_id, init_id));
  83. }
  84. if (discarded) {
  85. // Don't invent a temporary that we're going to discard.
  86. return SemIR::NodeId::Invalid;
  87. }
  88. // The initializer has no return slot, but we want to produce a temporary
  89. // object. Materialize one now.
  90. // TODO: Consider using an invalid ID to mean that we immediately
  91. // materialize and initialize a temporary, rather than two separate
  92. // nodes.
  93. auto init = semantics_ir.GetNode(init_id);
  94. auto temporary_id = context.AddNode(
  95. SemIR::Node::TemporaryStorage::Make(init.parse_node(), init.type_id()));
  96. return context.AddNode(SemIR::Node::Temporary::Make(
  97. init.parse_node(), init.type_id(), temporary_id, init_id));
  98. }
  99. // Materialize a temporary to hold the result of the given expression if it is
  100. // an initializing expression.
  101. static auto MaterializeIfInitializing(Context& context, SemIR::NodeId expr_id)
  102. -> SemIR::NodeId {
  103. if (GetExpressionCategory(context.semantics_ir(), expr_id) ==
  104. SemIR::ExpressionCategory::Initializing) {
  105. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  106. }
  107. return expr_id;
  108. }
  109. // Creates and adds a node to perform element access into an aggregate.
  110. template <typename AccessNodeT, typename NodeBlockT>
  111. static auto MakeElemAccessNode(Context& context, Parse::Node parse_node,
  112. SemIR::NodeId aggregate_id,
  113. SemIR::TypeId elem_type_id, NodeBlockT& block,
  114. std::size_t i) {
  115. if constexpr (std::is_same_v<AccessNodeT, SemIR::Node::ArrayIndex>) {
  116. // TODO: Add a new node kind for indexing an array at a constant index
  117. // so that we don't need an integer literal node here, and remove this
  118. // special case.
  119. auto index_id = block.AddNode(SemIR::Node::IntegerLiteral::Make(
  120. parse_node, context.CanonicalizeType(SemIR::NodeId::BuiltinIntegerType),
  121. context.semantics_ir().AddIntegerLiteral(llvm::APInt(32, i))));
  122. return block.AddNode(
  123. AccessNodeT::Make(parse_node, elem_type_id, aggregate_id, index_id));
  124. } else {
  125. return block.AddNode(AccessNodeT::Make(
  126. parse_node, elem_type_id, aggregate_id, SemIR::MemberIndex(i)));
  127. }
  128. }
  129. // Converts an element of one aggregate so that it can be used as an element of
  130. // another aggregate.
  131. //
  132. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  133. // element type, `i` is the index, and `SourceAccessNodeT` is the kind of node
  134. // used to access the source element.
  135. //
  136. // For the target: `kind` is the kind of conversion or initialization,
  137. // `target_elem_type` is the element type. For initialization, `target_id` is
  138. // the destination, `target_block` is a pending block for target location
  139. // calculations that will be spliced as the return slot of the initializer if
  140. // necessary, `i` is the index, and `TargetAccessNodeT` is the kind of node
  141. // used to access the destination element.
  142. template <typename SourceAccessNodeT, typename TargetAccessNodeT>
  143. static auto ConvertAggregateElement(
  144. Context& context, Parse::Node parse_node, SemIR::NodeId src_id,
  145. SemIR::TypeId src_elem_type,
  146. llvm::ArrayRef<SemIR::NodeId> src_literal_elems,
  147. ConversionTarget::Kind kind, SemIR::NodeId target_id,
  148. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  149. // Compute the location of the source element. This goes into the current code
  150. // block, not into the target block.
  151. // TODO: Ideally we would discard this node if it's unused.
  152. auto src_elem_id =
  153. !src_literal_elems.empty()
  154. ? src_literal_elems[i]
  155. : MakeElemAccessNode<SourceAccessNodeT>(context, parse_node, src_id,
  156. src_elem_type, context, i);
  157. // If we're performing a conversion rather than an initialization, we won't
  158. // have or need a target.
  159. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  160. if (!target.is_initializer()) {
  161. return Convert(context, parse_node, src_elem_id, target);
  162. }
  163. // Compute the location of the target element and initialize it.
  164. PendingBlock::DiscardUnusedNodesScope scope(target_block);
  165. target.init_block = target_block;
  166. target.init_id = MakeElemAccessNode<TargetAccessNodeT>(
  167. context, parse_node, target_id, target_elem_type, *target_block, i);
  168. return Convert(context, parse_node, src_elem_id, target);
  169. }
  170. namespace {
  171. // A handle to a new block that may be modified, with copy-on-write semantics.
  172. //
  173. // The constructor is given the ID of an existing block that provides the
  174. // initial contents of the new block. The new block is lazily allocated; if no
  175. // modifications have been made, the `id()` function will return the original
  176. // block ID.
  177. //
  178. // This is intended to avoid an unnecessary block allocation in the case where
  179. // the new block ends up being exactly the same as the original block.
  180. class CopyOnWriteBlock {
  181. public:
  182. // Constructs the block. If `source_id` is valid, it is used as the initial
  183. // value of the block. Otherwise, uninitialized storage for `size` elements
  184. // is allocated.
  185. CopyOnWriteBlock(SemIR::File& file, SemIR::NodeBlockId source_id, size_t size)
  186. : file_(file), source_id_(source_id) {
  187. if (!source_id_.is_valid()) {
  188. id_ = file_.AddUninitializedNodeBlock(size);
  189. }
  190. }
  191. auto id() -> SemIR::NodeBlockId const { return id_; }
  192. auto Set(int i, SemIR::NodeId value) -> void {
  193. if (source_id_.is_valid() && file_.GetNodeBlock(id_)[i] == value) {
  194. return;
  195. }
  196. if (id_ == source_id_) {
  197. id_ = file_.AddNodeBlock(file_.GetNodeBlock(source_id_));
  198. }
  199. file_.GetNodeBlock(id_)[i] = value;
  200. }
  201. private:
  202. SemIR::File& file_;
  203. SemIR::NodeBlockId source_id_;
  204. SemIR::NodeBlockId id_ = source_id_;
  205. };
  206. } // namespace
  207. // Performs a conversion from a tuple to an array type. Does not perform a
  208. // final conversion to the requested expression category.
  209. static auto ConvertTupleToArray(Context& context, SemIR::Node tuple_type,
  210. SemIR::Node array_type, SemIR::NodeId value_id,
  211. ConversionTarget target) -> SemIR::NodeId {
  212. auto& semantics_ir = context.semantics_ir();
  213. auto [array_bound_id, element_type_id] = array_type.GetAsArrayType();
  214. auto tuple_elem_types_id = tuple_type.GetAsTupleType();
  215. const auto& tuple_elem_types = semantics_ir.GetTypeBlock(tuple_elem_types_id);
  216. auto value = semantics_ir.GetNode(value_id);
  217. // If we're initializing from a tuple literal, we will use its elements
  218. // directly. Otherwise, materialize a temporary if needed and index into the
  219. // result.
  220. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  221. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  222. literal_elems = semantics_ir.GetNodeBlock(value.GetAsTupleLiteral());
  223. } else {
  224. value_id = MaterializeIfInitializing(context, value_id);
  225. }
  226. // Check that the tuple is the right size.
  227. uint64_t array_bound = semantics_ir.GetArrayBoundValue(array_bound_id);
  228. if (tuple_elem_types.size() != array_bound) {
  229. CARBON_DIAGNOSTIC(
  230. ArrayInitFromLiteralArgCountMismatch, Error,
  231. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  232. uint64_t, size_t);
  233. CARBON_DIAGNOSTIC(ArrayInitFromExpressionArgCountMismatch, Error,
  234. "Cannot initialize array of {0} element(s) from tuple "
  235. "with {1} element(s).",
  236. uint64_t, size_t);
  237. context.emitter().Emit(value.parse_node(),
  238. literal_elems.empty()
  239. ? ArrayInitFromExpressionArgCountMismatch
  240. : ArrayInitFromLiteralArgCountMismatch,
  241. array_bound, tuple_elem_types.size());
  242. return SemIR::NodeId::BuiltinError;
  243. }
  244. PendingBlock target_block_storage(context);
  245. PendingBlock* target_block =
  246. target.init_block ? target.init_block : &target_block_storage;
  247. // Arrays are always initialized in-place. Allocate a temporary as the
  248. // destination for the array initialization if we weren't given one.
  249. SemIR::NodeId return_slot_id = target.init_id;
  250. if (!target.init_id.is_valid()) {
  251. return_slot_id = target_block->AddNode(SemIR::Node::TemporaryStorage::Make(
  252. value.parse_node(), target.type_id));
  253. }
  254. // Initialize each element of the array from the corresponding element of the
  255. // tuple.
  256. // TODO: Annotate diagnostics coming from here with the array element index,
  257. // if initializing from a tuple literal.
  258. llvm::SmallVector<SemIR::NodeId> inits;
  259. inits.reserve(array_bound + 1);
  260. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  261. // TODO: This call recurses back into conversion. Switch to an iterative
  262. // approach.
  263. auto init_id = ConvertAggregateElement<SemIR::Node::TupleAccess,
  264. SemIR::Node::ArrayIndex>(
  265. context, value.parse_node(), value_id, src_type_id, literal_elems,
  266. ConversionTarget::FullInitializer, return_slot_id, element_type_id,
  267. target_block, i);
  268. if (init_id == SemIR::NodeId::BuiltinError) {
  269. return SemIR::NodeId::BuiltinError;
  270. }
  271. inits.push_back(init_id);
  272. }
  273. // The last element of the refs block contains the return slot for the array
  274. // initialization. Flush the temporary here if we didn't insert it earlier.
  275. target_block->InsertHere();
  276. inits.push_back(return_slot_id);
  277. return context.AddNode(
  278. SemIR::Node::ArrayInit::Make(value.parse_node(), target.type_id, value_id,
  279. semantics_ir.AddNodeBlock(inits)));
  280. }
  281. // Performs a conversion from a tuple to a tuple type. Does not perform a
  282. // final conversion to the requested expression category.
  283. static auto ConvertTupleToTuple(Context& context, SemIR::Node src_type,
  284. SemIR::Node dest_type, SemIR::NodeId value_id,
  285. ConversionTarget target) -> SemIR::NodeId {
  286. auto& semantics_ir = context.semantics_ir();
  287. auto src_elem_types = semantics_ir.GetTypeBlock(src_type.GetAsTupleType());
  288. auto dest_elem_types = semantics_ir.GetTypeBlock(dest_type.GetAsTupleType());
  289. auto value = semantics_ir.GetNode(value_id);
  290. // If we're initializing from a tuple literal, we will use its elements
  291. // directly. Otherwise, materialize a temporary if needed and index into the
  292. // result.
  293. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  294. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  295. literal_elems = semantics_ir.GetNodeBlock(value.GetAsTupleLiteral());
  296. } else {
  297. value_id = MaterializeIfInitializing(context, value_id);
  298. }
  299. // Check that the tuples are the same size.
  300. if (src_elem_types.size() != dest_elem_types.size()) {
  301. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  302. "Cannot initialize tuple of {0} element(s) from tuple "
  303. "with {1} element(s).",
  304. size_t, size_t);
  305. context.emitter().Emit(value.parse_node(), TupleInitElementCountMismatch,
  306. dest_elem_types.size(), src_elem_types.size());
  307. return SemIR::NodeId::BuiltinError;
  308. }
  309. // If we're forming an initializer, then we want an initializer for each
  310. // element. Otherwise, we want a value representation for each element.
  311. // Perform a final destination store if we're performing an in-place
  312. // initialization.
  313. bool is_init = target.is_initializer();
  314. ConversionTarget::Kind inner_kind =
  315. !is_init ? ConversionTarget::Value
  316. : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id)
  317. .kind == SemIR::InitializingRepresentation::InPlace
  318. ? ConversionTarget::FullInitializer
  319. : ConversionTarget::Initializer;
  320. // Initialize each element of the destination from the corresponding element
  321. // of the source.
  322. // TODO: Annotate diagnostics coming from here with the element index.
  323. CopyOnWriteBlock new_block(semantics_ir,
  324. value.kind() == SemIR::NodeKind::TupleLiteral
  325. ? value.GetAsTupleLiteral()
  326. : SemIR::NodeBlockId::Invalid,
  327. src_elem_types.size());
  328. for (auto [i, src_type_id, dest_type_id] :
  329. llvm::enumerate(src_elem_types, dest_elem_types)) {
  330. // TODO: This call recurses back into conversion. Switch to an iterative
  331. // approach.
  332. auto init_id = ConvertAggregateElement<SemIR::Node::TupleAccess,
  333. SemIR::Node::TupleAccess>(
  334. context, value.parse_node(), value_id, src_type_id, literal_elems,
  335. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  336. if (init_id == SemIR::NodeId::BuiltinError) {
  337. return SemIR::NodeId::BuiltinError;
  338. }
  339. new_block.Set(i, init_id);
  340. }
  341. return context.AddNode(
  342. is_init
  343. ? SemIR::Node::TupleInit::Make(value.parse_node(), target.type_id,
  344. value_id, new_block.id())
  345. : SemIR::Node::TupleValue::Make(value.parse_node(), target.type_id,
  346. value_id, new_block.id()));
  347. }
  348. // Performs a conversion from a struct to a struct type. Does not perform a
  349. // final conversion to the requested expression category.
  350. static auto ConvertStructToStruct(Context& context, SemIR::Node src_type,
  351. SemIR::Node dest_type, SemIR::NodeId value_id,
  352. ConversionTarget target) -> SemIR::NodeId {
  353. auto& semantics_ir = context.semantics_ir();
  354. auto src_elem_fields = semantics_ir.GetNodeBlock(src_type.GetAsStructType());
  355. auto dest_elem_fields =
  356. semantics_ir.GetNodeBlock(dest_type.GetAsStructType());
  357. auto value = semantics_ir.GetNode(value_id);
  358. // If we're initializing from a struct literal, we will use its elements
  359. // directly. Otherwise, materialize a temporary if needed and index into the
  360. // result.
  361. llvm::ArrayRef<SemIR::NodeId> literal_elems;
  362. if (value.kind() == SemIR::NodeKind::StructLiteral) {
  363. literal_elems = semantics_ir.GetNodeBlock(value.GetAsStructLiteral());
  364. } else {
  365. value_id = MaterializeIfInitializing(context, value_id);
  366. }
  367. // Check that the structs are the same size.
  368. // TODO: Check the field names are the same up to permutation, compute the
  369. // permutation, and use it below.
  370. if (src_elem_fields.size() != dest_elem_fields.size()) {
  371. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  372. "Cannot initialize struct of {0} element(s) from struct "
  373. "with {1} element(s).",
  374. size_t, size_t);
  375. context.emitter().Emit(value.parse_node(), StructInitElementCountMismatch,
  376. dest_elem_fields.size(), src_elem_fields.size());
  377. return SemIR::NodeId::BuiltinError;
  378. }
  379. // If we're forming an initializer, then we want an initializer for each
  380. // element. Otherwise, we want a value representation for each element.
  381. // Perform a final destination store if we're performing an in-place
  382. // initialization.
  383. bool is_init = target.is_initializer();
  384. ConversionTarget::Kind inner_kind =
  385. !is_init ? ConversionTarget::Value
  386. : SemIR::GetInitializingRepresentation(semantics_ir, target.type_id)
  387. .kind == SemIR::InitializingRepresentation::InPlace
  388. ? ConversionTarget::FullInitializer
  389. : ConversionTarget::Initializer;
  390. // Initialize each element of the destination from the corresponding element
  391. // of the source.
  392. // TODO: Annotate diagnostics coming from here with the element index.
  393. CopyOnWriteBlock new_block(semantics_ir,
  394. value.kind() == SemIR::NodeKind::StructLiteral
  395. ? value.GetAsStructLiteral()
  396. : SemIR::NodeBlockId::Invalid,
  397. src_elem_fields.size());
  398. for (auto [i, src_field_id, dest_field_id] :
  399. llvm::enumerate(src_elem_fields, dest_elem_fields)) {
  400. auto [src_name_id, src_type_id] =
  401. semantics_ir.GetNode(src_field_id).GetAsStructTypeField();
  402. auto [dest_name_id, dest_type_id] =
  403. semantics_ir.GetNode(dest_field_id).GetAsStructTypeField();
  404. if (src_name_id != dest_name_id) {
  405. CARBON_DIAGNOSTIC(
  406. StructInitFieldNameMismatch, Error,
  407. "Mismatched names for field {0} in struct initialization: "
  408. "source has field name `{1}`, destination has field name `{2}`.",
  409. size_t, llvm::StringRef, llvm::StringRef);
  410. context.emitter().Emit(value.parse_node(), StructInitFieldNameMismatch,
  411. i + 1, semantics_ir.GetString(src_name_id),
  412. semantics_ir.GetString(dest_name_id));
  413. return SemIR::NodeId::BuiltinError;
  414. }
  415. // TODO: This call recurses back into conversion. Switch to an iterative
  416. // approach.
  417. auto init_id = ConvertAggregateElement<SemIR::Node::StructAccess,
  418. SemIR::Node::StructAccess>(
  419. context, value.parse_node(), value_id, src_type_id, literal_elems,
  420. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  421. if (init_id == SemIR::NodeId::BuiltinError) {
  422. return SemIR::NodeId::BuiltinError;
  423. }
  424. new_block.Set(i, init_id);
  425. }
  426. return context.AddNode(
  427. is_init
  428. ? SemIR::Node::StructInit::Make(value.parse_node(), target.type_id,
  429. value_id, new_block.id())
  430. : SemIR::Node::StructValue::Make(value.parse_node(), target.type_id,
  431. value_id, new_block.id()));
  432. }
  433. // Returns whether `category` is a valid expression category to produce as a
  434. // result of a conversion with kind `target_kind`, or at most needs a temporary
  435. // to be materialized.
  436. static bool IsValidExpressionCategoryForConversionTarget(
  437. SemIR::ExpressionCategory category, ConversionTarget::Kind target_kind) {
  438. switch (target_kind) {
  439. case ConversionTarget::Value:
  440. return category == SemIR::ExpressionCategory::Value;
  441. case ConversionTarget::ValueOrReference:
  442. case ConversionTarget::Discarded:
  443. return category == SemIR::ExpressionCategory::Value ||
  444. category == SemIR::ExpressionCategory::DurableReference ||
  445. category == SemIR::ExpressionCategory::EphemeralReference ||
  446. category == SemIR::ExpressionCategory::Initializing;
  447. case ConversionTarget::Initializer:
  448. case ConversionTarget::FullInitializer:
  449. return category == SemIR::ExpressionCategory::Initializing;
  450. }
  451. }
  452. static auto PerformBuiltinConversion(Context& context, Parse::Node parse_node,
  453. SemIR::NodeId value_id,
  454. ConversionTarget target) -> SemIR::NodeId {
  455. auto& semantics_ir = context.semantics_ir();
  456. auto value = semantics_ir.GetNode(value_id);
  457. auto value_type_id = value.type_id();
  458. auto target_type_node = semantics_ir.GetNode(
  459. semantics_ir.GetTypeAllowBuiltinTypes(target.type_id));
  460. // Various forms of implicit conversion are supported as builtin conversions,
  461. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  462. // prelude. There are a few reasons we need to perform some of these
  463. // conversions as builtins:
  464. //
  465. // 1) Conversions from struct and tuple *literals* have special rules that
  466. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  467. // recurse into the elements of the literal before performing
  468. // initialization in order to avoid unnecessary conversions between
  469. // expression categories that would be performed by `ImplicitAs.Convert`.
  470. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  471. // the value of the facet, not only its type, and therefore cannot be
  472. // modeled by `ImplicitAs`.
  473. // 3) Some of these conversions are used while checking the library
  474. // definition of `ImplicitAs` itself or implementations of it.
  475. //
  476. // We also expect to see better performance by avoiding an `impl` lookup for
  477. // common conversions.
  478. //
  479. // TODO: We should provide a debugging flag to turn off as many of these
  480. // builtin conversions as we can so that we can test that they do the same
  481. // thing as the library implementations.
  482. //
  483. // The builtin conversions that correspond to `impl`s in the library all
  484. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  485. // being specialized in any of these cases.
  486. // If the value is already of the right kind and expression category, there's
  487. // nothing to do. Performing a conversion would decompose and rebuild tuples
  488. // and structs, so it's important that we bail out early in this case.
  489. if (value_type_id == target.type_id &&
  490. IsValidExpressionCategoryForConversionTarget(
  491. SemIR::GetExpressionCategory(semantics_ir, value_id), target.kind)) {
  492. return value_id;
  493. }
  494. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  495. // converts to Ui.
  496. if (target_type_node.kind() == SemIR::NodeKind::TupleType) {
  497. auto value_type_node = semantics_ir.GetNode(
  498. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  499. if (value_type_node.kind() == SemIR::NodeKind::TupleType) {
  500. return ConvertTupleToTuple(context, value_type_node, target_type_node,
  501. value_id, target);
  502. }
  503. }
  504. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  505. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  506. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  507. // to Ui.
  508. if (target_type_node.kind() == SemIR::NodeKind::StructType) {
  509. auto value_type_node = semantics_ir.GetNode(
  510. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  511. if (value_type_node.kind() == SemIR::NodeKind::StructType) {
  512. return ConvertStructToStruct(context, value_type_node, target_type_node,
  513. value_id, target);
  514. }
  515. }
  516. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  517. if (target_type_node.kind() == SemIR::NodeKind::ArrayType) {
  518. auto value_type_node = semantics_ir.GetNode(
  519. semantics_ir.GetTypeAllowBuiltinTypes(value_type_id));
  520. if (value_type_node.kind() == SemIR::NodeKind::TupleType) {
  521. return ConvertTupleToArray(context, value_type_node, target_type_node,
  522. value_id, target);
  523. }
  524. }
  525. if (target.type_id == SemIR::TypeId::TypeType) {
  526. // A tuple of types converts to type `type`.
  527. // TODO: This should apply even for non-literal tuples.
  528. if (value.kind() == SemIR::NodeKind::TupleLiteral) {
  529. auto tuple_block_id = value.GetAsTupleLiteral();
  530. llvm::SmallVector<SemIR::TypeId> type_ids;
  531. // If it is empty tuple type, we don't fetch anything.
  532. if (tuple_block_id != SemIR::NodeBlockId::Empty) {
  533. const auto& tuple_block = semantics_ir.GetNodeBlock(tuple_block_id);
  534. for (auto tuple_node_id : tuple_block) {
  535. // TODO: This call recurses back into conversion. Switch to an
  536. // iterative approach.
  537. type_ids.push_back(
  538. ExpressionAsType(context, parse_node, tuple_node_id));
  539. }
  540. }
  541. auto tuple_type_id =
  542. context.CanonicalizeTupleType(parse_node, std::move(type_ids));
  543. return semantics_ir.GetTypeAllowBuiltinTypes(tuple_type_id);
  544. }
  545. // `{}` converts to `{} as type`.
  546. // TODO: This conversion should also be performed for a non-literal value
  547. // of type `{}`.
  548. if (value.kind() == SemIR::NodeKind::StructLiteral &&
  549. value.GetAsStructLiteral() == SemIR::NodeBlockId::Empty) {
  550. value_id = semantics_ir.GetTypeAllowBuiltinTypes(value_type_id);
  551. }
  552. }
  553. // No builtin conversion applies.
  554. return value_id;
  555. }
  556. auto Convert(Context& context, Parse::Node parse_node, SemIR::NodeId expr_id,
  557. ConversionTarget target) -> SemIR::NodeId {
  558. auto& semantics_ir = context.semantics_ir();
  559. auto orig_expr_id = expr_id;
  560. // Start by making sure both sides are valid. If any part is invalid, the
  561. // result is invalid and we shouldn't error.
  562. if (expr_id == SemIR::NodeId::BuiltinError) {
  563. return expr_id;
  564. }
  565. if (semantics_ir.GetNode(expr_id).type_id() == SemIR::TypeId::Error ||
  566. target.type_id == SemIR::TypeId::Error) {
  567. return SemIR::NodeId::BuiltinError;
  568. }
  569. if (SemIR::GetExpressionCategory(semantics_ir, expr_id) ==
  570. SemIR::ExpressionCategory::NotExpression) {
  571. // TODO: We currently encounter this for use of namespaces and functions.
  572. // We should provide a better diagnostic for inappropriate use of
  573. // namespace names, and allow use of functions as values.
  574. CARBON_DIAGNOSTIC(UseOfNonExpressionAsValue, Error,
  575. "Expression cannot be used as a value.");
  576. context.emitter().Emit(semantics_ir.GetNode(expr_id).parse_node(),
  577. UseOfNonExpressionAsValue);
  578. return SemIR::NodeId::BuiltinError;
  579. }
  580. // Check whether any builtin conversion applies.
  581. expr_id = PerformBuiltinConversion(context, parse_node, expr_id, target);
  582. if (expr_id == SemIR::NodeId::BuiltinError) {
  583. return expr_id;
  584. }
  585. // If the types don't match at this point, we can't perform the conversion.
  586. // TODO: Look for an ImplicitAs impl.
  587. SemIR::Node expr = semantics_ir.GetNode(expr_id);
  588. if (expr.type_id() != target.type_id) {
  589. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  590. "Cannot implicitly convert from `{0}` to `{1}`.",
  591. std::string, std::string);
  592. context.emitter()
  593. .Build(parse_node, ImplicitAsConversionFailure,
  594. semantics_ir.StringifyType(expr.type_id()),
  595. semantics_ir.StringifyType(target.type_id))
  596. .Emit();
  597. return SemIR::NodeId::BuiltinError;
  598. }
  599. // Now perform any necessary value category conversions.
  600. switch (SemIR::GetExpressionCategory(semantics_ir, expr_id)) {
  601. case SemIR::ExpressionCategory::NotExpression:
  602. case SemIR::ExpressionCategory::Mixed:
  603. CARBON_FATAL() << "Unexpected expression " << expr
  604. << " after builtin conversions";
  605. case SemIR::ExpressionCategory::Initializing:
  606. if (target.is_initializer()) {
  607. if (orig_expr_id == expr_id) {
  608. // Don't fill in the return slot if we created the expression through
  609. // a conversion. In that case, we will have created it with the
  610. // target already set.
  611. // TODO: Find a better way to track whether we need to do this.
  612. MarkInitializerFor(semantics_ir, expr_id, target.init_id,
  613. *target.init_block);
  614. }
  615. break;
  616. }
  617. // Commit to using a temporary for this initializing expression.
  618. // TODO: Don't create a temporary if the initializing representation
  619. // is already a value representation.
  620. expr_id = FinalizeTemporary(context, expr_id,
  621. target.kind == ConversionTarget::Discarded);
  622. // We now have an ephemeral reference.
  623. [[fallthrough]];
  624. case SemIR::ExpressionCategory::DurableReference:
  625. case SemIR::ExpressionCategory::EphemeralReference: {
  626. // If we have a reference and don't want one, form a value binding.
  627. if (target.kind != ConversionTarget::ValueOrReference &&
  628. target.kind != ConversionTarget::Discarded) {
  629. // TODO: Support types with custom value representations.
  630. expr_id = context.AddNode(SemIR::Node::BindValue::Make(
  631. expr.parse_node(), expr.type_id(), expr_id));
  632. }
  633. break;
  634. }
  635. case SemIR::ExpressionCategory::Value:
  636. break;
  637. }
  638. // Perform a final destination store, if necessary.
  639. if (target.kind == ConversionTarget::FullInitializer) {
  640. if (auto init_rep =
  641. SemIR::GetInitializingRepresentation(semantics_ir, target.type_id);
  642. init_rep.kind == SemIR::InitializingRepresentation::ByCopy) {
  643. target.init_block->InsertHere();
  644. expr_id = context.AddNode(SemIR::Node::InitializeFrom::Make(
  645. parse_node, target.type_id, expr_id, target.init_id));
  646. }
  647. }
  648. return expr_id;
  649. }
  650. auto Initialize(Context& context, Parse::Node parse_node,
  651. SemIR::NodeId target_id, SemIR::NodeId value_id)
  652. -> SemIR::NodeId {
  653. PendingBlock target_block(context);
  654. return Convert(
  655. context, parse_node, value_id,
  656. {.kind = ConversionTarget::Initializer,
  657. .type_id = context.semantics_ir().GetNode(target_id).type_id(),
  658. .init_id = target_id,
  659. .init_block = &target_block});
  660. }
  661. auto ConvertToValueExpression(Context& context, SemIR::NodeId expr_id)
  662. -> SemIR::NodeId {
  663. auto expr = context.semantics_ir().GetNode(expr_id);
  664. return Convert(context, expr.parse_node(), expr_id,
  665. {.kind = ConversionTarget::Value, .type_id = expr.type_id()});
  666. }
  667. auto ConvertToValueOrReferenceExpression(Context& context,
  668. SemIR::NodeId expr_id)
  669. -> SemIR::NodeId {
  670. auto expr = context.semantics_ir().GetNode(expr_id);
  671. return Convert(
  672. context, expr.parse_node(), expr_id,
  673. {.kind = ConversionTarget::ValueOrReference, .type_id = expr.type_id()});
  674. }
  675. auto ConvertToValueOfType(Context& context, Parse::Node parse_node,
  676. SemIR::NodeId value_id, SemIR::TypeId type_id)
  677. -> SemIR::NodeId {
  678. return Convert(context, parse_node, value_id,
  679. {.kind = ConversionTarget::Value, .type_id = type_id});
  680. }
  681. auto ConvertToBoolValue(Context& context, Parse::Node parse_node,
  682. SemIR::NodeId value_id) -> SemIR::NodeId {
  683. return ConvertToValueOfType(
  684. context, parse_node, value_id,
  685. context.CanonicalizeType(SemIR::NodeId::BuiltinBoolType));
  686. }
  687. auto ConvertCallArgs(Context& context, Parse::Node call_parse_node,
  688. SemIR::NodeBlockId arg_refs_id,
  689. Parse::Node param_parse_node,
  690. SemIR::NodeBlockId param_refs_id, bool has_return_slot)
  691. -> bool {
  692. // If both arguments and parameters are empty, return quickly. Otherwise,
  693. // we'll fetch both so that errors are consistent.
  694. if (arg_refs_id == SemIR::NodeBlockId::Empty &&
  695. param_refs_id == SemIR::NodeBlockId::Empty) {
  696. return true;
  697. }
  698. auto arg_refs = context.semantics_ir().GetNodeBlock(arg_refs_id);
  699. auto param_refs = context.semantics_ir().GetNodeBlock(param_refs_id);
  700. if (has_return_slot) {
  701. // There's no entry in the parameter block for the return slot, so ignore
  702. // the corresponding entry in the argument block.
  703. // TODO: Consider adding the return slot to the parameter list.
  704. CARBON_CHECK(!arg_refs.empty()) << "missing return slot";
  705. arg_refs = arg_refs.drop_back();
  706. }
  707. // If sizes mismatch, fail early.
  708. if (arg_refs.size() != param_refs.size()) {
  709. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  710. "{0} argument(s) passed to function expecting "
  711. "{1} argument(s).",
  712. int, int);
  713. CARBON_DIAGNOSTIC(InCallToFunction, Note,
  714. "Calling function declared here.");
  715. context.emitter()
  716. .Build(call_parse_node, CallArgCountMismatch, arg_refs.size(),
  717. param_refs.size())
  718. .Note(param_parse_node, InCallToFunction)
  719. .Emit();
  720. return false;
  721. }
  722. if (param_refs.empty()) {
  723. return true;
  724. }
  725. int diag_param_index;
  726. DiagnosticAnnotationScope annotate_diagnostics(
  727. &context.emitter(), [&](auto& builder) {
  728. CARBON_DIAGNOSTIC(
  729. InCallToFunctionParam, Note,
  730. "Initializing parameter {0} of function declared here.", int);
  731. builder.Note(param_parse_node, InCallToFunctionParam,
  732. diag_param_index + 1);
  733. });
  734. // Check type conversions per-element.
  735. for (auto [i, value_id, param_ref] : llvm::enumerate(arg_refs, param_refs)) {
  736. diag_param_index = i;
  737. auto as_type_id = context.semantics_ir().GetNode(param_ref).type_id();
  738. // TODO: Convert to the proper expression category. For now, we assume
  739. // parameters are all `let` bindings.
  740. value_id =
  741. ConvertToValueOfType(context, call_parse_node, value_id, as_type_id);
  742. if (value_id == SemIR::NodeId::BuiltinError) {
  743. return false;
  744. }
  745. arg_refs[i] = value_id;
  746. }
  747. return true;
  748. }
  749. auto ExpressionAsType(Context& context, Parse::Node parse_node,
  750. SemIR::NodeId value_id) -> SemIR::TypeId {
  751. return context.CanonicalizeType(ConvertToValueOfType(
  752. context, parse_node, value_id, SemIR::TypeId::TypeType));
  753. }
  754. } // namespace Carbon::Check