convert.cpp 53 KB

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