convert.cpp 54 KB

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