convert.cpp 53 KB

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