convert.cpp 67 KB

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