convert.cpp 54 KB

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