convert.cpp 65 KB

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