convert.cpp 37 KB

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