convert.cpp 57 KB

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