convert.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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/sem_ir/file.h"
  11. #include "toolchain/sem_ir/inst.h"
  12. namespace Carbon::Check {
  13. // Given an initializing expression, find its return slot. Returns `Invalid` if
  14. // there is no return slot, because the initialization is not performed in
  15. // place.
  16. static auto FindReturnSlotForInitializer(SemIR::File& sem_ir,
  17. SemIR::InstId init_id)
  18. -> SemIR::InstId {
  19. while (true) {
  20. SemIR::Inst init = sem_ir.insts().Get(init_id);
  21. switch (init.kind()) {
  22. default:
  23. CARBON_FATAL() << "Initialization from unexpected inst " << init;
  24. case SemIR::Converted::Kind:
  25. init_id = init.As<SemIR::Converted>().result_id;
  26. continue;
  27. case SemIR::ArrayInit::Kind:
  28. return init.As<SemIR::ArrayInit>().dest_id;
  29. case SemIR::ClassInit::Kind:
  30. return init.As<SemIR::ClassInit>().dest_id;
  31. case SemIR::StructInit::Kind:
  32. return init.As<SemIR::StructInit>().dest_id;
  33. case SemIR::TupleInit::Kind:
  34. return init.As<SemIR::TupleInit>().dest_id;
  35. case SemIR::InitializeFrom::Kind:
  36. return init.As<SemIR::InitializeFrom>().dest_id;
  37. case SemIR::Call::Kind: {
  38. auto call = init.As<SemIR::Call>();
  39. if (!SemIR::GetInitRepr(sem_ir, call.type_id).has_return_slot()) {
  40. return SemIR::InstId::Invalid;
  41. }
  42. if (!call.args_id.is_valid()) {
  43. // Argument initialization failed, so we have no return slot.
  44. return SemIR::InstId::Invalid;
  45. }
  46. return sem_ir.inst_blocks().Get(call.args_id).back();
  47. }
  48. }
  49. }
  50. }
  51. // Marks the initializer `init_id` as initializing `target_id`.
  52. static auto MarkInitializerFor(SemIR::File& sem_ir, SemIR::InstId init_id,
  53. SemIR::InstId target_id,
  54. PendingBlock& target_block) -> void {
  55. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  56. if (return_slot_id.is_valid()) {
  57. // Replace the temporary in the return slot with a reference to our target.
  58. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  59. SemIR::TemporaryStorage::Kind)
  60. << "Return slot for initializer does not contain a temporary; "
  61. << "initialized multiple times? Have "
  62. << sem_ir.insts().Get(return_slot_id);
  63. target_block.MergeReplacing(return_slot_id, target_id);
  64. }
  65. }
  66. // Commits to using a temporary to store the result of the initializing
  67. // expression described by `init_id`, and returns the location of the
  68. // temporary. If `discarded` is `true`, the result is discarded, and no
  69. // temporary will be created if possible; if no temporary is created, the
  70. // return value will be `SemIR::InstId::Invalid`.
  71. static auto FinalizeTemporary(Context& context, SemIR::InstId init_id,
  72. bool discarded) -> SemIR::InstId {
  73. auto& sem_ir = context.sem_ir();
  74. auto return_slot_id = FindReturnSlotForInitializer(sem_ir, init_id);
  75. if (return_slot_id.is_valid()) {
  76. // The return slot should already have a materialized temporary in it.
  77. CARBON_CHECK(sem_ir.insts().Get(return_slot_id).kind() ==
  78. SemIR::TemporaryStorage::Kind)
  79. << "Return slot for initializer does not contain a temporary; "
  80. << "initialized multiple times? Have "
  81. << sem_ir.insts().Get(return_slot_id);
  82. auto init = sem_ir.insts().Get(init_id);
  83. return context.AddInst(
  84. {sem_ir.insts().GetNodeId(init_id),
  85. SemIR::Temporary{init.type_id(), return_slot_id, init_id}});
  86. }
  87. if (discarded) {
  88. // Don't invent a temporary that we're going to discard.
  89. return SemIR::InstId::Invalid;
  90. }
  91. // The initializer has no return slot, but we want to produce a temporary
  92. // object. Materialize one now.
  93. // TODO: Consider using an invalid ID to mean that we immediately
  94. // materialize and initialize a temporary, rather than two separate
  95. // instructions.
  96. auto init = sem_ir.insts().Get(init_id);
  97. auto node_id = sem_ir.insts().GetNodeId(init_id);
  98. auto temporary_id =
  99. context.AddInst({node_id, SemIR::TemporaryStorage{init.type_id()}});
  100. return context.AddInst(
  101. {node_id, SemIR::Temporary{init.type_id(), temporary_id, init_id}});
  102. }
  103. // Materialize a temporary to hold the result of the given expression if it is
  104. // an initializing expression.
  105. static auto MaterializeIfInitializing(Context& context, SemIR::InstId expr_id)
  106. -> SemIR::InstId {
  107. if (GetExprCategory(context.sem_ir(), expr_id) ==
  108. SemIR::ExprCategory::Initializing) {
  109. return FinalizeTemporary(context, expr_id, /*discarded=*/false);
  110. }
  111. return expr_id;
  112. }
  113. // Creates and adds an instruction to perform element access into an aggregate.
  114. template <typename AccessInstT, typename InstBlockT>
  115. static auto MakeElementAccessInst(Context& context, Parse::NodeId node_id,
  116. SemIR::InstId aggregate_id,
  117. SemIR::TypeId elem_type_id, InstBlockT& block,
  118. std::size_t i) {
  119. if constexpr (std::is_same_v<AccessInstT, SemIR::ArrayIndex>) {
  120. // TODO: Add a new instruction kind for indexing an array at a constant
  121. // index so that we don't need an integer literal instruction here, and
  122. // remove this special case.
  123. auto index_id = block.AddInst(
  124. {node_id,
  125. SemIR::IntLiteral{context.GetBuiltinType(SemIR::BuiltinKind::IntType),
  126. context.ints().Add(llvm::APInt(32, i))}});
  127. return block.AddInst(
  128. {node_id, AccessInstT{elem_type_id, aggregate_id, index_id}});
  129. } else {
  130. return block.AddInst({node_id, AccessInstT{elem_type_id, aggregate_id,
  131. SemIR::ElementIndex(i)}});
  132. }
  133. }
  134. // Converts an element of one aggregate so that it can be used as an element of
  135. // another aggregate.
  136. //
  137. // For the source: `src_id` is the source aggregate, `src_elem_type` is the
  138. // element type, `i` is the index, and `SourceAccessInstT` is the kind of
  139. // instruction used to access the source element.
  140. //
  141. // For the target: `kind` is the kind of conversion or initialization,
  142. // `target_elem_type` is the element type. For initialization, `target_id` is
  143. // the destination, `target_block` is a pending block for target location
  144. // calculations that will be spliced as the return slot of the initializer if
  145. // necessary, `i` is the index, and `TargetAccessInstT` is the kind of
  146. // instruction used to access the destination element.
  147. template <typename SourceAccessInstT, typename TargetAccessInstT>
  148. static auto ConvertAggregateElement(
  149. Context& context, Parse::NodeId node_id, SemIR::InstId src_id,
  150. SemIR::TypeId src_elem_type,
  151. llvm::ArrayRef<SemIR::InstId> src_literal_elems,
  152. ConversionTarget::Kind kind, SemIR::InstId target_id,
  153. SemIR::TypeId target_elem_type, PendingBlock* target_block, std::size_t i) {
  154. // Compute the location of the source element. This goes into the current code
  155. // block, not into the target block.
  156. // TODO: Ideally we would discard this instruction if it's unused.
  157. auto src_elem_id =
  158. !src_literal_elems.empty()
  159. ? src_literal_elems[i]
  160. : MakeElementAccessInst<SourceAccessInstT>(context, node_id, src_id,
  161. src_elem_type, context, i);
  162. // If we're performing a conversion rather than an initialization, we won't
  163. // have or need a target.
  164. ConversionTarget target = {.kind = kind, .type_id = target_elem_type};
  165. if (!target.is_initializer()) {
  166. return Convert(context, node_id, src_elem_id, target);
  167. }
  168. // Compute the location of the target element and initialize it.
  169. PendingBlock::DiscardUnusedInstsScope scope(target_block);
  170. target.init_block = target_block;
  171. target.init_id = MakeElementAccessInst<TargetAccessInstT>(
  172. context, node_id, target_id, target_elem_type, *target_block, i);
  173. return Convert(context, node_id, src_elem_id, target);
  174. }
  175. namespace {
  176. // A handle to a new block that may be modified, with copy-on-write semantics.
  177. //
  178. // The constructor is given the ID of an existing block that provides the
  179. // initial contents of the new block. The new block is lazily allocated; if no
  180. // modifications have been made, the `id()` function will return the original
  181. // block ID.
  182. //
  183. // This is intended to avoid an unnecessary block allocation in the case where
  184. // the new block ends up being exactly the same as the original block.
  185. class CopyOnWriteBlock {
  186. public:
  187. // Constructs the block. If `source_id` is valid, it is used as the initial
  188. // value of the block. Otherwise, uninitialized storage for `size` elements
  189. // is allocated.
  190. CopyOnWriteBlock(SemIR::File& file, SemIR::InstBlockId source_id, size_t size)
  191. : file_(file), source_id_(source_id) {
  192. if (!source_id_.is_valid()) {
  193. id_ = file_.inst_blocks().AddUninitialized(size);
  194. }
  195. }
  196. auto id() const -> SemIR::InstBlockId { return id_; }
  197. auto Set(int i, SemIR::InstId value) -> void {
  198. if (source_id_.is_valid() && file_.inst_blocks().Get(id_)[i] == value) {
  199. return;
  200. }
  201. if (id_ == source_id_) {
  202. id_ = file_.inst_blocks().Add(file_.inst_blocks().Get(source_id_));
  203. }
  204. file_.inst_blocks().Get(id_)[i] = value;
  205. }
  206. private:
  207. SemIR::File& file_;
  208. SemIR::InstBlockId source_id_;
  209. SemIR::InstBlockId id_ = source_id_;
  210. };
  211. } // namespace
  212. // Performs a conversion from a tuple to an array type. This function only
  213. // converts the type, and does not perform a final conversion to the requested
  214. // expression category.
  215. static auto ConvertTupleToArray(Context& context, SemIR::TupleType tuple_type,
  216. SemIR::ArrayType array_type,
  217. SemIR::InstId value_id, ConversionTarget target)
  218. -> SemIR::InstId {
  219. auto& sem_ir = context.sem_ir();
  220. auto tuple_elem_types = sem_ir.type_blocks().Get(tuple_type.elements_id);
  221. auto value = sem_ir.insts().Get(value_id);
  222. auto value_node_id = sem_ir.insts().GetNodeId(value_id);
  223. // If we're initializing from a tuple literal, we will use its elements
  224. // directly. Otherwise, materialize a temporary if needed and index into the
  225. // result.
  226. llvm::ArrayRef<SemIR::InstId> literal_elems;
  227. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  228. literal_elems = sem_ir.inst_blocks().Get(tuple_literal->elements_id);
  229. } else {
  230. value_id = MaterializeIfInitializing(context, value_id);
  231. }
  232. // Check that the tuple is the right size.
  233. uint64_t array_bound = sem_ir.GetArrayBoundValue(array_type.bound_id);
  234. if (tuple_elem_types.size() != array_bound) {
  235. CARBON_DIAGNOSTIC(
  236. ArrayInitFromLiteralArgCountMismatch, Error,
  237. "Cannot initialize array of {0} element(s) from {1} initializer(s).",
  238. uint64_t, size_t);
  239. CARBON_DIAGNOSTIC(ArrayInitFromExprArgCountMismatch, Error,
  240. "Cannot initialize array of {0} element(s) from tuple "
  241. "with {1} element(s).",
  242. uint64_t, size_t);
  243. context.emitter().Emit(value_node_id,
  244. literal_elems.empty()
  245. ? ArrayInitFromExprArgCountMismatch
  246. : ArrayInitFromLiteralArgCountMismatch,
  247. array_bound, tuple_elem_types.size());
  248. return SemIR::InstId::BuiltinError;
  249. }
  250. PendingBlock target_block_storage(context);
  251. PendingBlock* target_block =
  252. target.init_block ? target.init_block : &target_block_storage;
  253. // Arrays are always initialized in-place. Allocate a temporary as the
  254. // destination for the array initialization if we weren't given one.
  255. SemIR::InstId return_slot_id = target.init_id;
  256. if (!target.init_id.is_valid()) {
  257. return_slot_id = target_block->AddInst(
  258. {value_node_id, SemIR::TemporaryStorage{target.type_id}});
  259. }
  260. // Initialize each element of the array from the corresponding element of the
  261. // tuple.
  262. // TODO: Annotate diagnostics coming from here with the array element index,
  263. // if initializing from a tuple literal.
  264. llvm::SmallVector<SemIR::InstId> inits;
  265. inits.reserve(array_bound + 1);
  266. for (auto [i, src_type_id] : llvm::enumerate(tuple_elem_types)) {
  267. // TODO: This call recurses back into conversion. Switch to an iterative
  268. // approach.
  269. auto init_id =
  270. ConvertAggregateElement<SemIR::TupleAccess, SemIR::ArrayIndex>(
  271. context, value_node_id, value_id, src_type_id, literal_elems,
  272. ConversionTarget::FullInitializer, return_slot_id,
  273. array_type.element_type_id, target_block, i);
  274. if (init_id == SemIR::InstId::BuiltinError) {
  275. return SemIR::InstId::BuiltinError;
  276. }
  277. inits.push_back(init_id);
  278. }
  279. // Flush the temporary here if we didn't insert it earlier, so we can add a
  280. // reference to the return slot.
  281. target_block->InsertHere();
  282. return context.AddInst(
  283. {value_node_id,
  284. SemIR::ArrayInit{target.type_id, sem_ir.inst_blocks().Add(inits),
  285. return_slot_id}});
  286. }
  287. // Performs a conversion from a tuple to a tuple type. This function only
  288. // converts the type, and does not perform a final conversion to the requested
  289. // expression category.
  290. static auto ConvertTupleToTuple(Context& context, SemIR::TupleType src_type,
  291. SemIR::TupleType dest_type,
  292. SemIR::InstId value_id, ConversionTarget target)
  293. -> SemIR::InstId {
  294. auto& sem_ir = context.sem_ir();
  295. auto src_elem_types = sem_ir.type_blocks().Get(src_type.elements_id);
  296. auto dest_elem_types = sem_ir.type_blocks().Get(dest_type.elements_id);
  297. auto value = sem_ir.insts().Get(value_id);
  298. auto value_node_id = sem_ir.insts().GetNodeId(value_id);
  299. // If we're initializing from a tuple literal, we will use its elements
  300. // directly. Otherwise, materialize a temporary if needed and index into the
  301. // result.
  302. llvm::ArrayRef<SemIR::InstId> literal_elems;
  303. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  304. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  305. literal_elems_id = tuple_literal->elements_id;
  306. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  307. } else {
  308. value_id = MaterializeIfInitializing(context, value_id);
  309. }
  310. // Check that the tuples are the same size.
  311. if (src_elem_types.size() != dest_elem_types.size()) {
  312. CARBON_DIAGNOSTIC(TupleInitElementCountMismatch, Error,
  313. "Cannot initialize tuple of {0} element(s) from tuple "
  314. "with {1} element(s).",
  315. size_t, size_t);
  316. context.emitter().Emit(value_node_id, TupleInitElementCountMismatch,
  317. dest_elem_types.size(), src_elem_types.size());
  318. return SemIR::InstId::BuiltinError;
  319. }
  320. // If we're forming an initializer, then we want an initializer for each
  321. // element. Otherwise, we want a value representation for each element.
  322. // Perform a final destination store if we're performing an in-place
  323. // initialization.
  324. bool is_init = target.is_initializer();
  325. ConversionTarget::Kind inner_kind =
  326. !is_init ? ConversionTarget::Value
  327. : SemIR::GetInitRepr(sem_ir, target.type_id).kind ==
  328. SemIR::InitRepr::InPlace
  329. ? ConversionTarget::FullInitializer
  330. : ConversionTarget::Initializer;
  331. // Initialize each element of the destination from the corresponding element
  332. // of the source.
  333. // TODO: Annotate diagnostics coming from here with the element index.
  334. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_types.size());
  335. for (auto [i, src_type_id, dest_type_id] :
  336. llvm::enumerate(src_elem_types, dest_elem_types)) {
  337. // TODO: This call recurses back into conversion. Switch to an iterative
  338. // approach.
  339. auto init_id =
  340. ConvertAggregateElement<SemIR::TupleAccess, SemIR::TupleAccess>(
  341. context, value_node_id, value_id, src_type_id, literal_elems,
  342. inner_kind, target.init_id, dest_type_id, target.init_block, i);
  343. if (init_id == SemIR::InstId::BuiltinError) {
  344. return SemIR::InstId::BuiltinError;
  345. }
  346. new_block.Set(i, init_id);
  347. }
  348. if (is_init) {
  349. target.init_block->InsertHere();
  350. return context.AddInst(
  351. {value_node_id,
  352. SemIR::TupleInit{target.type_id, new_block.id(), target.init_id}});
  353. } else {
  354. return context.AddInst(
  355. {value_node_id, SemIR::TupleValue{target.type_id, new_block.id()}});
  356. }
  357. }
  358. // Common implementation for ConvertStructToStruct and ConvertStructToClass.
  359. template <typename TargetAccessInstT>
  360. static auto ConvertStructToStructOrClass(Context& context,
  361. SemIR::StructType src_type,
  362. SemIR::StructType dest_type,
  363. SemIR::InstId value_id,
  364. ConversionTarget target, bool is_class)
  365. -> SemIR::InstId {
  366. auto& sem_ir = context.sem_ir();
  367. auto src_elem_fields = sem_ir.inst_blocks().Get(src_type.fields_id);
  368. auto dest_elem_fields = sem_ir.inst_blocks().Get(dest_type.fields_id);
  369. auto value = sem_ir.insts().Get(value_id);
  370. auto value_node_id = sem_ir.insts().GetNodeId(value_id);
  371. // If we're initializing from a struct literal, we will use its elements
  372. // directly. Otherwise, materialize a temporary if needed and index into the
  373. // result.
  374. llvm::ArrayRef<SemIR::InstId> literal_elems;
  375. auto literal_elems_id = SemIR::InstBlockId::Invalid;
  376. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>()) {
  377. literal_elems_id = struct_literal->elements_id;
  378. literal_elems = sem_ir.inst_blocks().Get(literal_elems_id);
  379. } else {
  380. value_id = MaterializeIfInitializing(context, value_id);
  381. }
  382. // Check that the structs are the same size.
  383. // TODO: If not, include the name of the first source field that doesn't
  384. // exist in the destination or vice versa in the diagnostic.
  385. if (src_elem_fields.size() != dest_elem_fields.size()) {
  386. CARBON_DIAGNOSTIC(StructInitElementCountMismatch, Error,
  387. "Cannot initialize {0} with {1} field(s) from struct "
  388. "with {2} field(s).",
  389. llvm::StringLiteral, size_t, size_t);
  390. context.emitter().Emit(
  391. value_node_id, StructInitElementCountMismatch,
  392. is_class ? llvm::StringLiteral("class") : llvm::StringLiteral("struct"),
  393. dest_elem_fields.size(), src_elem_fields.size());
  394. return SemIR::InstId::BuiltinError;
  395. }
  396. // Prepare to look up fields in the source by index.
  397. llvm::SmallDenseMap<SemIR::NameId, int32_t> src_field_indexes;
  398. if (src_type.fields_id != dest_type.fields_id) {
  399. for (auto [i, field_id] : llvm::enumerate(src_elem_fields)) {
  400. auto [it, added] = src_field_indexes.insert(
  401. {context.insts().GetAs<SemIR::StructTypeField>(field_id).name_id, i});
  402. CARBON_CHECK(added) << "Duplicate field in source structure";
  403. }
  404. }
  405. // If we're forming an initializer, then we want an initializer for each
  406. // element. Otherwise, we want a value representation for each element.
  407. // Perform a final destination store if we're performing an in-place
  408. // initialization.
  409. bool is_init = target.is_initializer();
  410. ConversionTarget::Kind inner_kind =
  411. !is_init ? ConversionTarget::Value
  412. : SemIR::GetInitRepr(sem_ir, target.type_id).kind ==
  413. SemIR::InitRepr::InPlace
  414. ? ConversionTarget::FullInitializer
  415. : ConversionTarget::Initializer;
  416. // Initialize each element of the destination from the corresponding element
  417. // of the source.
  418. // TODO: Annotate diagnostics coming from here with the element index.
  419. CopyOnWriteBlock new_block(sem_ir, literal_elems_id, src_elem_fields.size());
  420. for (auto [i, dest_field_id] : llvm::enumerate(dest_elem_fields)) {
  421. auto dest_field =
  422. sem_ir.insts().GetAs<SemIR::StructTypeField>(dest_field_id);
  423. // Find the matching source field.
  424. auto src_field_index = i;
  425. if (src_type.fields_id != dest_type.fields_id) {
  426. auto src_field_it = src_field_indexes.find(dest_field.name_id);
  427. if (src_field_it == src_field_indexes.end()) {
  428. if (literal_elems_id.is_valid()) {
  429. CARBON_DIAGNOSTIC(
  430. StructInitMissingFieldInLiteral, Error,
  431. "Missing value for field `{0}` in struct initialization.",
  432. SemIR::NameId);
  433. context.emitter().Emit(value_node_id, StructInitMissingFieldInLiteral,
  434. dest_field.name_id);
  435. } else {
  436. CARBON_DIAGNOSTIC(StructInitMissingFieldInConversion, Error,
  437. "Cannot convert from struct type `{0}` to `{1}`: "
  438. "missing field `{2}` in source type.",
  439. SemIR::TypeId, SemIR::TypeId, SemIR::NameId);
  440. context.emitter().Emit(
  441. value_node_id, StructInitMissingFieldInConversion,
  442. value.type_id(), target.type_id, dest_field.name_id);
  443. }
  444. return SemIR::InstId::BuiltinError;
  445. }
  446. src_field_index = src_field_it->second;
  447. }
  448. auto src_field = sem_ir.insts().GetAs<SemIR::StructTypeField>(
  449. src_elem_fields[src_field_index]);
  450. // TODO: This call recurses back into conversion. Switch to an iterative
  451. // approach.
  452. auto init_id =
  453. ConvertAggregateElement<SemIR::StructAccess, TargetAccessInstT>(
  454. context, value_node_id, value_id, src_field.field_type_id,
  455. literal_elems, inner_kind, target.init_id, dest_field.field_type_id,
  456. target.init_block, src_field_index);
  457. if (init_id == SemIR::InstId::BuiltinError) {
  458. return SemIR::InstId::BuiltinError;
  459. }
  460. new_block.Set(i, init_id);
  461. }
  462. if (is_class) {
  463. target.init_block->InsertHere();
  464. CARBON_CHECK(is_init)
  465. << "Converting directly to a class value is not supported";
  466. return context.AddInst(
  467. {value_node_id,
  468. SemIR::ClassInit{target.type_id, new_block.id(), target.init_id}});
  469. } else if (is_init) {
  470. target.init_block->InsertHere();
  471. return context.AddInst(
  472. {value_node_id,
  473. SemIR::StructInit{target.type_id, new_block.id(), target.init_id}});
  474. } else {
  475. return context.AddInst(
  476. {value_node_id, SemIR::StructValue{target.type_id, new_block.id()}});
  477. }
  478. }
  479. // Performs a conversion from a struct to a struct type. This function only
  480. // converts the type, and does not perform a final conversion to the requested
  481. // expression category.
  482. static auto ConvertStructToStruct(Context& context, SemIR::StructType src_type,
  483. SemIR::StructType dest_type,
  484. SemIR::InstId value_id,
  485. ConversionTarget target) -> SemIR::InstId {
  486. return ConvertStructToStructOrClass<SemIR::StructAccess>(
  487. context, src_type, dest_type, value_id, target, /*is_class=*/false);
  488. }
  489. // Performs a conversion from a struct to a class type. This function only
  490. // converts the type, and does not perform a final conversion to the requested
  491. // expression category.
  492. static auto ConvertStructToClass(Context& context, SemIR::StructType src_type,
  493. SemIR::ClassType dest_type,
  494. SemIR::InstId value_id,
  495. ConversionTarget target) -> SemIR::InstId {
  496. PendingBlock target_block(context);
  497. auto& class_info = context.classes().Get(dest_type.class_id);
  498. if (class_info.inheritance_kind == SemIR::Class::Abstract) {
  499. CARBON_DIAGNOSTIC(ConstructionOfAbstractClass, Error,
  500. "Cannot construct instance of abstract class. "
  501. "Consider using `partial {0}` instead.",
  502. SemIR::TypeId);
  503. context.emitter().Emit(value_id, ConstructionOfAbstractClass,
  504. target.type_id);
  505. return SemIR::InstId::BuiltinError;
  506. }
  507. if (class_info.object_repr_id == SemIR::TypeId::Error) {
  508. return SemIR::InstId::BuiltinError;
  509. }
  510. auto dest_struct_type =
  511. context.types().GetAs<SemIR::StructType>(class_info.object_repr_id);
  512. // If we're trying to create a class value, form a temporary for the value to
  513. // point to.
  514. bool need_temporary = !target.is_initializer();
  515. if (need_temporary) {
  516. target.kind = ConversionTarget::Initializer;
  517. target.init_block = &target_block;
  518. target.init_id =
  519. target_block.AddInst({context.insts().GetNodeId(value_id),
  520. SemIR::TemporaryStorage{target.type_id}});
  521. }
  522. auto result_id = ConvertStructToStructOrClass<SemIR::ClassElementAccess>(
  523. context, src_type, dest_struct_type, value_id, target, /*is_class=*/true);
  524. if (need_temporary) {
  525. target_block.InsertHere();
  526. result_id = context.AddInst(
  527. {context.insts().GetNodeId(value_id),
  528. SemIR::Temporary{target.type_id, target.init_id, result_id}});
  529. }
  530. return result_id;
  531. }
  532. // An inheritance path is a sequence of `BaseDecl`s in order from derived to
  533. // base.
  534. using InheritancePath = llvm::SmallVector<SemIR::InstId>;
  535. // Computes the inheritance path from class `derived_id` to class `base_id`.
  536. // Returns nullopt if `derived_id` is not a class derived from `base_id`.
  537. static auto ComputeInheritancePath(Context& context, SemIR::TypeId derived_id,
  538. SemIR::TypeId base_id)
  539. -> std::optional<InheritancePath> {
  540. // We intend for NRVO to be applied to `result`. All `return` statements in
  541. // this function should `return result;`.
  542. std::optional<InheritancePath> result(std::in_place);
  543. if (!context.TryToCompleteType(derived_id)) {
  544. // TODO: Should we give an error here? If we don't, and there is an
  545. // inheritance path when the class is defined, we may have a coherence
  546. // problem.
  547. result = std::nullopt;
  548. return result;
  549. }
  550. while (derived_id != base_id) {
  551. auto derived_class_type =
  552. context.types().TryGetAs<SemIR::ClassType>(derived_id);
  553. if (!derived_class_type) {
  554. result = std::nullopt;
  555. break;
  556. }
  557. auto& derived_class = context.classes().Get(derived_class_type->class_id);
  558. if (!derived_class.base_id.is_valid()) {
  559. result = std::nullopt;
  560. break;
  561. }
  562. result->push_back(derived_class.base_id);
  563. derived_id = context.insts()
  564. .GetAs<SemIR::BaseDecl>(derived_class.base_id)
  565. .base_type_id;
  566. }
  567. return result;
  568. }
  569. // Performs a conversion from a derived class value or reference to a base class
  570. // value or reference.
  571. static auto ConvertDerivedToBase(Context& context, Parse::NodeId node_id,
  572. SemIR::InstId value_id,
  573. const InheritancePath& path) -> SemIR::InstId {
  574. // Materialize a temporary if necessary.
  575. value_id = ConvertToValueOrRefExpr(context, value_id);
  576. // Add a series of `.base` accesses.
  577. for (auto base_id : path) {
  578. auto base_decl = context.insts().GetAs<SemIR::BaseDecl>(base_id);
  579. value_id = context.AddInst(
  580. {node_id, SemIR::ClassElementAccess{base_decl.base_type_id, value_id,
  581. base_decl.index}});
  582. }
  583. return value_id;
  584. }
  585. // Performs a conversion from a derived class pointer to a base class pointer.
  586. static auto ConvertDerivedPointerToBasePointer(
  587. Context& context, Parse::NodeId node_id, SemIR::PointerType src_ptr_type,
  588. SemIR::TypeId dest_ptr_type_id, SemIR::InstId ptr_id,
  589. const InheritancePath& path) -> SemIR::InstId {
  590. // Form `*p`.
  591. ptr_id = ConvertToValueExpr(context, ptr_id);
  592. auto ref_id =
  593. context.AddInst({node_id, SemIR::Deref{src_ptr_type.pointee_id, ptr_id}});
  594. // Convert as a reference expression.
  595. ref_id = ConvertDerivedToBase(context, node_id, ref_id, path);
  596. // Take the address.
  597. return context.AddInst({node_id, SemIR::AddrOf{dest_ptr_type_id, ref_id}});
  598. }
  599. // Returns whether `category` is a valid expression category to produce as a
  600. // result of a conversion with kind `target_kind`, or at most needs a temporary
  601. // to be materialized.
  602. static auto IsValidExprCategoryForConversionTarget(
  603. SemIR::ExprCategory category, ConversionTarget::Kind target_kind) -> bool {
  604. switch (target_kind) {
  605. case ConversionTarget::Value:
  606. return category == SemIR::ExprCategory::Value;
  607. case ConversionTarget::ValueOrRef:
  608. case ConversionTarget::Discarded:
  609. return category == SemIR::ExprCategory::Value ||
  610. category == SemIR::ExprCategory::DurableRef ||
  611. category == SemIR::ExprCategory::EphemeralRef ||
  612. category == SemIR::ExprCategory::Initializing;
  613. case ConversionTarget::ExplicitAs:
  614. return true;
  615. case ConversionTarget::Initializer:
  616. case ConversionTarget::FullInitializer:
  617. return category == SemIR::ExprCategory::Initializing;
  618. }
  619. }
  620. static auto PerformBuiltinConversion(Context& context, Parse::NodeId node_id,
  621. SemIR::InstId value_id,
  622. ConversionTarget target) -> SemIR::InstId {
  623. auto& sem_ir = context.sem_ir();
  624. auto value = sem_ir.insts().Get(value_id);
  625. auto value_type_id = value.type_id();
  626. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  627. // Various forms of implicit conversion are supported as builtin conversions,
  628. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  629. // prelude. There are a few reasons we need to perform some of these
  630. // conversions as builtins:
  631. //
  632. // 1) Conversions from struct and tuple *literals* have special rules that
  633. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  634. // recurse into the elements of the literal before performing
  635. // initialization in order to avoid unnecessary conversions between
  636. // expression categories that would be performed by `ImplicitAs.Convert`.
  637. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  638. // the value of the facet, not only its type, and therefore cannot be
  639. // modeled by `ImplicitAs`.
  640. // 3) Some of these conversions are used while checking the library
  641. // definition of `ImplicitAs` itself or implementations of it.
  642. //
  643. // We also expect to see better performance by avoiding an `impl` lookup for
  644. // common conversions.
  645. //
  646. // TODO: We should provide a debugging flag to turn off as many of these
  647. // builtin conversions as we can so that we can test that they do the same
  648. // thing as the library implementations.
  649. //
  650. // The builtin conversions that correspond to `impl`s in the library all
  651. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  652. // being specialized in any of these cases.
  653. // If the value is already of the right kind and expression category, there's
  654. // nothing to do. Performing a conversion would decompose and rebuild tuples
  655. // and structs, so it's important that we bail out early in this case.
  656. if (value_type_id == target.type_id) {
  657. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  658. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  659. return value_id;
  660. }
  661. // If the source is an initializing expression, we may be able to pull a
  662. // value right out of it.
  663. if (value_cat == SemIR::ExprCategory::Initializing &&
  664. IsValidExprCategoryForConversionTarget(SemIR::ExprCategory::Value,
  665. target.kind) &&
  666. SemIR::GetInitRepr(sem_ir, value_type_id).kind ==
  667. SemIR::InitRepr::ByCopy) {
  668. auto value_rep = SemIR::GetValueRepr(sem_ir, value_type_id);
  669. if (value_rep.kind == SemIR::ValueRepr::Copy &&
  670. value_rep.type_id == value_type_id) {
  671. // The initializer produces an object representation by copy, and the
  672. // value representation is a copy of the object representation, so we
  673. // already have a value of the right form.
  674. return context.AddInst(
  675. {node_id, SemIR::ValueOfInitializer{value_type_id, value_id}});
  676. }
  677. }
  678. }
  679. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  680. // converts to Ui.
  681. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  682. if (auto src_tuple_type =
  683. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  684. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  685. value_id, target);
  686. }
  687. }
  688. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  689. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  690. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  691. // to Ui.
  692. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  693. if (auto src_struct_type =
  694. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  695. return ConvertStructToStruct(context, *src_struct_type,
  696. *target_struct_type, value_id, target);
  697. }
  698. }
  699. // A tuple (T1, T2, ..., Tn) converts to [T; n] if each Ti converts to T.
  700. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  701. if (auto src_tuple_type =
  702. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  703. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  704. value_id, target);
  705. }
  706. }
  707. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  708. // if it converts to the struct type that is the class's representation type
  709. // (a struct with the same fields as the class, plus a base field where
  710. // relevant).
  711. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  712. if (auto src_struct_type =
  713. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  714. return ConvertStructToClass(context, *src_struct_type, *target_class_type,
  715. value_id, target);
  716. }
  717. // An expression of type T converts to U if T is a class derived from U.
  718. if (auto path =
  719. ComputeInheritancePath(context, value_type_id, target.type_id);
  720. path && !path->empty()) {
  721. return ConvertDerivedToBase(context, node_id, value_id, *path);
  722. }
  723. }
  724. // A pointer T* converts to U* if T is a class derived from U.
  725. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  726. if (auto src_pointer_type =
  727. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  728. if (auto path =
  729. ComputeInheritancePath(context, src_pointer_type->pointee_id,
  730. target_pointer_type->pointee_id);
  731. path && !path->empty()) {
  732. return ConvertDerivedPointerToBasePointer(
  733. context, node_id, *src_pointer_type, target.type_id, value_id,
  734. *path);
  735. }
  736. }
  737. }
  738. if (target.type_id == SemIR::TypeId::TypeType) {
  739. // A tuple of types converts to type `type`.
  740. // TODO: This should apply even for non-literal tuples.
  741. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  742. llvm::SmallVector<SemIR::TypeId> type_ids;
  743. for (auto tuple_inst_id :
  744. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  745. // TODO: This call recurses back into conversion. Switch to an
  746. // iterative approach.
  747. type_ids.push_back(ExprAsType(context, node_id, tuple_inst_id));
  748. }
  749. auto tuple_type_id = context.GetTupleType(type_ids);
  750. return sem_ir.types().GetInstId(tuple_type_id);
  751. }
  752. // `{}` converts to `{} as type`.
  753. // TODO: This conversion should also be performed for a non-literal value
  754. // of type `{}`.
  755. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  756. struct_literal &&
  757. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  758. value_id = sem_ir.types().GetInstId(value_type_id);
  759. }
  760. // Facet type conversions: a value T of facet type F1 can be implicitly
  761. // converted to facet type F2 if T satisfies the requirements of F2.
  762. //
  763. // TODO: Support this conversion in general. For now we only support it in
  764. // the case where F1 is an interface type and F2 is `type`.
  765. // TODO: Support converting tuple and struct values to facet types,
  766. // combining the above conversions and this one in a single conversion.
  767. if (sem_ir.types().Is<SemIR::InterfaceType>(value_type_id)) {
  768. return context.AddInst(
  769. {node_id, SemIR::FacetTypeAccess{target.type_id, value_id}});
  770. }
  771. }
  772. // No builtin conversion applies.
  773. return value_id;
  774. }
  775. // Given a value expression, form a corresponding initializer that copies from
  776. // that value, if it is possible to do so.
  777. static auto PerformCopy(Context& context, SemIR::InstId expr_id)
  778. -> SemIR::InstId {
  779. auto expr = context.insts().Get(expr_id);
  780. auto type_id = expr.type_id();
  781. if (type_id == SemIR::TypeId::Error) {
  782. return SemIR::InstId::BuiltinError;
  783. }
  784. // TODO: Directly track on the value representation whether it's a copy of
  785. // the object representation.
  786. auto value_rep = SemIR::GetValueRepr(context.sem_ir(), type_id);
  787. if (value_rep.kind == SemIR::ValueRepr::Copy &&
  788. value_rep.aggregate_kind == SemIR::ValueRepr::NotAggregate &&
  789. value_rep.type_id == type_id) {
  790. // For by-value scalar types, no explicit action is required. Initializing
  791. // from a value expression is treated as copying the value.
  792. return expr_id;
  793. }
  794. // TODO: We don't yet have rules for whether and when a class type is
  795. // copyable, or how to perform the copy.
  796. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  797. "Cannot copy value of type `{0}`.", SemIR::TypeId);
  798. context.emitter().Emit(expr_id, CopyOfUncopyableType, type_id);
  799. return SemIR::InstId::BuiltinError;
  800. }
  801. auto Convert(Context& context, Parse::NodeId node_id, SemIR::InstId expr_id,
  802. ConversionTarget target) -> SemIR::InstId {
  803. auto& sem_ir = context.sem_ir();
  804. auto orig_expr_id = expr_id;
  805. // Start by making sure both sides are valid. If any part is invalid, the
  806. // result is invalid and we shouldn't error.
  807. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::TypeId::Error ||
  808. target.type_id == SemIR::TypeId::Error) {
  809. return SemIR::InstId::BuiltinError;
  810. }
  811. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  812. // TODO: We currently encounter this for use of namespaces and functions.
  813. // We should provide a better diagnostic for inappropriate use of
  814. // namespace names, and allow use of functions as values.
  815. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  816. "Expression cannot be used as a value.");
  817. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  818. return SemIR::InstId::BuiltinError;
  819. }
  820. // We can only perform initialization for complete types.
  821. if (!context.TryToCompleteType(target.type_id, [&] {
  822. CARBON_DIAGNOSTIC(IncompleteTypeInInit, Error,
  823. "Initialization of incomplete type `{0}`.",
  824. SemIR::TypeId);
  825. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  826. "Forming value of incomplete type `{0}`.",
  827. SemIR::TypeId);
  828. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  829. "Invalid use of incomplete type `{0}`.",
  830. SemIR::TypeId);
  831. return context.emitter().Build(node_id,
  832. target.is_initializer()
  833. ? IncompleteTypeInInit
  834. : target.kind == ConversionTarget::Value
  835. ? IncompleteTypeInValueConversion
  836. : IncompleteTypeInConversion,
  837. target.type_id);
  838. })) {
  839. return SemIR::InstId::BuiltinError;
  840. }
  841. // Check whether any builtin conversion applies.
  842. expr_id = PerformBuiltinConversion(context, node_id, expr_id, target);
  843. if (expr_id == SemIR::InstId::BuiltinError) {
  844. return expr_id;
  845. }
  846. // If the types don't match at this point, we can't perform the conversion.
  847. // TODO: Look for an `ImplicitAs` impl, or an `As` impl in the case where
  848. // `target.kind == ConversionTarget::ExplicitAs`.
  849. SemIR::Inst expr = sem_ir.insts().Get(expr_id);
  850. if (expr.type_id() != target.type_id) {
  851. CARBON_DIAGNOSTIC(ImplicitAsConversionFailure, Error,
  852. "Cannot implicitly convert from `{0}` to `{1}`.",
  853. SemIR::TypeId, SemIR::TypeId);
  854. CARBON_DIAGNOSTIC(ExplicitAsConversionFailure, Error,
  855. "Cannot convert from `{0}` to `{1}` with `as`.",
  856. SemIR::TypeId, SemIR::TypeId);
  857. context.emitter()
  858. .Build(node_id,
  859. target.kind == ConversionTarget::ExplicitAs
  860. ? ExplicitAsConversionFailure
  861. : ImplicitAsConversionFailure,
  862. expr.type_id(), target.type_id)
  863. .Emit();
  864. return SemIR::InstId::BuiltinError;
  865. }
  866. // Track that we performed a type conversion, if we did so.
  867. if (orig_expr_id != expr_id) {
  868. expr_id = context.AddInst(
  869. {context.insts().GetNodeId(orig_expr_id),
  870. SemIR::Converted{target.type_id, orig_expr_id, expr_id}});
  871. }
  872. // For `as`, don't perform any value category conversions. In particular, an
  873. // identity conversion shouldn't change the expression category.
  874. if (target.kind == ConversionTarget::ExplicitAs) {
  875. return expr_id;
  876. }
  877. // Now perform any necessary value category conversions.
  878. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  879. case SemIR::ExprCategory::NotExpr:
  880. case SemIR::ExprCategory::Mixed:
  881. CARBON_FATAL() << "Unexpected expression " << expr
  882. << " after builtin conversions";
  883. case SemIR::ExprCategory::Error:
  884. return SemIR::InstId::BuiltinError;
  885. case SemIR::ExprCategory::Initializing:
  886. if (target.is_initializer()) {
  887. if (orig_expr_id == expr_id) {
  888. // Don't fill in the return slot if we created the expression through
  889. // a conversion. In that case, we will have created it with the
  890. // target already set.
  891. // TODO: Find a better way to track whether we need to do this.
  892. MarkInitializerFor(sem_ir, expr_id, target.init_id,
  893. *target.init_block);
  894. }
  895. break;
  896. }
  897. // Commit to using a temporary for this initializing expression.
  898. // TODO: Don't create a temporary if the initializing representation
  899. // is already a value representation.
  900. expr_id = FinalizeTemporary(context, expr_id,
  901. target.kind == ConversionTarget::Discarded);
  902. // We now have an ephemeral reference.
  903. [[fallthrough]];
  904. case SemIR::ExprCategory::DurableRef:
  905. case SemIR::ExprCategory::EphemeralRef:
  906. // If a reference expression is an acceptable result, we're done.
  907. if (target.kind == ConversionTarget::ValueOrRef ||
  908. target.kind == ConversionTarget::Discarded) {
  909. break;
  910. }
  911. // If we have a reference and don't want one, form a value binding.
  912. // TODO: Support types with custom value representations.
  913. expr_id = context.AddInst({context.insts().GetNodeId(expr_id),
  914. SemIR::BindValue{expr.type_id(), expr_id}});
  915. // We now have a value expression.
  916. [[fallthrough]];
  917. case SemIR::ExprCategory::Value:
  918. // When initializing from a value, perform a copy.
  919. if (target.is_initializer()) {
  920. expr_id = PerformCopy(context, expr_id);
  921. }
  922. break;
  923. }
  924. // Perform a final destination store, if necessary.
  925. if (target.kind == ConversionTarget::FullInitializer) {
  926. if (auto init_rep = SemIR::GetInitRepr(sem_ir, target.type_id);
  927. init_rep.kind == SemIR::InitRepr::ByCopy) {
  928. target.init_block->InsertHere();
  929. expr_id = context.AddInst(
  930. {node_id,
  931. SemIR::InitializeFrom{target.type_id, expr_id, target.init_id}});
  932. }
  933. }
  934. return expr_id;
  935. }
  936. auto Initialize(Context& context, Parse::NodeId node_id,
  937. SemIR::InstId target_id, SemIR::InstId value_id)
  938. -> SemIR::InstId {
  939. PendingBlock target_block(context);
  940. return Convert(context, node_id, value_id,
  941. {.kind = ConversionTarget::Initializer,
  942. .type_id = context.insts().Get(target_id).type_id(),
  943. .init_id = target_id,
  944. .init_block = &target_block});
  945. }
  946. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  947. -> SemIR::InstId {
  948. return Convert(context, context.insts().GetNodeId(expr_id), expr_id,
  949. {.kind = ConversionTarget::Value,
  950. .type_id = context.insts().Get(expr_id).type_id()});
  951. }
  952. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  953. -> SemIR::InstId {
  954. return Convert(context, context.insts().GetNodeId(expr_id), expr_id,
  955. {.kind = ConversionTarget::ValueOrRef,
  956. .type_id = context.insts().Get(expr_id).type_id()});
  957. }
  958. auto ConvertToValueOfType(Context& context, Parse::NodeId node_id,
  959. SemIR::InstId expr_id, SemIR::TypeId type_id)
  960. -> SemIR::InstId {
  961. return Convert(context, node_id, expr_id,
  962. {.kind = ConversionTarget::Value, .type_id = type_id});
  963. }
  964. auto ConvertToValueOrRefOfType(Context& context, Parse::NodeId node_id,
  965. SemIR::InstId expr_id, SemIR::TypeId type_id)
  966. -> SemIR::InstId {
  967. return Convert(context, node_id, expr_id,
  968. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  969. }
  970. auto ConvertToBoolValue(Context& context, Parse::NodeId node_id,
  971. SemIR::InstId value_id) -> SemIR::InstId {
  972. return ConvertToValueOfType(
  973. context, node_id, value_id,
  974. context.GetBuiltinType(SemIR::BuiltinKind::BoolType));
  975. }
  976. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  977. SemIR::InstId value_id, SemIR::TypeId type_id)
  978. -> SemIR::InstId {
  979. return Convert(context, as_node, value_id,
  980. {.kind = ConversionTarget::ExplicitAs, .type_id = type_id});
  981. }
  982. CARBON_DIAGNOSTIC(InCallToFunction, Note, "Calling function declared here.");
  983. // Convert the object argument in a method call to match the `self` parameter.
  984. static auto ConvertSelf(Context& context, Parse::NodeId call_node_id,
  985. SemIR::InstId callee_id,
  986. std::optional<SemIR::AddrPattern> addr_pattern,
  987. SemIR::InstId self_param_id, SemIR::Param self_param,
  988. SemIR::InstId self_id) -> SemIR::InstId {
  989. if (!self_id.is_valid()) {
  990. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  991. "Missing object argument in method call.");
  992. context.emitter()
  993. .Build(call_node_id, MissingObjectInMethodCall)
  994. .Note(callee_id, InCallToFunction)
  995. .Emit();
  996. return SemIR::InstId::BuiltinError;
  997. }
  998. DiagnosticAnnotationScope annotate_diagnostics(
  999. &context.emitter(), [&](auto& builder) {
  1000. CARBON_DIAGNOSTIC(
  1001. InCallToFunctionSelf, Note,
  1002. "Initializing `{0}` parameter of method declared here.",
  1003. llvm::StringLiteral);
  1004. builder.Note(self_param_id, InCallToFunctionSelf,
  1005. addr_pattern ? llvm::StringLiteral("addr self")
  1006. : llvm::StringLiteral("self"));
  1007. });
  1008. // For `addr self`, take the address of the object argument.
  1009. auto self_or_addr_id = self_id;
  1010. if (addr_pattern) {
  1011. self_or_addr_id = ConvertToValueOrRefExpr(context, self_or_addr_id);
  1012. auto self = context.insts().Get(self_or_addr_id);
  1013. switch (SemIR::GetExprCategory(context.sem_ir(), self_id)) {
  1014. case SemIR::ExprCategory::Error:
  1015. case SemIR::ExprCategory::DurableRef:
  1016. case SemIR::ExprCategory::EphemeralRef:
  1017. break;
  1018. default:
  1019. CARBON_DIAGNOSTIC(AddrSelfIsNonRef, Error,
  1020. "`addr self` method cannot be invoked on a value.");
  1021. context.emitter().Emit(TokenOnly(call_node_id), AddrSelfIsNonRef);
  1022. return SemIR::InstId::BuiltinError;
  1023. }
  1024. auto node_id = context.insts().GetNodeId(self_or_addr_id);
  1025. self_or_addr_id = context.AddInst(
  1026. {node_id, SemIR::AddrOf{context.GetPointerType(self.type_id()),
  1027. self_or_addr_id}});
  1028. }
  1029. return ConvertToValueOfType(context, call_node_id, self_or_addr_id,
  1030. self_param.type_id);
  1031. }
  1032. auto ConvertCallArgs(Context& context, Parse::NodeId call_node_id,
  1033. SemIR::InstId self_id,
  1034. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1035. SemIR::InstId return_storage_id, SemIR::InstId callee_id,
  1036. SemIR::InstBlockId implicit_param_refs_id,
  1037. SemIR::InstBlockId param_refs_id) -> SemIR::InstBlockId {
  1038. auto implicit_param_refs = context.inst_blocks().Get(implicit_param_refs_id);
  1039. auto param_refs = context.inst_blocks().Get(param_refs_id);
  1040. // If sizes mismatch, fail early.
  1041. if (arg_refs.size() != param_refs.size()) {
  1042. CARBON_DIAGNOSTIC(CallArgCountMismatch, Error,
  1043. "{0} argument(s) passed to function expecting "
  1044. "{1} argument(s).",
  1045. int, int);
  1046. context.emitter()
  1047. .Build(call_node_id, CallArgCountMismatch, arg_refs.size(),
  1048. param_refs.size())
  1049. .Note(callee_id, InCallToFunction)
  1050. .Emit();
  1051. return SemIR::InstBlockId::Invalid;
  1052. }
  1053. // Start building a block to hold the converted arguments.
  1054. llvm::SmallVector<SemIR::InstId> args;
  1055. args.reserve(implicit_param_refs.size() + param_refs.size() +
  1056. return_storage_id.is_valid());
  1057. // Check implicit parameters.
  1058. for (auto implicit_param_id : implicit_param_refs) {
  1059. auto addr_pattern =
  1060. context.insts().TryGetAs<SemIR::AddrPattern>(implicit_param_id);
  1061. auto [param_id, param] = SemIR::Function::GetParamFromParamRefId(
  1062. context.sem_ir(), implicit_param_id);
  1063. if (param.name_id == SemIR::NameId::SelfValue) {
  1064. auto converted_self_id =
  1065. ConvertSelf(context, call_node_id, callee_id, addr_pattern, param_id,
  1066. param, self_id);
  1067. if (converted_self_id == SemIR::InstId::BuiltinError) {
  1068. return SemIR::InstBlockId::Invalid;
  1069. }
  1070. args.push_back(converted_self_id);
  1071. } else {
  1072. // TODO: Form argument values for implicit parameters.
  1073. context.TODO(call_node_id, "Call with implicit parameters");
  1074. return SemIR::InstBlockId::Invalid;
  1075. }
  1076. }
  1077. int diag_param_index;
  1078. DiagnosticAnnotationScope annotate_diagnostics(
  1079. &context.emitter(), [&](auto& builder) {
  1080. CARBON_DIAGNOSTIC(
  1081. InCallToFunctionParam, Note,
  1082. "Initializing parameter {0} of function declared here.", int);
  1083. builder.Note(callee_id, InCallToFunctionParam, diag_param_index + 1);
  1084. });
  1085. // Check type conversions per-element.
  1086. for (auto [i, arg_id, param_id] : llvm::enumerate(arg_refs, param_refs)) {
  1087. diag_param_index = i;
  1088. auto param_type_id = context.insts().Get(param_id).type_id();
  1089. // TODO: Convert to the proper expression category. For now, we assume
  1090. // parameters are all `let` bindings.
  1091. auto converted_arg_id =
  1092. ConvertToValueOfType(context, call_node_id, arg_id, param_type_id);
  1093. if (converted_arg_id == SemIR::InstId::BuiltinError) {
  1094. return SemIR::InstBlockId::Invalid;
  1095. }
  1096. args.push_back(converted_arg_id);
  1097. }
  1098. // Track the return storage, if present.
  1099. if (return_storage_id.is_valid()) {
  1100. args.push_back(return_storage_id);
  1101. }
  1102. return context.inst_blocks().Add(args);
  1103. }
  1104. auto ExprAsType(Context& context, Parse::NodeId node_id, SemIR::InstId value_id)
  1105. -> SemIR::TypeId {
  1106. auto type_inst_id =
  1107. ConvertToValueOfType(context, node_id, value_id, SemIR::TypeId::TypeType);
  1108. if (type_inst_id == SemIR::InstId::BuiltinError) {
  1109. return SemIR::TypeId::Error;
  1110. }
  1111. auto type_const_id = context.constant_values().Get(type_inst_id);
  1112. if (!type_const_id.is_constant()) {
  1113. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1114. "Cannot evaluate type expression.");
  1115. context.emitter().Emit(node_id, TypeExprEvaluationFailure);
  1116. return SemIR::TypeId::Error;
  1117. }
  1118. return context.GetTypeIdForTypeConstant(type_const_id);
  1119. }
  1120. } // namespace Carbon::Check