convert.cpp 54 KB

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