convert.cpp 77 KB

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