convert.cpp 52 KB

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