convert.cpp 59 KB

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