convert.cpp 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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.sem_ir().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, bool allow_unsafe)
  737. -> bool {
  738. if (quals.HasAnyOf(SemIR::TypeQualifiers::Const) && !allow_unsafe &&
  739. SemIR::IsRefCategory(cat)) {
  740. // Removing `const` is an unsafe conversion for a reference expression.
  741. return false;
  742. }
  743. if (quals.HasAnyOf(SemIR::TypeQualifiers::Partial) &&
  744. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  745. // TODO: Allow removing `partial` for initializing expressions as a safe
  746. // conversion. `PerformBuiltinConversion` will need to initialize the vptr
  747. // as part of the conversion.
  748. return false;
  749. }
  750. if (quals.HasAnyOf(SemIR::TypeQualifiers::MaybeUnformed) &&
  751. (!allow_unsafe || cat == SemIR::ExprCategory::Initializing)) {
  752. // As an unsafe conversion, `MaybeUnformed` can be removed from a value or
  753. // reference expression.
  754. return false;
  755. }
  756. return true;
  757. }
  758. static auto DiagnoseConversionFailureToConstraintValue(
  759. Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  760. SemIR::TypeId target_type_id) -> void {
  761. CARBON_DCHECK(target_type_id == SemIR::TypeType::TypeId ||
  762. context.types().Is<SemIR::FacetType>(target_type_id));
  763. auto type_of_expr_id = context.insts().Get(expr_id).type_id();
  764. CARBON_CHECK(context.types().IsFacetType(type_of_expr_id));
  765. // If the source type is/has a facet value, then we can include its
  766. // FacetType in the diagnostic to help explain what interfaces the
  767. // source type implements.
  768. auto facet_value_inst_id = SemIR::InstId::None;
  769. if (auto facet_access_type =
  770. context.insts().TryGetAs<SemIR::FacetAccessType>(expr_id)) {
  771. facet_value_inst_id = facet_access_type->facet_value_inst_id;
  772. } else if (context.types().Is<SemIR::FacetType>(type_of_expr_id)) {
  773. facet_value_inst_id = expr_id;
  774. }
  775. if (facet_value_inst_id.has_value()) {
  776. CARBON_DIAGNOSTIC(ConversionFailureFacetToFacet, Error,
  777. "cannot convert type {0} that implements {1} into type "
  778. "implementing {2}",
  779. InstIdAsType, TypeOfInstId, SemIR::TypeId);
  780. context.emitter().Emit(loc_id, ConversionFailureFacetToFacet, expr_id,
  781. facet_value_inst_id, target_type_id);
  782. } else {
  783. CARBON_DIAGNOSTIC(ConversionFailureTypeToFacet, Error,
  784. "cannot convert type {0} into type implementing {1}",
  785. InstIdAsType, SemIR::TypeId);
  786. context.emitter().Emit(loc_id, ConversionFailureTypeToFacet, expr_id,
  787. target_type_id);
  788. }
  789. }
  790. static auto PerformBuiltinConversion(
  791. Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  792. ConversionTarget target, SemIR::ClassType* vtable_class_type = nullptr)
  793. -> SemIR::InstId {
  794. auto& sem_ir = context.sem_ir();
  795. auto value = sem_ir.insts().Get(value_id);
  796. auto value_type_id = value.type_id();
  797. auto target_type_inst = sem_ir.types().GetAsInst(target.type_id);
  798. // Various forms of implicit conversion are supported as builtin conversions,
  799. // either in addition to or instead of `impl`s of `ImplicitAs` in the Carbon
  800. // prelude. There are a few reasons we need to perform some of these
  801. // conversions as builtins:
  802. //
  803. // 1) Conversions from struct and tuple *literals* have special rules that
  804. // cannot be implemented by invoking `ImplicitAs`. Specifically, we must
  805. // recurse into the elements of the literal before performing
  806. // initialization in order to avoid unnecessary conversions between
  807. // expression categories that would be performed by `ImplicitAs.Convert`.
  808. // 2) (Not implemented yet) Conversion of a facet to a facet type depends on
  809. // the value of the facet, not only its type, and therefore cannot be
  810. // modeled by `ImplicitAs`.
  811. // 3) Some of these conversions are used while checking the library
  812. // definition of `ImplicitAs` itself or implementations of it.
  813. //
  814. // We also expect to see better performance by avoiding an `impl` lookup for
  815. // common conversions.
  816. //
  817. // TODO: We should provide a debugging flag to turn off as many of these
  818. // builtin conversions as we can so that we can test that they do the same
  819. // thing as the library implementations.
  820. //
  821. // The builtin conversions that correspond to `impl`s in the library all
  822. // correspond to `final impl`s, so we don't need to worry about `ImplicitAs`
  823. // being specialized in any of these cases.
  824. // If the value is already of the right kind and expression category, there's
  825. // nothing to do. Performing a conversion would decompose and rebuild tuples
  826. // and structs, so it's important that we bail out early in this case.
  827. if (value_type_id == target.type_id) {
  828. auto value_cat = SemIR::GetExprCategory(sem_ir, value_id);
  829. if (IsValidExprCategoryForConversionTarget(value_cat, target.kind)) {
  830. return value_id;
  831. }
  832. // If the source is an initializing expression, we may be able to pull a
  833. // value right out of it.
  834. if (value_cat == SemIR::ExprCategory::Initializing &&
  835. CanUseValueOfInitializer(sem_ir, value_type_id, target.kind)) {
  836. return AddInst<SemIR::ValueOfInitializer>(
  837. context, loc_id, {.type_id = value_type_id, .init_id = value_id});
  838. }
  839. // PerformBuiltinConversion converts each part of a tuple or struct, even
  840. // when the types are the same. This is not done for classes since they have
  841. // to define their conversions as part of their api.
  842. //
  843. // If a class adapts a tuple or struct, we convert each of its parts when
  844. // there's no other conversion going on (the source and target types are the
  845. // same). To do so, we have to insert a conversion of the value up to the
  846. // foundation and back down, and a conversion of the initializing object if
  847. // there is one.
  848. //
  849. // Implementation note: We do the conversion through a call to
  850. // PerformBuiltinConversion() call rather than a Convert() call to avoid
  851. // extraneous `converted` semir instructions on the adapted types, and as a
  852. // shortcut to doing the explicit calls to walk the parts of the
  853. // tuple/struct which happens inside PerformBuiltinConversion().
  854. if (auto foundation_type_id =
  855. context.types().GetTransitiveAdaptedType(value_type_id);
  856. foundation_type_id != value_type_id &&
  857. (context.types().Is<SemIR::TupleType>(foundation_type_id) ||
  858. context.types().Is<SemIR::StructType>(foundation_type_id))) {
  859. auto foundation_value_id = AddInst<SemIR::AsCompatible>(
  860. context, loc_id,
  861. {.type_id = foundation_type_id, .source_id = value_id});
  862. auto foundation_init_id = target.init_id;
  863. if (foundation_init_id != SemIR::InstId::None) {
  864. foundation_init_id = target.init_block->AddInst<SemIR::AsCompatible>(
  865. loc_id,
  866. {.type_id = foundation_type_id, .source_id = target.init_id});
  867. }
  868. {
  869. // While the types are the same, the conversion can still fail if it
  870. // performs a copy while converting the value to another category, and
  871. // the type (or some part of it) is not copyable.
  872. Diagnostics::AnnotationScope annotate_diagnostics(
  873. &context.emitter(), [&](auto& builder) {
  874. CARBON_DIAGNOSTIC(InCopy, Note, "in copy of {0}", TypeOfInstId);
  875. builder.Note(value_id, InCopy, value_id);
  876. });
  877. foundation_value_id =
  878. PerformBuiltinConversion(context, loc_id, foundation_value_id,
  879. {.kind = target.kind,
  880. .type_id = foundation_type_id,
  881. .init_id = foundation_init_id,
  882. .init_block = target.init_block,
  883. .diagnose = target.diagnose});
  884. if (foundation_value_id == SemIR::ErrorInst::InstId) {
  885. return SemIR::ErrorInst::InstId;
  886. }
  887. }
  888. return AddInst<SemIR::AsCompatible>(
  889. context, loc_id,
  890. {.type_id = target.type_id, .source_id = foundation_value_id});
  891. }
  892. }
  893. // T explicitly converts to U if T is compatible with U, and we're allowed to
  894. // remove / add any qualifiers that differ.
  895. if (target.is_explicit_as() && target.type_id != value_type_id) {
  896. auto [target_foundation_id, target_quals] =
  897. context.types().GetTransitiveUnqualifiedAdaptedType(target.type_id);
  898. auto [value_foundation_id, value_quals] =
  899. context.types().GetTransitiveUnqualifiedAdaptedType(value_type_id);
  900. if (target_foundation_id == value_foundation_id) {
  901. auto category = SemIR::GetExprCategory(context.sem_ir(), value_id);
  902. auto added_quals = target_quals & ~value_quals;
  903. auto removed_quals = value_quals & ~target_quals;
  904. if (CanAddQualifiers(added_quals, category) &&
  905. CanRemoveQualifiers(
  906. removed_quals, category,
  907. target.kind == ConversionTarget::ExplicitUnsafeAs)) {
  908. // For a struct or tuple literal, perform a category conversion if
  909. // necessary.
  910. if (category == SemIR::ExprCategory::Mixed) {
  911. value_id = PerformBuiltinConversion(context, loc_id, value_id,
  912. {.kind = ConversionTarget::Value,
  913. .type_id = value_type_id,
  914. .diagnose = target.diagnose});
  915. }
  916. // `MaybeUnformed(T)` has a pointer value representation, and `T` might
  917. // not, so convert as needed when removing `MaybeUnformed`.
  918. bool need_value_binding = false;
  919. if ((removed_quals & SemIR::TypeQualifiers::MaybeUnformed) !=
  920. SemIR::TypeQualifiers::None &&
  921. category == SemIR::ExprCategory::Value) {
  922. value_id = AddInst<SemIR::ValueAsRef>(
  923. context, loc_id,
  924. {.type_id = value_type_id, .value_id = value_id});
  925. need_value_binding = true;
  926. }
  927. value_id = AddInst<SemIR::AsCompatible>(
  928. context, loc_id,
  929. {.type_id = target.type_id, .source_id = value_id});
  930. if (need_value_binding) {
  931. value_id = AddInst<SemIR::BindValue>(
  932. context, loc_id,
  933. {.type_id = target.type_id, .value_id = value_id});
  934. }
  935. return value_id;
  936. } else {
  937. // TODO: Produce a custom diagnostic explaining that we can't perform
  938. // this conversion due to the change in qualifiers and/or the expression
  939. // category.
  940. }
  941. }
  942. }
  943. // A tuple (T1, T2, ..., Tn) converts to (U1, U2, ..., Un) if each Ti
  944. // converts to Ui.
  945. if (auto target_tuple_type = target_type_inst.TryAs<SemIR::TupleType>()) {
  946. if (auto src_tuple_type =
  947. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  948. return ConvertTupleToTuple(context, *src_tuple_type, *target_tuple_type,
  949. value_id, target);
  950. }
  951. }
  952. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to
  953. // {.f_p(1): U_p(1), .f_p(2): U_p(2), ..., .f_p(n): U_p(n)} if
  954. // (p(1), ..., p(n)) is a permutation of (1, ..., n) and each Ti converts
  955. // to Ui.
  956. if (auto target_struct_type = target_type_inst.TryAs<SemIR::StructType>()) {
  957. if (auto src_struct_type =
  958. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  959. return ConvertStructToStruct(context, *src_struct_type,
  960. *target_struct_type, value_id, target);
  961. }
  962. }
  963. // No other conversions apply when the source and destination types are the
  964. // same.
  965. if (value_type_id == target.type_id) {
  966. return value_id;
  967. }
  968. // A tuple (T1, T2, ..., Tn) converts to array(T, n) if each Ti converts to T.
  969. if (auto target_array_type = target_type_inst.TryAs<SemIR::ArrayType>()) {
  970. if (auto src_tuple_type =
  971. sem_ir.types().TryGetAs<SemIR::TupleType>(value_type_id)) {
  972. return ConvertTupleToArray(context, *src_tuple_type, *target_array_type,
  973. value_id, target);
  974. }
  975. }
  976. // A struct {.f_1: T_1, .f_2: T_2, ..., .f_n: T_n} converts to a class type
  977. // if it converts to the struct type that is the class's representation type
  978. // (a struct with the same fields as the class, plus a base field where
  979. // relevant).
  980. if (auto target_class_type = target_type_inst.TryAs<SemIR::ClassType>()) {
  981. if (auto src_struct_type =
  982. sem_ir.types().TryGetAs<SemIR::StructType>(value_type_id)) {
  983. if (!context.classes()
  984. .Get(target_class_type->class_id)
  985. .adapt_id.has_value()) {
  986. return ConvertStructToClass(context, *src_struct_type,
  987. *target_class_type, value_id, target,
  988. vtable_class_type);
  989. }
  990. }
  991. // An expression of type T converts to U if T is a class derived from U.
  992. if (auto path = ComputeInheritancePath(context, loc_id, value_type_id,
  993. target.type_id);
  994. path && !path->empty()) {
  995. return ConvertDerivedToBase(context, loc_id, value_id, *path);
  996. }
  997. }
  998. // A pointer T* converts to [qualified] U* if T is the same as U, or is a
  999. // class derived from U.
  1000. if (auto target_pointer_type = target_type_inst.TryAs<SemIR::PointerType>()) {
  1001. if (auto src_pointer_type =
  1002. sem_ir.types().TryGetAs<SemIR::PointerType>(value_type_id)) {
  1003. auto target_pointee_id = context.types().GetTypeIdForTypeInstId(
  1004. target_pointer_type->pointee_id);
  1005. auto src_pointee_id =
  1006. context.types().GetTypeIdForTypeInstId(src_pointer_type->pointee_id);
  1007. // Try to complete the pointee types so that we can walk through adapters
  1008. // to their adapted types.
  1009. TryToCompleteType(context, target_pointee_id, loc_id);
  1010. TryToCompleteType(context, src_pointee_id, loc_id);
  1011. auto [unqual_target_pointee_type_id, target_quals] =
  1012. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(target_pointee_id);
  1013. auto [unqual_src_pointee_type_id, src_quals] =
  1014. sem_ir.types().GetTransitiveUnqualifiedAdaptedType(src_pointee_id);
  1015. // If the qualifiers are incompatible, we can't perform a conversion,
  1016. // except with `unsafe as`.
  1017. if ((src_quals & ~target_quals) != SemIR::TypeQualifiers::None &&
  1018. target.kind != ConversionTarget::ExplicitUnsafeAs) {
  1019. // TODO: Consider producing a custom diagnostic here for a cast that
  1020. // discards constness.
  1021. return value_id;
  1022. }
  1023. if (unqual_target_pointee_type_id != unqual_src_pointee_type_id) {
  1024. // If there's an inheritance path from target to source, this is a
  1025. // derived to base conversion.
  1026. if (auto path = ComputeInheritancePath(context, loc_id,
  1027. unqual_src_pointee_type_id,
  1028. unqual_target_pointee_type_id);
  1029. path && !path->empty()) {
  1030. value_id = ConvertDerivedPointerToBasePointer(
  1031. context, loc_id, *src_pointer_type, target.type_id, value_id,
  1032. *path);
  1033. } else {
  1034. // No conversion was possible.
  1035. return value_id;
  1036. }
  1037. }
  1038. // Perform a compatible conversion to add any new qualifiers.
  1039. if (src_quals != target_quals) {
  1040. return AddInst<SemIR::AsCompatible>(
  1041. context, loc_id,
  1042. {.type_id = target.type_id, .source_id = value_id});
  1043. }
  1044. return value_id;
  1045. }
  1046. }
  1047. if (target.type_id == SemIR::TypeType::TypeId ||
  1048. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1049. auto type_value_id = SemIR::InstId::None;
  1050. // A tuple of types converts to type `type`.
  1051. // TODO: This should apply even for non-literal tuples.
  1052. if (auto tuple_literal = value.TryAs<SemIR::TupleLiteral>()) {
  1053. llvm::SmallVector<SemIR::InstId> type_inst_ids;
  1054. for (auto tuple_inst_id :
  1055. sem_ir.inst_blocks().Get(tuple_literal->elements_id)) {
  1056. // TODO: This call recurses back into conversion. Switch to an
  1057. // iterative approach.
  1058. type_inst_ids.push_back(
  1059. ExprAsType(context, loc_id, tuple_inst_id, target.diagnose)
  1060. .inst_id);
  1061. }
  1062. // TODO: Should we add this as an instruction? It will contain references
  1063. // to local InstIds.
  1064. auto tuple_type_id = GetTupleType(context, type_inst_ids);
  1065. type_value_id = sem_ir.types().GetInstId(tuple_type_id);
  1066. }
  1067. // `{}` converts to `{} as type`.
  1068. // TODO: This conversion should also be performed for a non-literal value
  1069. // of type `{}`.
  1070. if (auto struct_literal = value.TryAs<SemIR::StructLiteral>();
  1071. struct_literal &&
  1072. struct_literal->elements_id == SemIR::InstBlockId::Empty) {
  1073. type_value_id = sem_ir.types().GetInstId(value_type_id);
  1074. }
  1075. if (type_value_id != SemIR::InstId::None) {
  1076. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1077. // Use the converted `TypeType` value for converting to a facet.
  1078. value_id = type_value_id;
  1079. value_type_id = SemIR::TypeType::TypeId;
  1080. } else {
  1081. // We wanted a `TypeType`, and we've done that.
  1082. return type_value_id;
  1083. }
  1084. }
  1085. }
  1086. // FacetType converts to Type by wrapping the facet value in
  1087. // FacetAccessType.
  1088. if (target.type_id == SemIR::TypeType::TypeId &&
  1089. sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1090. return AddInst<SemIR::FacetAccessType>(
  1091. context, loc_id,
  1092. {.type_id = target.type_id, .facet_value_inst_id = value_id});
  1093. }
  1094. // Type values can convert to facet values, and facet values can convert to
  1095. // other facet values, as long as they satisfy the required interfaces of the
  1096. // target `FacetType`.
  1097. if (sem_ir.types().Is<SemIR::FacetType>(target.type_id) &&
  1098. (sem_ir.types().Is<SemIR::TypeType>(value_type_id) ||
  1099. sem_ir.types().Is<SemIR::FacetType>(value_type_id))) {
  1100. // The value is a type or facet value, so it has a constant value. We get
  1101. // that to unwrap things like NameRef and get to the underlying type or
  1102. // facet value instruction so that we can use `TryGetAs`.
  1103. auto const_value_id = sem_ir.constant_values().GetConstantInstId(value_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 (!const_value_id.has_value()) {
  1107. context.TODO(loc_id, "conversion of runtime facet value");
  1108. const_value_id = SemIR::ErrorInst::InstId;
  1109. }
  1110. if (auto facet_access_type_inst =
  1111. sem_ir.insts().TryGetAs<SemIR::FacetAccessType>(const_value_id)) {
  1112. // Conversion from a `FacetAccessType` to a `FacetValue` of the target
  1113. // `FacetType` if the instruction in the `FacetAccessType` is of a
  1114. // `FacetType` that satisfies the requirements of the target `FacetType`.
  1115. // If the `FacetType` exactly matches the target `FacetType` then we can
  1116. // shortcut and use that value, and avoid impl lookup.
  1117. auto facet_value_inst_id = facet_access_type_inst->facet_value_inst_id;
  1118. if (sem_ir.insts().Get(facet_value_inst_id).type_id() == target.type_id) {
  1119. return facet_value_inst_id;
  1120. }
  1121. }
  1122. // Conversion from a facet value (which has type `FacetType`) or a type
  1123. // value (which has type `TypeType`) to a facet value. We can do this if the
  1124. // type satisfies the requirements of the target `FacetType`, as determined
  1125. // by finding impl witnesses for the target FacetType.
  1126. auto lookup_result = LookupImplWitness(
  1127. context, loc_id, sem_ir.constant_values().Get(const_value_id),
  1128. sem_ir.types().GetConstantId(target.type_id));
  1129. if (lookup_result.has_value()) {
  1130. if (lookup_result.has_error_value()) {
  1131. return SemIR::ErrorInst::InstId;
  1132. } else {
  1133. // We bind the input value to the target `FacetType` with a
  1134. // `FacetValue`, which requires an instruction of type `TypeType`. So if
  1135. // we are converting from a facet value, we get its `type` via an extra
  1136. // `FacetAccessType` instruction.
  1137. auto type_inst_id = SemIR::TypeInstId::None;
  1138. if (sem_ir.types().Is<SemIR::FacetType>(value_type_id)) {
  1139. type_inst_id = AddTypeInst<SemIR::FacetAccessType>(
  1140. context, loc_id,
  1141. {.type_id = SemIR::TypeType::TypeId,
  1142. .facet_value_inst_id = const_value_id});
  1143. } else {
  1144. type_inst_id = context.types().GetAsTypeInstId(const_value_id);
  1145. }
  1146. // Note that `FacetValue`'s type is the same `FacetType` that was used
  1147. // to construct the set of witnesses, ie. the query to
  1148. // `LookupImplWitness()`. This ensures that the witnesses are in the
  1149. // same order as the `required_interfaces()` in the `FacetValue`'s type.
  1150. return AddInst<SemIR::FacetValue>(
  1151. context, loc_id,
  1152. {.type_id = target.type_id,
  1153. .type_inst_id = type_inst_id,
  1154. .witnesses_block_id = lookup_result.inst_block_id()});
  1155. }
  1156. } else {
  1157. // If impl lookup fails, don't keep looking for another way to convert.
  1158. // See https://github.com/carbon-language/carbon-lang/issues/5122.
  1159. // TODO: Pass this function into `LookupImplWitness` so it can construct
  1160. // the error add notes explaining failure.
  1161. if (target.diagnose) {
  1162. DiagnoseConversionFailureToConstraintValue(context, loc_id, value_id,
  1163. target.type_id);
  1164. }
  1165. return SemIR::ErrorInst::InstId;
  1166. }
  1167. }
  1168. // No builtin conversion applies.
  1169. return value_id;
  1170. }
  1171. // Determine whether this is a C++ enum type.
  1172. // TODO: This should be removed once we can properly add a `Copy` impl for C++
  1173. // enum types.
  1174. static auto IsCppEnum(Context& context, SemIR::TypeId type_id) -> bool {
  1175. auto class_type = context.types().TryGetAs<SemIR::ClassType>(type_id);
  1176. if (!class_type) {
  1177. return false;
  1178. }
  1179. // A C++-imported class type that is an adapter is an enum.
  1180. auto& class_info = context.classes().Get(class_type->class_id);
  1181. return class_info.adapt_id.has_value() &&
  1182. context.name_scopes().Get(class_info.scope_id).is_cpp_scope();
  1183. }
  1184. // Given a value expression, form a corresponding initializer that copies from
  1185. // that value to the specified target, if it is possible to do so.
  1186. static auto PerformCopy(Context& context, SemIR::InstId expr_id,
  1187. ConversionTarget& target) -> SemIR::InstId {
  1188. // TODO: We don't have a mechanism yet to generate `Copy` impls for each enum
  1189. // type imported from C++. For now we fake it by providing a direct copy.
  1190. auto type_id = context.insts().Get(expr_id).type_id();
  1191. if (IsCppEnum(context, type_id)) {
  1192. return expr_id;
  1193. }
  1194. auto copy_id = BuildUnaryOperator(
  1195. context, SemIR::LocId(expr_id), {"Copy"}, expr_id, [&] {
  1196. if (!target.diagnose) {
  1197. return context.emitter().BuildSuppressed();
  1198. }
  1199. CARBON_DIAGNOSTIC(CopyOfUncopyableType, Error,
  1200. "cannot copy value of type {0}", TypeOfInstId);
  1201. return context.emitter().Build(expr_id, CopyOfUncopyableType, expr_id);
  1202. });
  1203. MarkInitializerFor(context.sem_ir(), copy_id, target);
  1204. return copy_id;
  1205. }
  1206. // Convert a value expression so that it can be used to initialize a C++ thunk
  1207. // parameter.
  1208. static auto ConvertValueForCppThunkRef(Context& context, SemIR::InstId expr_id)
  1209. -> SemIR::InstId {
  1210. auto expr = context.insts().Get(expr_id);
  1211. // If the expression has a pointer value representation, extract that and use
  1212. // it directly.
  1213. if (SemIR::ValueRepr::ForType(context.sem_ir(), expr.type_id()).kind ==
  1214. SemIR::ValueRepr::Pointer) {
  1215. return AddInst<SemIR::ValueAsRef>(
  1216. context, SemIR::LocId(expr_id),
  1217. {.type_id = expr.type_id(), .value_id = expr_id});
  1218. }
  1219. // Otherwise, we need a temporary to pass as the thunk argument. Create a copy
  1220. // and initialize a temporary from it.
  1221. auto temporary_id = AddInst<SemIR::TemporaryStorage>(
  1222. context, SemIR::LocId(expr_id), {.type_id = expr.type_id()});
  1223. expr_id = Initialize(context, SemIR::LocId(expr_id), temporary_id, expr_id);
  1224. return AddInstWithCleanup<SemIR::Temporary>(context, SemIR::LocId(expr_id),
  1225. {.type_id = expr.type_id(),
  1226. .storage_id = temporary_id,
  1227. .init_id = expr_id});
  1228. }
  1229. // Returns the Core interface name to use for a given kind of conversion.
  1230. static auto GetConversionInterfaceName(ConversionTarget::Kind kind)
  1231. -> llvm::StringLiteral {
  1232. switch (kind) {
  1233. case ConversionTarget::ExplicitAs:
  1234. return "As";
  1235. case ConversionTarget::ExplicitUnsafeAs:
  1236. return "UnsafeAs";
  1237. default:
  1238. return "ImplicitAs";
  1239. }
  1240. }
  1241. auto PerformAction(Context& context, SemIR::LocId loc_id,
  1242. SemIR::ConvertToValueAction action) -> SemIR::InstId {
  1243. return Convert(context, loc_id, action.inst_id,
  1244. {.kind = ConversionTarget::Value,
  1245. .type_id = context.types().GetTypeIdForTypeInstId(
  1246. action.target_type_inst_id)});
  1247. }
  1248. auto Convert(Context& context, SemIR::LocId loc_id, SemIR::InstId expr_id,
  1249. ConversionTarget target, SemIR::ClassType* vtable_class_type)
  1250. -> SemIR::InstId {
  1251. auto& sem_ir = context.sem_ir();
  1252. auto orig_expr_id = expr_id;
  1253. // Start by making sure both sides are non-errors. If any part is an error,
  1254. // the result is an error and we shouldn't diagnose.
  1255. if (sem_ir.insts().Get(expr_id).type_id() == SemIR::ErrorInst::TypeId ||
  1256. target.type_id == SemIR::ErrorInst::TypeId) {
  1257. return SemIR::ErrorInst::InstId;
  1258. }
  1259. if (SemIR::GetExprCategory(sem_ir, expr_id) == SemIR::ExprCategory::NotExpr) {
  1260. // TODO: We currently encounter this for use of namespaces and functions.
  1261. // We should provide a better diagnostic for inappropriate use of
  1262. // namespace names, and allow use of functions as values.
  1263. if (target.diagnose) {
  1264. CARBON_DIAGNOSTIC(UseOfNonExprAsValue, Error,
  1265. "expression cannot be used as a value");
  1266. context.emitter().Emit(expr_id, UseOfNonExprAsValue);
  1267. }
  1268. return SemIR::ErrorInst::InstId;
  1269. }
  1270. // We can only perform initialization for complete, non-abstract types. Note
  1271. // that `RequireConcreteType` returns true for facet types, since their
  1272. // representation is fixed. This allows us to support using the `Self` of an
  1273. // interface inside its definition.
  1274. if (!RequireConcreteType(
  1275. context, target.type_id, loc_id,
  1276. [&] {
  1277. CARBON_CHECK(!target.is_initializer(),
  1278. "Initialization of incomplete types is expected to be "
  1279. "caught elsewhere.");
  1280. if (!target.diagnose) {
  1281. return context.emitter().BuildSuppressed();
  1282. }
  1283. CARBON_DIAGNOSTIC(IncompleteTypeInValueConversion, Error,
  1284. "forming value of incomplete type {0}",
  1285. SemIR::TypeId);
  1286. CARBON_DIAGNOSTIC(IncompleteTypeInConversion, Error,
  1287. "invalid use of incomplete type {0}",
  1288. SemIR::TypeId);
  1289. return context.emitter().Build(
  1290. loc_id,
  1291. target.kind == ConversionTarget::Value
  1292. ? IncompleteTypeInValueConversion
  1293. : IncompleteTypeInConversion,
  1294. target.type_id);
  1295. },
  1296. [&] {
  1297. if (!target.diagnose || !target.is_initializer()) {
  1298. return context.emitter().BuildSuppressed();
  1299. }
  1300. CARBON_DIAGNOSTIC(AbstractTypeInInit, Error,
  1301. "initialization of abstract type {0}",
  1302. SemIR::TypeId);
  1303. return context.emitter().Build(loc_id, AbstractTypeInInit,
  1304. target.type_id);
  1305. })) {
  1306. return SemIR::ErrorInst::InstId;
  1307. }
  1308. // The source type doesn't need to be complete, but its completeness can
  1309. // affect the result. For example, we don't know what type it adapts or
  1310. // derives from unless it's complete.
  1311. // TODO: Is there a risk of coherence problems if the source type is
  1312. // incomplete, but a conversion would have been possible or would have behaved
  1313. // differently if it were complete?
  1314. TryToCompleteType(context, context.insts().Get(expr_id).type_id(), loc_id);
  1315. // Check whether any builtin conversion applies.
  1316. expr_id = PerformBuiltinConversion(context, loc_id, expr_id, target,
  1317. vtable_class_type);
  1318. if (expr_id == SemIR::ErrorInst::InstId) {
  1319. return expr_id;
  1320. }
  1321. // Defer the action if it's dependent. We do this now rather than before
  1322. // attempting any conversion so that we can still perform builtin conversions
  1323. // on dependent arguments. This matters for things like converting a
  1324. // `template T:! SomeInterface` to `type`, where it's important to form a
  1325. // `FacetAccessType` when checking the template. But when running the action
  1326. // later, we need to try builtin conversions again, because one may apply that
  1327. // didn't apply in the template definition.
  1328. // TODO: Support this for targets other than `Value`.
  1329. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id &&
  1330. target.kind == ConversionTarget::Value &&
  1331. (OperandIsDependent(context, expr_id) ||
  1332. OperandIsDependent(context, target.type_id))) {
  1333. auto target_type_inst_id = context.types().GetInstId(target.type_id);
  1334. return AddDependentActionSplice(
  1335. context, loc_id,
  1336. SemIR::ConvertToValueAction{.type_id = SemIR::InstType::TypeId,
  1337. .inst_id = expr_id,
  1338. .target_type_inst_id = target_type_inst_id},
  1339. target_type_inst_id);
  1340. }
  1341. // If this is not a builtin conversion, try an `ImplicitAs` conversion.
  1342. if (sem_ir.insts().Get(expr_id).type_id() != target.type_id) {
  1343. SemIR::InstId interface_args[] = {
  1344. context.types().GetInstId(target.type_id)};
  1345. Operator op = {
  1346. .interface_name = GetConversionInterfaceName(target.kind),
  1347. .interface_args_ref = interface_args,
  1348. .op_name = "Convert",
  1349. };
  1350. expr_id = BuildUnaryOperator(context, loc_id, op, expr_id, [&] {
  1351. if (!target.diagnose) {
  1352. return context.emitter().BuildSuppressed();
  1353. }
  1354. int target_kind_for_diag =
  1355. target.kind == ConversionTarget::ExplicitAs ? 1
  1356. : target.kind == ConversionTarget::ExplicitUnsafeAs ? 2
  1357. : 0;
  1358. if (target.type_id == SemIR::TypeType::TypeId ||
  1359. sem_ir.types().Is<SemIR::FacetType>(target.type_id)) {
  1360. CARBON_DIAGNOSTIC(
  1361. ConversionFailureNonTypeToFacet, Error,
  1362. "cannot{0:=0: implicitly|:} convert non-type value of type {1} "
  1363. "{2:to|into type implementing} {3}"
  1364. "{0:=1: with `as`|=2: with `unsafe as`|:}",
  1365. Diagnostics::IntAsSelect, TypeOfInstId, Diagnostics::BoolAsSelect,
  1366. SemIR::TypeId);
  1367. return context.emitter().Build(
  1368. loc_id, ConversionFailureNonTypeToFacet, target_kind_for_diag,
  1369. expr_id, target.type_id == SemIR::TypeType::TypeId, target.type_id);
  1370. } else {
  1371. CARBON_DIAGNOSTIC(
  1372. ConversionFailure, Error,
  1373. "cannot{0:=0: implicitly|:} convert expression of type "
  1374. "{1} to {2}{0:=1: with `as`|=2: with `unsafe as`|:}",
  1375. Diagnostics::IntAsSelect, TypeOfInstId, SemIR::TypeId);
  1376. return context.emitter().Build(loc_id, ConversionFailure,
  1377. target_kind_for_diag, expr_id,
  1378. target.type_id);
  1379. }
  1380. });
  1381. // Pull a value directly out of the initializer if possible and wanted.
  1382. if (expr_id != SemIR::ErrorInst::InstId &&
  1383. CanUseValueOfInitializer(sem_ir, target.type_id, target.kind)) {
  1384. expr_id = AddInst<SemIR::ValueOfInitializer>(
  1385. context, loc_id, {.type_id = target.type_id, .init_id = expr_id});
  1386. }
  1387. }
  1388. // Track that we performed a type conversion, if we did so.
  1389. if (orig_expr_id != expr_id) {
  1390. expr_id = AddInst<SemIR::Converted>(context, loc_id,
  1391. {.type_id = target.type_id,
  1392. .original_id = orig_expr_id,
  1393. .result_id = expr_id});
  1394. }
  1395. // For `as`, don't perform any value category conversions. In particular, an
  1396. // identity conversion shouldn't change the expression category.
  1397. if (target.is_explicit_as()) {
  1398. return expr_id;
  1399. }
  1400. // Now perform any necessary value category conversions.
  1401. switch (SemIR::GetExprCategory(sem_ir, expr_id)) {
  1402. case SemIR::ExprCategory::NotExpr:
  1403. case SemIR::ExprCategory::Mixed:
  1404. CARBON_FATAL("Unexpected expression {0} after builtin conversions",
  1405. sem_ir.insts().Get(expr_id));
  1406. case SemIR::ExprCategory::Error:
  1407. return SemIR::ErrorInst::InstId;
  1408. case SemIR::ExprCategory::Initializing:
  1409. if (target.is_initializer()) {
  1410. if (orig_expr_id == expr_id) {
  1411. // Don't fill in the return slot if we created the expression through
  1412. // a conversion. In that case, we will have created it with the
  1413. // target already set.
  1414. // TODO: Find a better way to track whether we need to do this.
  1415. MarkInitializerFor(sem_ir, expr_id, target);
  1416. }
  1417. break;
  1418. }
  1419. // Commit to using a temporary for this initializing expression.
  1420. // TODO: Don't create a temporary if the initializing representation
  1421. // is already a value representation.
  1422. // TODO: If the target is DurableRef, materialize a VarStorage instead of
  1423. // a TemporaryStorage to lifetime-extend.
  1424. expr_id = FinalizeTemporary(context, expr_id,
  1425. target.kind == ConversionTarget::Discarded);
  1426. // We now have an ephemeral reference.
  1427. [[fallthrough]];
  1428. case SemIR::ExprCategory::DurableRef:
  1429. if (target.kind == ConversionTarget::DurableRef) {
  1430. break;
  1431. }
  1432. [[fallthrough]];
  1433. case SemIR::ExprCategory::EphemeralRef:
  1434. // If a reference expression is an acceptable result, we're done.
  1435. if (target.kind == ConversionTarget::ValueOrRef ||
  1436. target.kind == ConversionTarget::Discarded ||
  1437. target.kind == ConversionTarget::CppThunkRef) {
  1438. break;
  1439. }
  1440. // If we have a reference and don't want one, form a value binding.
  1441. // TODO: Support types with custom value representations.
  1442. expr_id = AddInst<SemIR::BindValue>(
  1443. context, SemIR::LocId(expr_id),
  1444. {.type_id = target.type_id, .value_id = expr_id});
  1445. // We now have a value expression.
  1446. [[fallthrough]];
  1447. case SemIR::ExprCategory::Value:
  1448. if (target.kind == ConversionTarget::DurableRef) {
  1449. if (target.diagnose) {
  1450. CARBON_DIAGNOSTIC(ConversionFailureNonRefToRef, Error,
  1451. "cannot bind durable reference to non-reference "
  1452. "value of type {0}",
  1453. SemIR::TypeId);
  1454. context.emitter().Emit(loc_id, ConversionFailureNonRefToRef,
  1455. target.type_id);
  1456. }
  1457. return SemIR::ErrorInst::InstId;
  1458. }
  1459. // When initializing from a value, perform a copy.
  1460. if (target.is_initializer()) {
  1461. expr_id = PerformCopy(context, expr_id, target);
  1462. }
  1463. // When initializing a C++ thunk parameter, form a reference, creating a
  1464. // temporary if needed.
  1465. if (target.kind == ConversionTarget::CppThunkRef) {
  1466. expr_id = ConvertValueForCppThunkRef(context, expr_id);
  1467. }
  1468. break;
  1469. }
  1470. // Perform a final destination store, if necessary.
  1471. if (target.kind == ConversionTarget::FullInitializer) {
  1472. if (auto init_rep = SemIR::InitRepr::ForType(sem_ir, target.type_id);
  1473. init_rep.MightBeByCopy()) {
  1474. target.init_block->InsertHere();
  1475. expr_id = AddInst<SemIR::InitializeFrom>(context, loc_id,
  1476. {.type_id = target.type_id,
  1477. .src_id = expr_id,
  1478. .dest_id = target.init_id});
  1479. }
  1480. }
  1481. return expr_id;
  1482. }
  1483. auto Initialize(Context& context, SemIR::LocId loc_id, SemIR::InstId target_id,
  1484. SemIR::InstId value_id) -> SemIR::InstId {
  1485. PendingBlock target_block(&context);
  1486. return Convert(context, loc_id, value_id,
  1487. {.kind = ConversionTarget::Initializer,
  1488. .type_id = context.insts().Get(target_id).type_id(),
  1489. .init_id = target_id,
  1490. .init_block = &target_block});
  1491. }
  1492. auto ConvertToValueExpr(Context& context, SemIR::InstId expr_id)
  1493. -> SemIR::InstId {
  1494. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1495. {.kind = ConversionTarget::Value,
  1496. .type_id = context.insts().Get(expr_id).type_id()});
  1497. }
  1498. auto ConvertToValueOrRefExpr(Context& context, SemIR::InstId expr_id)
  1499. -> SemIR::InstId {
  1500. return Convert(context, SemIR::LocId(expr_id), expr_id,
  1501. {.kind = ConversionTarget::ValueOrRef,
  1502. .type_id = context.insts().Get(expr_id).type_id()});
  1503. }
  1504. auto ConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1505. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1506. -> SemIR::InstId {
  1507. return Convert(context, loc_id, expr_id,
  1508. {.kind = ConversionTarget::Value, .type_id = type_id});
  1509. }
  1510. auto ConvertToValueOrRefOfType(Context& context, SemIR::LocId loc_id,
  1511. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1512. -> SemIR::InstId {
  1513. return Convert(context, loc_id, expr_id,
  1514. {.kind = ConversionTarget::ValueOrRef, .type_id = type_id});
  1515. }
  1516. // Like ConvertToValueOfType but failure to convert does not result in
  1517. // diagnostics. An ErrorInst instruction is still returned on failure.
  1518. auto TryConvertToValueOfType(Context& context, SemIR::LocId loc_id,
  1519. SemIR::InstId expr_id, SemIR::TypeId type_id)
  1520. -> SemIR::InstId {
  1521. return Convert(
  1522. context, loc_id, expr_id,
  1523. {.kind = ConversionTarget::Value, .type_id = type_id, .diagnose = false});
  1524. }
  1525. auto ConvertToBoolValue(Context& context, SemIR::LocId loc_id,
  1526. SemIR::InstId value_id) -> SemIR::InstId {
  1527. return ConvertToValueOfType(
  1528. context, loc_id, value_id,
  1529. GetSingletonType(context, SemIR::BoolType::TypeInstId));
  1530. }
  1531. auto ConvertForExplicitAs(Context& context, Parse::NodeId as_node,
  1532. SemIR::InstId value_id, SemIR::TypeId type_id,
  1533. bool unsafe) -> SemIR::InstId {
  1534. return Convert(context, as_node, value_id,
  1535. {.kind = unsafe ? ConversionTarget::ExplicitUnsafeAs
  1536. : ConversionTarget::ExplicitAs,
  1537. .type_id = type_id});
  1538. }
  1539. // TODO: Consider moving this to pattern_match.h.
  1540. auto ConvertCallArgs(Context& context, SemIR::LocId call_loc_id,
  1541. SemIR::InstId self_id,
  1542. llvm::ArrayRef<SemIR::InstId> arg_refs,
  1543. SemIR::InstId return_slot_arg_id,
  1544. const SemIR::Function& callee,
  1545. SemIR::SpecificId callee_specific_id)
  1546. -> SemIR::InstBlockId {
  1547. auto param_patterns =
  1548. context.inst_blocks().GetOrEmpty(callee.param_patterns_id);
  1549. auto return_slot_pattern_id = callee.return_slot_pattern_id;
  1550. // The caller should have ensured this callee has the right arity.
  1551. CARBON_CHECK(arg_refs.size() == param_patterns.size());
  1552. if (callee.self_param_id.has_value() && !self_id.has_value()) {
  1553. CARBON_DIAGNOSTIC(MissingObjectInMethodCall, Error,
  1554. "missing object argument in method call");
  1555. CARBON_DIAGNOSTIC(InCallToFunction, Note, "calling function declared here");
  1556. context.emitter()
  1557. .Build(call_loc_id, MissingObjectInMethodCall)
  1558. .Note(callee.latest_decl_id(), InCallToFunction)
  1559. .Emit();
  1560. self_id = SemIR::ErrorInst::InstId;
  1561. }
  1562. return CallerPatternMatch(context, callee_specific_id, callee.self_param_id,
  1563. callee.param_patterns_id, return_slot_pattern_id,
  1564. self_id, arg_refs, return_slot_arg_id);
  1565. }
  1566. auto ExprAsType(Context& context, SemIR::LocId loc_id, SemIR::InstId value_id,
  1567. bool diagnose) -> TypeExpr {
  1568. auto type_inst_id =
  1569. ConvertToValueOfType(context, loc_id, value_id, SemIR::TypeType::TypeId);
  1570. if (type_inst_id == SemIR::ErrorInst::InstId) {
  1571. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1572. .type_id = SemIR::ErrorInst::TypeId};
  1573. }
  1574. auto type_const_id = context.constant_values().Get(type_inst_id);
  1575. if (!type_const_id.is_constant()) {
  1576. if (diagnose) {
  1577. CARBON_DIAGNOSTIC(TypeExprEvaluationFailure, Error,
  1578. "cannot evaluate type expression");
  1579. context.emitter().Emit(loc_id, TypeExprEvaluationFailure);
  1580. }
  1581. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1582. .type_id = SemIR::ErrorInst::TypeId};
  1583. }
  1584. return {.inst_id = context.types().GetAsTypeInstId(type_inst_id),
  1585. .type_id = context.types().GetTypeIdForTypeConstantId(type_const_id)};
  1586. }
  1587. auto DiscardExpr(Context& context, SemIR::InstId expr_id) -> void {
  1588. // If we discard an initializing expression, convert it to a value or
  1589. // reference so that it has something to initialize.
  1590. auto expr = context.insts().Get(expr_id);
  1591. Convert(context, SemIR::LocId(expr_id), expr_id,
  1592. {.kind = ConversionTarget::Discarded, .type_id = expr.type_id()});
  1593. // TODO: This will eventually need to do some "do not discard" analysis.
  1594. }
  1595. } // namespace Carbon::Check
  1596. // NOLINTEND(misc-no-recursion)